HTML.pm 57 KB

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