HTML.pm 44 KB

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