HTML.pm 56 KB

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