HTML.pm 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  1. package Trog::Routes::HTML;
  2. use strict;
  3. use warnings;
  4. no warnings qw{experimental once};
  5. use feature qw{signatures state};
  6. use Errno qw{ENOENT};
  7. use File::Touch();
  8. use List::Util();
  9. use List::MoreUtils();
  10. use Capture::Tiny qw{capture};
  11. use HTML::SocialMeta;
  12. use Encode qw{encode_utf8};
  13. use IO::Compress::Gzip;
  14. use Path::Tiny();
  15. use File::Basename qw{dirname};
  16. use URI();
  17. use FindBin::libs;
  18. use Trog::Log qw{:all};
  19. use Trog::Utils;
  20. use Trog::Config;
  21. use Trog::Auth;
  22. use Trog::Data;
  23. use Trog::FileHandler;
  24. use Trog::Themes;
  25. use Trog::Renderer;
  26. use Trog::Component::EmojiPicker;
  27. my $conf = Trog::Config::get();
  28. our $landing_page = 'default.tx';
  29. our $htmltitle = 'title.tx';
  30. our $midtitle = 'midtitle.tx';
  31. our $rightbar = 'rightbar.tx';
  32. our $leftbar = 'leftbar.tx';
  33. our $topbar = 'topbar.tx';
  34. our $footbar = 'footbar.tx';
  35. # Note to maintainers: never ever remove backends from this list.
  36. # the auth => 1 is a crucial protection.
  37. our %routes = (
  38. default => {
  39. callback => \&Trog::Routes::HTML::setup,
  40. },
  41. '/index' => {
  42. method => 'GET',
  43. callback => \&Trog::Routes::HTML::index,
  44. },
  45. #Deal with most indexDocument directives interfering with proxied requests to /
  46. #TODO replace with alias routes
  47. '/index.html' => {
  48. method => 'GET',
  49. callback => \&Trog::Routes::HTML::index,
  50. },
  51. '/index.php' => {
  52. method => 'GET',
  53. callback => \&Trog::Routes::HTML::index,
  54. },
  55. # This should only be enabled to debug
  56. # '/setup' => {
  57. # method => 'GET',
  58. # callback => \&Trog::Routes::HTML::setup,
  59. # },
  60. '/login' => {
  61. method => 'GET',
  62. callback => \&Trog::Routes::HTML::login,
  63. },
  64. '/logout' => {
  65. method => 'GET',
  66. callback => \&Trog::Routes::HTML::logout,
  67. },
  68. '/auth' => {
  69. method => 'POST',
  70. callback => \&Trog::Routes::HTML::login,
  71. },
  72. '/totp' => {
  73. method => 'GET',
  74. auth => 1,
  75. callback => \&Trog::Routes::HTML::totp,
  76. },
  77. '/post/save' => {
  78. method => 'POST',
  79. auth => 1,
  80. callback => \&Trog::Routes::HTML::post_save,
  81. },
  82. '/post/delete' => {
  83. method => 'POST',
  84. auth => 1,
  85. callback => \&Trog::Routes::HTML::post_delete,
  86. },
  87. '/config/save' => {
  88. method => 'POST',
  89. auth => 1,
  90. callback => \&Trog::Routes::HTML::config_save,
  91. },
  92. '/themeclone' => {
  93. method => 'POST',
  94. auth => 1,
  95. callback => \&Trog::Routes::HTML::themeclone,
  96. },
  97. '/profile' => {
  98. method => 'POST',
  99. auth => 1,
  100. callback => \&Trog::Routes::HTML::profile,
  101. },
  102. '/manual' => {
  103. method => 'GET',
  104. auth => 1,
  105. callback => \&Trog::Routes::HTML::manual,
  106. },
  107. '/lib/(.*)' => {
  108. method => 'GET',
  109. auth => 1,
  110. captures => ['module'],
  111. callback => \&Trog::Routes::HTML::manual,
  112. },
  113. #TODO transform into posts?
  114. '/sitemap',
  115. => {
  116. method => 'GET',
  117. callback => \&Trog::Routes::HTML::sitemap,
  118. },
  119. '/sitemap_index.xml',
  120. => {
  121. method => 'GET',
  122. callback => \&Trog::Routes::HTML::sitemap,
  123. data => { xml => 1 },
  124. },
  125. '/sitemap_index.xml.gz',
  126. => {
  127. method => 'GET',
  128. callback => \&Trog::Routes::HTML::sitemap,
  129. data => { xml => 1, compressed => 1 },
  130. },
  131. '/sitemap/static.xml' => {
  132. method => 'GET',
  133. callback => \&Trog::Routes::HTML::sitemap,
  134. data => { xml => 1, map => 'static' },
  135. },
  136. '/sitemap/static.xml.gz' => {
  137. method => 'GET',
  138. callback => \&Trog::Routes::HTML::sitemap,
  139. data => { xml => 1, compressed => 1, map => 'static' },
  140. },
  141. '/sitemap/(.*).xml' => {
  142. method => 'GET',
  143. callback => \&Trog::Routes::HTML::sitemap,
  144. data => { xml => 1 },
  145. captures => ['map'],
  146. },
  147. '/sitemap/(.*).xml.gz' => {
  148. method => 'GET',
  149. callback => \&Trog::Routes::HTML::sitemap,
  150. data => { xml => 1, compressed => 1 },
  151. captures => ['map'],
  152. },
  153. '/robots.txt' => {
  154. method => 'GET',
  155. callback => \&Trog::Routes::HTML::robots,
  156. },
  157. '/humans.txt' => {
  158. method => 'GET',
  159. callback => \&Trog::Routes::HTML::posts,
  160. data => { tag => ['about'] },
  161. },
  162. '/styles/avatars.css' => {
  163. method => 'GET',
  164. callback => \&Trog::Routes::HTML::avatars,
  165. data => { tag => ['about'] },
  166. },
  167. '/favicon.ico' => {
  168. method => 'GET',
  169. callback => \&Trog::Routes::HTML::icon,
  170. },
  171. '/styles/rss-style.xsl' => {
  172. method => 'GET',
  173. callback => \&Trog::Routes::HTML::rss_style,
  174. },
  175. '/rss.xml' => {
  176. method => 'GET',
  177. callback => \&Trog::Routes::HTML::posts,
  178. data => { format => 'rss' },
  179. },
  180. );
  181. # Grab theme routes
  182. my $themed = 0;
  183. if ($Trog::Themes::theme_dir) {
  184. my $theme_mod = "$Trog::Themes::theme_dir/routes.pm";
  185. if ( -f "www/$theme_mod" ) {
  186. use lib 'www';
  187. require $theme_mod;
  188. @routes{ keys(%Theme::routes) } = values(%Theme::routes);
  189. $themed = 1;
  190. } else {
  191. # Use the special "default" theme
  192. require Theme;
  193. }
  194. }
  195. my $data = Trog::Data->new($conf);
  196. =head1 PRIMARY ROUTE
  197. =head2 index
  198. Implements the primary route used by all pages not behind auth.
  199. Most subsequent functions simply pass content to this function.
  200. =cut
  201. sub index ( $query, $content = '', $i_styles = [] ) {
  202. $query->{theme_dir} = $Trog::Themes::td;
  203. my $to_render = $query->{template} // $landing_page;
  204. $content ||= Trog::Renderer->render( template => $to_render, data => $query, component => 1, contenttype => 'text/html' );
  205. my @styles = ('avatars.css');
  206. if ($Trog::Themes::theme_dir) {
  207. if ( $query->{embed} ) {
  208. unshift( @styles, Trog::Themes::themed_style("embed.css") ) if -f 'www/' . Trog::Themes::themed_style("embed.css");
  209. }
  210. unshift( @styles, Trog::Themes::themed_style("screen.css") ) if -f 'www/' . Trog::Themes::themed_style("screen.css");
  211. unshift( @styles, Trog::Themes::themed_style("print.css") ) if -f 'www/' . Trog::Themes::themed_style("print.css");
  212. unshift( @styles, Trog::Themes::themed_style("structure.css") ) if -f 'www/' . Trog::Themes::themed_style("structure.css");
  213. }
  214. push( @styles, @$i_styles );
  215. #TODO allow theming of print css
  216. my @series = _get_series(0);
  217. my $title = $query->{primary_post}{title} // $query->{title} // $Theme::default_title // 'tCMS';
  218. # Handle link "unfurling" correctly
  219. my ( $default_tags, $meta_desc, $meta_tags ) = _build_social_meta( $query, $title );
  220. #Do embed content
  221. my $tmpl = $query->{embed} ? 'embed.tx' : 'index.tx';
  222. return finish_render(
  223. $tmpl,
  224. {
  225. %$query,
  226. search_lang => $data->lang(),
  227. search_help => $data->help(),
  228. theme_dir => $Trog::Themes::td,
  229. content => $content,
  230. title => $title,
  231. htmltitle => Trog::Renderer->render( template => $htmltitle, data => $query, component => 1, contenttype => 'text/html' ),
  232. midtitle => Trog::Renderer->render( template => $midtitle, data => $query, component => 1, contenttype => 'text/html' ),
  233. rightbar => Trog::Renderer->render( template => $rightbar, data => $query, component => 1, contenttype => 'text/html' ),
  234. leftbar => Trog::Renderer->render( template => $leftbar, data => $query, component => 1, contenttype => 'text/html' ),
  235. topbar => Trog::Renderer->render( template => $topbar, data => $query, component => 1, contenttype => 'text/html' ),
  236. footbar => Trog::Renderer->render( template => $footbar, data => $query, component => 1, contenttype => 'text/html' ),
  237. categories => \@series,
  238. stylesheets => \@styles,
  239. show_madeby => $Theme::show_madeby ? 1 : 0,
  240. embed => $query->{embed} ? 1 : 0,
  241. embed_video => $query->{primary_post}{is_video},
  242. default_tags => $default_tags,
  243. meta_desc => $meta_desc,
  244. meta_tags => $meta_tags,
  245. }
  246. );
  247. }
  248. sub _build_social_meta ( $query, $title ) {
  249. return ( undef, undef, undef ) unless $query->{social_meta} && $query->{route} && $query->{domain};
  250. my $default_tags = $Theme::default_tags;
  251. $default_tags .= ',' . join( ',', @{ $query->{primary_post}->{tags} } ) if $default_tags && $query->{primary_post}->{tags};
  252. my $meta_desc = $query->{primary_post}{data} // $Theme::description // "tCMS Site";
  253. $meta_desc = Trog::Utils::strip_and_trunc($meta_desc) || '';
  254. my $meta_tags = '';
  255. my $card_type = 'summary';
  256. $card_type = 'featured_image' if $query->{primary_post} && $query->{primary_post}{is_image};
  257. $card_type = 'player' if $query->{primary_post} && $query->{primary_post}{is_video};
  258. my $image = $Theme::default_image ? "https://$query->{domain}/$Trog::Themes::td/$Theme::default_image" : '';
  259. $image = "https://$query->{domain}/$query->{primary_post}{preview}" if $query->{primary_post} && $query->{primary_post}{preview};
  260. $image = "https://$query->{domain}/$query->{primary_post}{href}" if $query->{primary_post} && $query->{primary_post}{is_image};
  261. my $primary_route = "https://$query->{domain}/$query->{route}";
  262. $primary_route =~ s/[\/]+/\//g;
  263. my $display_name = $Theme::display_name // 'Another tCMS Site';
  264. my $extra_tags = '';
  265. my %sopts = (
  266. site_name => $display_name,
  267. app_name => $display_name,
  268. title => $title,
  269. description => $meta_desc,
  270. url => $primary_route,
  271. );
  272. $sopts{site} = $Theme::twitter_account if $Theme::twitter_account;
  273. $sopts{image} = $image if $image;
  274. $sopts{fb_app_id} = $Theme::fb_app_id if $Theme::fb_app_id;
  275. if ( $query->{primary_post} && $query->{primary_post}{is_video} ) {
  276. #$sopts{player} = "$primary_route?embed=1";
  277. $sopts{player} = "https://$query->{domain}/$query->{primary_post}{href}";
  278. #XXX don't hardcode this
  279. $sopts{player_width} = 1280;
  280. $sopts{player_height} = 720;
  281. $extra_tags .= "<meta property='og:video:type' content='$query->{primary_post}{content_type}' />\n";
  282. }
  283. my $social = HTML::SocialMeta->new(%sopts);
  284. $meta_tags = eval { $social->create($card_type) };
  285. $meta_tags =~ s/content="video"/content="video:other"/mg if $meta_tags;
  286. $meta_tags .= $extra_tags if $extra_tags;
  287. print STDERR "WARNING: Theme misconfigured, social media tags will not be included\n$@\n" if $Trog::Themes::theme_dir && !$meta_tags;
  288. return ( $default_tags, $meta_desc, $meta_tags );
  289. }
  290. =head1 ADMIN ROUTES
  291. These are things that issue returns other than 200, and are not directly accessible by users via any defined route.
  292. =head2 notfound, forbidden, badrequest
  293. Implements the 4XX status codes. Override templates named the same for theming this.
  294. =cut
  295. sub _generic_route ( $rname, $code, $title, $query ) {
  296. $query->{code} = $code;
  297. $query->{route} //= $rname;
  298. $query->{title} = $title;
  299. $query->{template} = "$rname.tx";
  300. INFO("$query->{method} $code $query->{route}");
  301. return Trog::Routes::HTML::index( $query );
  302. }
  303. sub notfound (@args) {
  304. return _generic_route( 'notfound', 404, "Return to sender, Address unknown", @args );
  305. }
  306. sub forbidden (@args) {
  307. return _generic_route( 'forbidden', 403, "STAY OUT YOU RED MENACE", @args );
  308. }
  309. sub badrequest (@args) {
  310. return _generic_route( 'badrequest', 400, "Bad Request", @args );
  311. }
  312. sub toolong (@args) {
  313. return _generic_route( 'toolong', 419, "URI too long", @args );
  314. }
  315. =head2 redirect, redirect_permanent, see_also
  316. Redirects to the provided page.
  317. =cut
  318. sub redirect ($to) {
  319. INFO("redirect: $to");
  320. return [ 302, [ "Location" => $to ], [''] ];
  321. }
  322. sub redirect_permanent ($to) {
  323. INFO("permanent redirect: $to");
  324. return [ 301, [ "Location" => $to ], [''] ];
  325. }
  326. sub see_also ($to) {
  327. INFO("see also: $to");
  328. return [ 303, [ "Location" => $to ], [''] ];
  329. }
  330. =head1 NORMAL ROUTES
  331. These are expected to either return a 200, or redirect to something which does.
  332. =head2 robots
  333. Return an appropriate robots.txt
  334. =cut
  335. sub robots ($query) {
  336. state $etag = "robots-" . time();
  337. return Trog::Renderer->render(
  338. contenttype => 'text/plain',
  339. template => 'robots.tx',
  340. data => {
  341. etag => $etag,
  342. %$query,
  343. },
  344. code => 200,
  345. );
  346. }
  347. =head2 setup
  348. One time setup page; should only display to the first user to visit the site which we presume to be the administrator.
  349. =cut
  350. sub setup ($query) {
  351. File::Touch::touch("config/setup");
  352. Trog::Renderer->render(
  353. template => 'notconfigured.tx',
  354. data => {
  355. title => 'tCMS Requires Setup to Continue...',
  356. stylesheets => _build_themed_styles(['notconfigured.css']),
  357. %$query,
  358. },
  359. contenttype => 'text/html',
  360. code => 200,
  361. );
  362. }
  363. =head2 totp
  364. Enable 2 factor auth via TOTP for the currently authenticated user.
  365. Returns a page with a QR code & TOTP uri for pasting into your authenticator app of choice.
  366. =cut
  367. sub totp ($query) {
  368. my $active_user = $query->{user};
  369. my $domain = $query->{domain};
  370. $query->{failure} //= -1;
  371. my ( $uri, $qr, $failure, $message ) = Trog::Auth::totp( $active_user, $domain );
  372. return Trog::Routes::HTML::index(
  373. {
  374. title => 'Enable TOTP 2-Factor Auth',
  375. theme_dir => $Trog::Themes::td,
  376. uri => $uri,
  377. qr => $qr,
  378. failure => $failure,
  379. message => $message,
  380. template => 'totp.tx',
  381. is_admin => 1,
  382. %$query,
  383. },
  384. undef,
  385. [qw{post.css}],
  386. );
  387. }
  388. =head2 login
  389. Sets the user cookie if the provided user exists, or sets up the user as an admin with the provided credentials in the event that no users exist.
  390. =cut
  391. sub login ($query) {
  392. # Redirect if we actually have a logged in user.
  393. # Note to future me -- this user value is overwritten explicitly in server.psgi.
  394. # If that ever changes, you will die
  395. $query->{to} //= $query->{route};
  396. $query->{to} = '/config' if List::Util::any { $query->{to} eq $_ } qw{/login /logout};
  397. if ( $query->{user} ) {
  398. DEBUG("Login by $query->{user}, redirecting to $query->{to}");
  399. return see_also( $query->{to} );
  400. }
  401. #Check and see if we have no users. If so we will just accept whatever creds are passed.
  402. my $hasusers = -f "config/has_users";
  403. my $btnmsg = $hasusers ? "Log In" : "Register";
  404. my $headers;
  405. my $has_totp = 0;
  406. if ( $query->{username} && $query->{password} ) {
  407. if ( !$hasusers ) {
  408. # Make the first user
  409. Trog::Auth::useradd( $query->{username}, $query->{password}, ['admin'] );
  410. # Add a stub user page and the initial series.
  411. my $dat = Trog::Data->new($conf);
  412. _setup_initial_db( $dat, $query->{username} );
  413. # Ensure we stop registering new users
  414. File::Touch::touch("config/has_users");
  415. }
  416. $query->{failed} = 1;
  417. my $cookie = Trog::Auth::mksession( $query->{username}, $query->{password}, $query->{token} );
  418. if ($cookie) {
  419. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  420. my $secure = '';
  421. $secure = '; Secure' if $query->{scheme} eq 'https';
  422. $headers = {
  423. "Set-Cookie" => "tcmslogin=$cookie; HttpOnly; SameSite=Strict$secure",
  424. };
  425. $query->{failed} = 0;
  426. }
  427. }
  428. $query->{failed} //= -1;
  429. return Trog::Renderer->render(
  430. template => 'login.tx',
  431. data => {
  432. title => 'tCMS 2 ~ Login',
  433. to => $query->{to},
  434. failure => int( $query->{failed} ),
  435. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  436. btnmsg => $btnmsg,
  437. stylesheets => _build_themed_styles([qw{login.css}]),
  438. theme_dir => $Trog::Themes::td,
  439. has_users => $hasusers,
  440. %$query,
  441. },
  442. headers => $headers,
  443. contenttype => 'text/html',
  444. code => 200,
  445. );
  446. }
  447. sub _setup_initial_db ( $dat, $user ) {
  448. $dat->add(
  449. {
  450. "aclname" => "series",
  451. "acls" => [],
  452. "callback" => "Trog::Routes::HTML::series",
  453. method => 'GET',
  454. "data" => "Series",
  455. "href" => "/series",
  456. "local_href" => "/series",
  457. "preview" => "/img/sys/testpattern.jpg",
  458. "tags" => [qw{series topbar}],
  459. visibility => 'public',
  460. "title" => "Series",
  461. user => $user,
  462. form => 'series.tx',
  463. child_form => 'series.tx',
  464. aliases => [],
  465. },
  466. {
  467. "aclname" => "about",
  468. "acls" => [],
  469. "callback" => "Trog::Routes::HTML::series",
  470. method => 'GET',
  471. "data" => "About",
  472. "href" => "/about",
  473. "local_href" => "/about",
  474. "preview" => "/img/sys/testpattern.jpg",
  475. "tags" => [qw{series topbar public}],
  476. visibility => 'public',
  477. "title" => "About",
  478. user => $user,
  479. form => 'series.tx',
  480. child_form => 'profile.tx',
  481. aliases => [],
  482. },
  483. {
  484. "aclname" => "config",
  485. acls => [],
  486. "callback" => "Trog::Routes::HTML::config",
  487. 'method' => 'GET',
  488. "content_type" => "text/html",
  489. "data" => "Config",
  490. "href" => "/config",
  491. "local_href" => "/config",
  492. "preview" => "/img/sys/testpattern.jpg",
  493. "tags" => [qw{admin}],
  494. visibility => 'private',
  495. "title" => "Configure tCMS",
  496. user => $user,
  497. aliases => [],
  498. },
  499. {
  500. title => $user,
  501. data => 'Default user',
  502. preview => '/img/avatar/humm.gif',
  503. wallpaper => '/img/sys/testpattern.jpg',
  504. tags => ['about'],
  505. visibility => 'public',
  506. acls => ['admin'],
  507. local_href => "/users/$user",
  508. callback => "Trog::Routes::HTML::users",
  509. method => 'GET',
  510. user => $user,
  511. form => 'profile.tx',
  512. aliases => [],
  513. },
  514. );
  515. }
  516. =head2 logout
  517. Deletes your users' session and opens the index.
  518. =cut
  519. sub logout ($query) {
  520. Trog::Auth::killsession( $query->{user} ) if $query->{user};
  521. delete $query->{user};
  522. return Trog::Routes::HTML::index($query);
  523. }
  524. =head2 config
  525. Renders the configuration page, or redirects you back to the login page.
  526. =cut
  527. sub config ($query) {
  528. return see_also('/login') unless $query->{user};
  529. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  530. $query->{failure} //= -1;
  531. return Trog::Routes::HTML::index(
  532. {
  533. title => 'Configure tCMS',
  534. theme_dir => $Trog::Themes::td,
  535. stylesheets => [qw{config.css}],
  536. scripts => [qw{post.js}],
  537. themes => _get_themes() || [],
  538. data_models => _get_data_models(),
  539. current_theme => $conf->param('general.theme') // '',
  540. current_data_model => $conf->param('general.data_model') // 'DUMMY',
  541. totp_secret => $conf->param('totp.secret'),
  542. message => $query->{message},
  543. failure => $query->{failure},
  544. to => '/config',
  545. scheme => $query->{scheme},
  546. embeds => $conf->param('security.allow_embeds_from') // '',
  547. is_admin => 1,
  548. template => 'config.tx',
  549. %$query,
  550. },
  551. undef,
  552. [qw{config.css}],
  553. );
  554. }
  555. sub _get_series ( $edit = 0 ) {
  556. my @series = $data->get(
  557. acls => [qw{public}],
  558. tags => [qw{topbar}],
  559. limit => 10,
  560. page => 1,
  561. );
  562. @series = map { $_->{local_href} = "/post$_->{local_href}"; $_ } @series if $edit;
  563. return @series;
  564. }
  565. sub _get_themes {
  566. my $dir = 'www/themes';
  567. opendir( my $dh, $dir ) || do { die "Can't opendir $dir: $!" unless $!{ENOENT} };
  568. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  569. closedir $dh;
  570. return \@tdirs;
  571. }
  572. sub _get_data_models {
  573. my $dir = 'lib/Trog/Data';
  574. opendir( my $dh, $dir ) || die "Can't opendir $dir: $!";
  575. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  576. closedir $dh;
  577. return \@dmods;
  578. }
  579. =head2 config_save
  580. Implements /config/save route. Saves what little configuration we actually use to ~/.tcms/tcms.conf
  581. =cut
  582. sub config_save ($query) {
  583. return see_also('/login') unless $query->{user};
  584. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  585. $conf->param( 'general.theme', $query->{theme} ) if defined $query->{theme};
  586. $conf->param( 'general.data_model', $query->{data_model} ) if $query->{data_model};
  587. # Erase all TOTP secrets in the event we change the global secret
  588. if ( $query->{totp_secret} ) {
  589. $conf->param( 'totp.secret', $query->{totp_secret} );
  590. Trog::Auth::clear_totp();
  591. }
  592. $query->{failure} = 1;
  593. $query->{message} = "Failed to save configuration!";
  594. if ( $conf->write($Trog::Config::home_cfg) ) {
  595. $query->{failure} = 0;
  596. $query->{message} = "Configuration updated succesfully.";
  597. }
  598. #Get the PID of the parent port using lsof, send HUP
  599. my $parent = getppid;
  600. kill 'HUP', $parent;
  601. return config($query);
  602. }
  603. =head2 themeclone
  604. Clone a theme by copying a directory.
  605. =cut
  606. sub themeclone ($query) {
  607. return see_also('/login') unless $query->{user};
  608. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  609. my ( $theme, $newtheme ) = ( $query->{theme}, $query->{newtheme} );
  610. my $themedir = 'www/themes';
  611. $query->{failure} = 1;
  612. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  613. require File::Copy::Recursive;
  614. if ( $theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" ) ) {
  615. $query->{failure} = 0;
  616. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  617. }
  618. return see_also('/config');
  619. }
  620. =head2 post_save
  621. Saves posts submitted via the /post pages
  622. =cut
  623. sub post_save ($query) {
  624. return see_also('/login') unless $query->{user};
  625. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  626. my $to = delete $query->{to};
  627. #Copy this down since it will be deleted later
  628. my $acls = $query->{acls};
  629. $query->{tags} = Trog::Utils::coerce_array( $query->{tags} );
  630. # Filter bits and bobs
  631. delete $query->{primary_post};
  632. delete $query->{social_meta};
  633. delete $query->{deflate};
  634. delete $query->{acls};
  635. # Ensure there are no null tags
  636. @{ $query->{tags} } = grep { defined $_ } @{ $query->{tags} };
  637. # Posts will always be GET
  638. $query->{method} = 'GET';
  639. $data->add($query) and die "Could not add post";
  640. return see_also($to);
  641. }
  642. =head2 profile
  643. Saves / updates new users.
  644. =cut
  645. sub profile ($query) {
  646. return see_also('/login') unless $query->{user};
  647. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  648. #TODO allow users to do something OTHER than be admins
  649. if ( $query->{password} ) {
  650. Trog::Auth::useradd( $query->{username}, $query->{password}, ['admin'] );
  651. }
  652. #Make sure it is "self-authored", redact pw
  653. $query->{user} = delete $query->{username};
  654. delete $query->{password};
  655. return post_save($query);
  656. }
  657. =head2 post_delete
  658. deletes posts.
  659. =cut
  660. sub post_delete ($query) {
  661. return see_also('/login') unless $query->{user};
  662. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  663. $data->delete($query) and die "Could not delete post";
  664. return see_also( $query->{to} );
  665. }
  666. =head2 series
  667. Series specific view, much like the users/ route
  668. Displays identified series, not all series.
  669. =cut
  670. sub series ($query) {
  671. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  672. #we are either viewed one of two ways, /post/$id or /$aclname
  673. my ( undef, $aclname, $id ) = split( /\//, $query->{route} );
  674. $query->{aclname} = $aclname if !$id;
  675. $query->{id} = $id if $id;
  676. # Don't show topbar series on the series page. That said, don't exclude it from direct series view.
  677. $query->{exclude_tags} = ['topbar'] if !$is_admin && $aclname && $aclname eq 'series';
  678. #XXX I'd prefer to overload id to actually *be* the aclname...
  679. # but this way, accomodates things like the flat file time-indexing hack.
  680. # TODO I should probably have it for all posts, and make *everything* a series.
  681. # WE can then do threaded comments/posts.
  682. # That will essentially necessitate it *becoming* the ID for real.
  683. #Grab the relevant tag (aclname), then pass that to posts
  684. my @posts = _post_helper( $query, ['series'], $query->{user_acls} );
  685. delete $query->{id};
  686. delete $query->{aclname};
  687. $query->{subhead} = $posts[0]->{data};
  688. $query->{title} = $posts[0]->{title};
  689. $query->{tag} = $posts[0]->{aclname};
  690. $query->{primary_post} = $posts[0];
  691. $query->{in_series} = 1;
  692. return posts($query);
  693. }
  694. =head2 avatars
  695. Returns the avatars.css.
  696. =cut
  697. sub avatars ($query) {
  698. push( @{ $query->{user_acls} }, 'public' );
  699. my $tags = Trog::Utils::coerce_array( $query->{tag} );
  700. my @posts = _post_helper( $query, $tags, $query->{user_acls} );
  701. if (@posts) {
  702. # Set the eTag so that we don't get a re-fetch
  703. $query->{etag} = "$posts[0]{id}-$posts[0]{version}";
  704. }
  705. return Trog::Renderer->render(
  706. template => 'avatars.tx',
  707. data => {
  708. users => \@posts,
  709. %$query,
  710. },
  711. code => 200,
  712. contenttype => 'text/css',
  713. );
  714. }
  715. =head2 users
  716. Implements direct user profile view.
  717. =cut
  718. sub users ($query) {
  719. # Capture the username
  720. my ( undef, undef, $username ) = split( /\//, $query->{route} );
  721. $query->{username} //= $username;
  722. push( @{ $query->{user_acls} }, 'public' );
  723. $query->{exclude_tags} = ['about'];
  724. # Don't show topbar series on the series page. That said, don't exclude it from direct series view.
  725. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  726. push( @{ $query->{exclude_tags} }, 'topbar' ) if !$is_admin;
  727. my @posts = _post_helper( { author => $query->{username} }, ['about'], $query->{user_acls} );
  728. $query->{id} = $posts[0]->{id};
  729. $query->{title} = $posts[0]->{title};
  730. $query->{user_obj} = $posts[0];
  731. $query->{primary_post} = $posts[0];
  732. $query->{in_series} = 1;
  733. return posts($query);
  734. }
  735. =head2 posts
  736. Display multi or single posts, supports RSS and pagination.
  737. =cut
  738. sub posts ( $query, $direct = 0 ) {
  739. # Allow rss.xml to tell what posts to loop over
  740. my $fmt = $query->{format} || '';
  741. my $for = URI->new($query->{for} || '')->path() || $query->{route};
  742. $query->{route} = $for if $fmt eq 'rss';
  743. #Process the input URI to capture tag/id
  744. $query->{route} //= $query->{to};
  745. my ( undef, undef, $id ) = split( /\//, $query->{route} );
  746. my $tags = Trog::Utils::coerce_array( $query->{tag} );
  747. $query->{id} = $id if $id && !$query->{in_series};
  748. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  749. push( @{ $query->{user_acls} }, 'public' );
  750. push( @{ $query->{user_acls} }, 'unlisted' ) if $query->{id};
  751. push( @{ $query->{user_acls} }, 'private' ) if $is_admin;
  752. my @posts;
  753. # Discover this user's visibility, so we can make them post in this category by default
  754. my $user_visibility = 'public';
  755. if ( $query->{user_obj} ) {
  756. #Optimize the /users/* route
  757. @posts = ( $query->{user_obj} );
  758. $user_visibility = $query->{user_obj}->{visibility};
  759. }
  760. else {
  761. if ( $query->{user} ) {
  762. my @me = _post_helper( { author => $query->{user} }, ['about'], $query->{user_acls} );
  763. $user_visibility = $me[0]->{visibility};
  764. }
  765. @posts = _post_helper( $query, $tags, $query->{user_acls} );
  766. }
  767. if ( $query->{id} ) {
  768. $query->{primary_post} = $posts[0] if @posts;
  769. }
  770. #OK, so if we have a user as the ID we found, go grab the rest of their posts
  771. if ( $query->{id} && @posts && List::Util::any { $_ eq 'about' } @{ $posts[0]->{tags} } ) {
  772. my $user = shift(@posts);
  773. my $id = delete $query->{id};
  774. $query->{author} = $user->{user};
  775. @posts = _post_helper( $query, $tags, $query->{user_acls} );
  776. @posts = grep { $_->{id} ne $id } @posts;
  777. unshift @posts, $user;
  778. }
  779. if ( !$is_admin ) {
  780. return notfound($query) unless @posts;
  781. }
  782. # Set the eTag so that we don't get a re-fetch
  783. $query->{etag} = "$posts[0]{id}-$posts[0]{version}" if @posts;
  784. #Correct page headers
  785. my $ph = $themed ? _themed_title( $query->{route} ) : $query->{route};
  786. return _rss( $query, $ph, \@posts ) if $fmt eq 'rss';
  787. #XXX Is used by the sitemap, maybe just fix there?
  788. my @post_aliases = map { $_->{local_href} } _get_series();
  789. # Allow themes to put in custom headers/footers on posts
  790. my ( $header, $footer );
  791. $header = Trog::Renderer->render( 'headers/' . $query->{primary_post}{header}, { theme_dir => $Trog::Themes::td } ) if $query->{primary_post}{header};
  792. $footer = Trog::Renderer->render( 'footers/' . $query->{primary_post}{footer}, { theme_dir => $Trog::Themes::td } ) if $query->{primary_post}{footer};
  793. # List the available headers/footers
  794. my $headers = Trog::Themes::templates_in_dir( "headers", 'text/html', 1 );
  795. my $footers = Trog::Themes::templates_in_dir( "footers", 'text/html', 1 );
  796. #XXX used to be post.css, but probably not good anymore?
  797. my $styles = [];
  798. # Build page title if it wasn't set by a wrapping sub
  799. $query->{title} = "$query->{domain} : $query->{title}" if $query->{title} && $query->{domain};
  800. $query->{title} ||= @$tags && $query->{domain} ? "$query->{domain} : @$tags" : undef;
  801. #Handle paginator vars
  802. my $limit = int( $query->{limit} || 25 );
  803. my $now_year = ( localtime(time) )[5] + 1900;
  804. my $oldest_year = $now_year - 20; #XXX actually find oldest post year
  805. # Handle post style.
  806. if ( $query->{style} ) {
  807. undef $header;
  808. undef $footer;
  809. }
  810. my $older = !@posts ? 0 : $posts[-1]->{created};
  811. $query->{failure} //= -1;
  812. $query->{id} //= '';
  813. my $newer = !@posts ? 0 : $posts[0]->{created};
  814. #XXX messed up data has to be fixed unfortunately
  815. @$tags = List::Util::uniq @$tags;
  816. #Filter displaying visibility tags
  817. my @visibuddies = qw{public unlisted private};
  818. foreach my $post (@posts) {
  819. @{ $post->{tags} } = grep {
  820. my $tag = $_;
  821. !grep { $tag eq $_ } @visibuddies
  822. } @{ $post->{tags} };
  823. }
  824. #XXX note that we are explicitly relying on the first tag to be the ACL
  825. my $aclselected = $tags->[0] || '';
  826. my @acls = map {
  827. $_->{selected} = $_->{aclname} eq $aclselected ? 'selected' : '';
  828. $_
  829. } _post_helper( {}, ['series'], $query->{user_acls} );
  830. my $forms = Trog::Themes::templates_in_dir("forms", 'text/html', 1);
  831. my $edittype = $query->{primary_post} ? $query->{primary_post}->{child_form} : $query->{form};
  832. my $tiled = $query->{primary_post} ? !$is_admin && $query->{primary_post}->{tiled} : 0;
  833. # Grab the rest of the tags to dump into the edit form
  834. my @tags_all = $data->tags();
  835. #Filter out the visibilities and special series tags
  836. @tags_all = grep {
  837. my $subj = $_;
  838. scalar( grep { $_ eq $subj } qw{public private unlisted admin series about topbar} ) == 0
  839. } @tags_all;
  840. @posts = map {
  841. my $subject = $_;
  842. my @et = grep {
  843. my $subj = $_;
  844. grep { $subj eq $_ } @tags_all
  845. } @{ $subject->{tags} };
  846. @et = grep { $_ ne $aclselected } @et;
  847. $_->{extra_tags} = \@et;
  848. $_
  849. } @posts;
  850. my @et = List::MoreUtils::singleton( @$tags, @tags_all );
  851. $query->{author} = $query->{primary_post}{user} // $posts[0]{user};
  852. my $picker = Trog::Component::EmojiPicker::render();
  853. return $picker if ref $picker eq 'ARRAY';
  854. #XXX the only reason this is needed is due to direct=1
  855. #XXX is this even used?
  856. my $content = Trog::Renderer->render(
  857. template => 'posts.tx',
  858. data => {
  859. acls => \@acls,
  860. can_edit => $is_admin,
  861. forms => $forms,
  862. post => { tags => $tags, extra_tags => \@et, form => $edittype, visibility => $user_visibility, addpost => 1 },
  863. post_visibilities => \@visibuddies,
  864. failure => $query->{failure},
  865. to => $query->{to},
  866. message => $query->{failure} ? "Failed to add post!" : "Successfully added Post as $query->{id}",
  867. direct => $direct,
  868. title => $query->{title},
  869. author => $query->{primary_post}{user} // $posts[0]{user},
  870. style => $query->{style},
  871. posts => \@posts,
  872. like => $query->{like},
  873. in_series => exists $query->{in_series} || !!( $query->{route} =~ m/^\/series\// ),
  874. route => $query->{route},
  875. limit => $limit,
  876. pages => scalar(@posts) == $limit,
  877. older => $older,
  878. newer => $newer,
  879. sizes => [ 25, 50, 100 ],
  880. rss => !$query->{id} && !$query->{older},
  881. tiled => $tiled,
  882. category => $ph,
  883. subhead => $query->{subhead},
  884. header => $header,
  885. footer => $footer,
  886. headers => $headers,
  887. footers => $footers,
  888. years => [ reverse( $oldest_year .. $now_year ) ],
  889. months => [ 0 .. 11 ],
  890. emoji_picker => $picker,
  891. },
  892. contenttype => 'text/html',
  893. component => 1,
  894. );
  895. # Something exploded
  896. return $content if ref $content eq "ARRAY";
  897. return $content if $direct;
  898. return Trog::Routes::HTML::index( $query, $content, $styles );
  899. }
  900. sub _themed_title ($path) {
  901. return $path unless %Theme::paths;
  902. return $Theme::paths{$path} ? $Theme::paths{$path} : $path;
  903. }
  904. sub _post_helper ( $query, $tags, $acls ) {
  905. return $data->get(
  906. older => $query->{older},
  907. newer => $query->{newer},
  908. page => int( $query->{page} || 1 ),
  909. limit => int( $query->{limit} || 25 ),
  910. tags => $tags,
  911. exclude_tags => $query->{exclude_tags},
  912. acls => $acls,
  913. aclname => $query->{aclname},
  914. like => $query->{like},
  915. author => $query->{author},
  916. id => $query->{id},
  917. version => $query->{version},
  918. );
  919. }
  920. =head2 sitemap
  921. Return the sitemap index unless the static or a set of dynamic routes is requested.
  922. We have a maximum of 99,990,000 posts we can make under this model
  923. As we have 10,000 * 10,000 posts which are indexable via the sitemap format.
  924. 1 top level index slot (10k posts) is taken by our static routes, the rest will be /posts.
  925. Passing ?xml=1 will result in an appropriate sitemap.xml instead.
  926. This is used to generate the static sitemaps as expected by search engines.
  927. Passing compressed=1 will gzip the output.
  928. =cut
  929. sub sitemap ($query) {
  930. state $etag = "sitemap-" . time();
  931. my ( @to_map, $is_index, $route_type );
  932. my $warning = '';
  933. $query->{map} //= '';
  934. if ( $query->{map} eq 'static' ) {
  935. # Return the map of static routes
  936. $route_type = 'Static Routes';
  937. @to_map = grep { !defined $routes{$_}->{captures} && $_ !~ m/^default|login|auth$/ && !$routes{$_}->{auth} } keys(%routes);
  938. }
  939. elsif ( !$query->{map} ) {
  940. # Return the index instead
  941. @to_map = ('static');
  942. my $tot = $data->count();
  943. my $size = 50000;
  944. my $pages = int( $tot / $size ) + ( ( $tot % $size ) ? 1 : 0 );
  945. # Truncate pages at 10k due to standard
  946. my $clamped = $pages > 49999 ? 49999 : $pages;
  947. $warning = "More posts than possible to represent in sitemaps & index! Old posts have been truncated." if $pages > 49999;
  948. foreach my $page ( $clamped .. 1 ) {
  949. push( @to_map, "$page" );
  950. }
  951. $is_index = 1;
  952. }
  953. else {
  954. $route_type = "Posts: Page $query->{map}";
  955. # Return the map of the particular range of dynamic posts
  956. $query->{limit} = 50000;
  957. $query->{page} = $query->{map};
  958. @to_map = _post_helper( $query, [], ['public'] );
  959. }
  960. if ( $query->{xml} ) {
  961. DEBUG("RENDER SITEMAP XML");
  962. my $sm;
  963. my $xml_date = time();
  964. my $fmt = "xml";
  965. $fmt .= ".gz" if $query->{compressed};
  966. if ( !$query->{map} ) {
  967. require WWW::SitemapIndex::XML;
  968. $sm = WWW::SitemapIndex::XML->new();
  969. foreach my $url (@to_map) {
  970. $sm->add(
  971. loc => "http://$query->{domain}/sitemap/$url.$fmt",
  972. lastmod => $xml_date,
  973. );
  974. }
  975. }
  976. else {
  977. require WWW::Sitemap::XML;
  978. $sm = WWW::Sitemap::XML->new();
  979. my $changefreq = $query->{map} eq 'static' ? 'monthly' : 'daily';
  980. foreach my $url (@to_map) {
  981. my $true_uri = "http://$query->{domain}$url";
  982. if ( ref $url eq 'HASH' ) {
  983. my $is_user_page = grep { $_ eq 'about' } @{ $url->{tags} };
  984. $true_uri = "http://$query->{domain}/posts/$url->{id}";
  985. $true_uri = "http://$query->{domain}/users/$url->{title}" if $is_user_page;
  986. }
  987. my %out = (
  988. loc => $true_uri,
  989. lastmod => $xml_date,
  990. mobile => 1,
  991. changefreq => $changefreq,
  992. priority => 1.0,
  993. );
  994. if ( ref $url eq 'HASH' ) {
  995. #add video & preview image if applicable
  996. $out{images} = [
  997. {
  998. loc => "http://$query->{domain}$url->{href}",
  999. caption => $url->{data},
  1000. title => substr( $url->{title}, 0, 100 ),
  1001. }
  1002. ]
  1003. if $url->{is_image};
  1004. # Truncate descriptions
  1005. my $desc = substr( $url->{data}, 0, 2048 ) || '';
  1006. my $href = $url->{href} || '';
  1007. my $preview = $url->{preview} || '';
  1008. my $domain = $query->{domain} || '';
  1009. $out{videos} = [
  1010. {
  1011. content_loc => "http://$domain$href",
  1012. thumbnail_loc => "http://$domain$preview",
  1013. title => substr( $url->{title}, 0, 100 ) || '',
  1014. description => $desc,
  1015. }
  1016. ]
  1017. if $url->{is_video};
  1018. }
  1019. $sm->add(%out);
  1020. }
  1021. }
  1022. my $xml = $sm->as_xml();
  1023. require IO::String;
  1024. my $buf = IO::String->new();
  1025. my $ct = 'application/xml';
  1026. $xml->toFH( $buf, 0 );
  1027. seek $buf, 0, 0;
  1028. if ( $query->{compressed} ) {
  1029. require IO::Compress::Gzip;
  1030. my $compressed = IO::String->new();
  1031. IO::Compress::Gzip::gzip( $buf => $compressed );
  1032. $ct = 'application/gzip';
  1033. $buf = $compressed;
  1034. seek $compressed, 0, 0;
  1035. }
  1036. #XXX This is one of the few exceptions where we don't use finish_render, as it *requires* gzip.
  1037. return [ 200, [ "Content-type" => $ct, 'ETag' => $etag ], $buf ];
  1038. }
  1039. @to_map = sort @to_map unless $is_index;
  1040. my $styles = ['sitemap.css'];
  1041. $query->{title} = "$query->{domain} : Sitemap";
  1042. $query->{template} = 'sitemap.tx',
  1043. $query->{to_map} = \@to_map,
  1044. $query->{is_index} = $is_index,
  1045. $query->{route_type} = $route_type,
  1046. $query->{etag} = $etag;
  1047. return Trog::Routes::HTML::index( $query, undef, $styles );
  1048. }
  1049. sub _rss ( $query, $subtitle, $posts ) {
  1050. require XML::RSS;
  1051. my $rss = XML::RSS->new( version => '2.0', stylesheet => '/styles/rss-style.xsl' );
  1052. my $now = DateTime->from_epoch( epoch => time() );
  1053. $rss->channel(
  1054. title => "$query->{domain}",
  1055. subtitle => $subtitle,
  1056. link => "http://$query->{domain}/$query->{route}.rss.xml",
  1057. language => 'en', #TODO localization
  1058. description => "$query->{domain} : $query->{route}",
  1059. pubDate => $now,
  1060. lastBuildDate => $now,
  1061. );
  1062. $rss->image(
  1063. title => $query->{domain},
  1064. url => "/favicon.ico",
  1065. link => "http://$query->{domain}",
  1066. width => 32,
  1067. height => 32,
  1068. description => "$query->{domain} favicon",
  1069. );
  1070. foreach my $post (@$posts) {
  1071. my $url = "http://$query->{domain}$post->{local_href}";
  1072. _post2rss( $rss, $url, $post );
  1073. next unless ref $post->{aliases} eq 'ARRAY';
  1074. foreach my $alias ( @{ $post->{aliases} } ) {
  1075. $url = "http://$query->{domain}$alias";
  1076. _post2rss( $rss, $url, $post );
  1077. }
  1078. }
  1079. return finish_render(
  1080. undef,
  1081. {
  1082. etag => $query->{etag},
  1083. contenttype => "application/xml",
  1084. body => encode_utf8( $rss->as_string ),
  1085. scheme => $query->{scheme},
  1086. },
  1087. 'Content-Disposition' => 'inline; filename="rss.xml"',
  1088. );
  1089. }
  1090. sub _post2rss ( $rss, $url, $post ) {
  1091. $rss->add_item(
  1092. title => $post->{title},
  1093. permaLink => $url,
  1094. link => $url,
  1095. enclosure => { url => $url, type => "text/html" },
  1096. description => "<![CDATA[$post->{data}]]>",
  1097. pubDate => DateTime->from_epoch( epoch => $post->{created} ), #TODO format like Thu, 23 Aug 1999 07:00:00 GMT
  1098. author => $post->{user}, #TODO translate to "email (user)" format
  1099. );
  1100. }
  1101. =head2 manual
  1102. Implements the /manual and /lib/* routes.
  1103. Basically a thin wrapper around Pod::Html.
  1104. =cut
  1105. sub manual ($query) {
  1106. return see_also('/login') unless $query->{user};
  1107. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1108. require Pod::Html;
  1109. require Capture::Tiny;
  1110. #Fix links from Pod::HTML
  1111. $query->{module} =~ s/\.html$//g if $query->{module};
  1112. $query->{failure} //= -1;
  1113. my $infile = $query->{module} ? "$query->{module}.pm" : 'tCMS/Manual.pod';
  1114. return notfound($query) unless -f "lib/$infile";
  1115. my $content = capture { Pod::Html::pod2html( qw{--podpath=lib --podroot=.}, "--infile=lib/$infile" ) };
  1116. return Trog::Routes::HTML::index(
  1117. {
  1118. title => 'tCMS Manual',
  1119. theme_dir => $Trog::Themes::td,
  1120. content => $content,
  1121. template => 'manual.tx',
  1122. is_admin => 1,
  1123. %$query,
  1124. },
  1125. undef,
  1126. ['post.css'],
  1127. );
  1128. }
  1129. # basically a file rewrite rule for themes
  1130. sub icon ($query) {
  1131. my $path = $query->{route};
  1132. return Trog::FileHandler::serve("$Trog::Themes::td/img/icon/$path");
  1133. }
  1134. # TODO make statics, abstract gzipped outputting & header handling
  1135. sub rss_style ($query) {
  1136. $query->{port} = ":$query->{port}" if $query->{port};
  1137. $query->{rss_css} = Trog::Themes::themed_style("rss.css");
  1138. return Trog::Renderer->render(
  1139. template => 'rss-style.tx',
  1140. contenttype => 'text/xsl',
  1141. data => $query,
  1142. code => 200,
  1143. );
  1144. }
  1145. sub _build_themed_styles ($styles) {
  1146. my @styles = map { Trog::Themes::themed_style("$_") } @{Trog::Utils::coerce_array($styles)};
  1147. return \@styles;
  1148. }
  1149. sub _build_themed_scripts ($scripts) {
  1150. my @scripts = map { Trog::Themes::themed_script("$_") } @{Trog::Utils::coerce_array($scripts)};
  1151. return \@scripts;
  1152. }
  1153. sub finish_render ( $template, $vars, %headers ) {
  1154. #XXX default vars that need to be pulled from config
  1155. $vars->{lang} //= 'en-US';
  1156. $vars->{title} //= 'tCMS';
  1157. $vars->{stylesheets} //= [];
  1158. $vars->{scripts} //= [];
  1159. # Theme-ize the paths
  1160. $vars->{stylesheets} = _build_themed_styles($vars->{stylesheets});
  1161. $vars->{scripts} = _build_themed_scripts($vars->{scripts});
  1162. # Absolute-ize the paths for scripts & stylesheets
  1163. @{ $vars->{stylesheets} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{stylesheets} };
  1164. @{ $vars->{scripts} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{scripts} };
  1165. # TODO Smash together the stylesheets and minify
  1166. $vars->{contenttype} //= $Trog::Vars::content_types{html};
  1167. $vars->{cachecontrol} //= $Trog::Vars::cache_control{revalidate};
  1168. $vars->{code} ||= 200;
  1169. $vars->{header} = Trog::Renderer->render( template => 'header.tx', data => $vars, contenttype => 'text/html', component => 1 );
  1170. $vars->{footer} = Trog::Renderer->render( template => 'footer.tx', data => $vars, contenttype => 'text/html', component => 1 );
  1171. return Trog::Renderer->render( template => $template, data => $vars, contenttype => 'text/html', code => $vars->{code} );
  1172. }
  1173. 1;