HTML.pm 56 KB

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