HTML.pm 43 KB

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