HTML.pm 51 KB

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