HTML.pm 53 KB

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