HTML.pm 54 KB

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