HTML.pm 43 KB

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