HTML.pm 53 KB

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