HTML.pm 48 KB

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