HTML.pm 52 KB

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