HTML.pm 54 KB

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