HTML.pm 57 KB

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