HTML.pm 48 KB

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