HTML.pm 45 KB

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