HTML.pm 56 KB

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