HTML.pm 52 KB

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