HTML.pm 57 KB

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