HTML.pm 48 KB

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