HTML.pm 55 KB

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