HTML.pm 44 KB

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