HTML.pm 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  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 Ref::Util();
  13. use Capture::Tiny qw{capture};
  14. use HTML::SocialMeta;
  15. use Clone qw{clone};
  16. use Encode qw{encode_utf8};
  17. use Digest::MD5 qw{md5_hex};
  18. use Digest::SHA qw{sha256_hex};
  19. use JSON::MaybeXS();
  20. use IO::Compress::Gzip;
  21. use Path::Tiny();
  22. use File::Basename qw{dirname};
  23. use URI();
  24. use URI::Escape();
  25. use FindBin::libs;
  26. use Trog::Log qw{:all};
  27. use Trog::Utils;
  28. use Trog::Config;
  29. use Trog::Auth;
  30. use Trog::Data;
  31. use Trog::FileHandler;
  32. use Trog::Themes;
  33. use Trog::Renderer;
  34. use Trog::Email;
  35. use Trog::Component::EmojiPicker;
  36. our $landing_page = 'default.tx';
  37. our $htmltitle = 'title.tx';
  38. our $midtitle = 'midtitle.tx';
  39. our $rightbar = 'rightbar.tx';
  40. our $leftbar = 'leftbar.tx';
  41. our $topbar = 'topbar.tx';
  42. our $footbar = 'footbar.tx';
  43. our $categorybar = 'categories.tx';
  44. # Note to maintainers: never ever remove backends from this list.
  45. # the auth => 1 is a crucial protection.
  46. our %routes = (
  47. default => {
  48. callback => \&Trog::Routes::HTML::setup,
  49. nomap => 1,
  50. },
  51. '/index' => {
  52. method => 'GET',
  53. callback => \&Trog::Routes::HTML::index,
  54. },
  55. # This should only be enabled to debug
  56. # '/setup' => {
  57. # method => 'GET',
  58. # callback => \&Trog::Routes::HTML::setup,
  59. # },
  60. '/login' => {
  61. method => 'GET',
  62. callback => \&Trog::Routes::HTML::login,
  63. noindex => 1,
  64. },
  65. '/logout' => {
  66. method => 'GET',
  67. callback => \&Trog::Routes::HTML::logout,
  68. noindex => 1,
  69. nocache => 1,
  70. },
  71. '/auth' => {
  72. method => 'POST',
  73. callback => \&Trog::Routes::HTML::login,
  74. nocache => 1,
  75. noindex => 1,
  76. },
  77. '/totp' => {
  78. method => 'GET',
  79. auth => 1,
  80. callback => \&Trog::Routes::HTML::totp,
  81. },
  82. '/post/save' => {
  83. method => 'POST',
  84. auth => 1,
  85. callback => \&Trog::Routes::HTML::post_save,
  86. },
  87. '/post/delete' => {
  88. method => 'POST',
  89. auth => 1,
  90. callback => \&Trog::Routes::HTML::post_delete,
  91. },
  92. '/config/save' => {
  93. method => 'POST',
  94. auth => 1,
  95. callback => \&Trog::Routes::HTML::config_save,
  96. },
  97. '/themeclone' => {
  98. method => 'POST',
  99. auth => 1,
  100. callback => \&Trog::Routes::HTML::themeclone,
  101. },
  102. '/profile' => {
  103. method => 'POST',
  104. auth => 1,
  105. callback => \&Trog::Routes::HTML::profile,
  106. },
  107. '/manual' => {
  108. method => 'GET',
  109. auth => 1,
  110. callback => \&Trog::Routes::HTML::manual,
  111. },
  112. '/lib/(.*)' => {
  113. method => 'GET',
  114. auth => 1,
  115. captures => ['module'],
  116. callback => \&Trog::Routes::HTML::manual,
  117. },
  118. '/password_reset' => {
  119. method => 'GET',
  120. callback => \&Trog::Routes::HTML::resetpass,
  121. noindex => 1,
  122. },
  123. # When we are logged in, we get a diff ver of the page.
  124. '/secure/password_reset' => {
  125. method => 'GET',
  126. callback => \&Trog::Routes::HTML::resetpass,
  127. auth => 1,
  128. },
  129. '/request_password_reset' => {
  130. method => 'POST',
  131. callback => \&Trog::Routes::HTML::do_resetpass,
  132. noindex => 1,
  133. nocache => 1,
  134. },
  135. '/request_totp_clear' => {
  136. method => 'POST',
  137. callback => \&Trog::Routes::HTML::do_totp_clear,
  138. noindex => 1,
  139. nocache => 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. '/admin/sessions' => {
  152. method => 'GET',
  153. auth => 1,
  154. callback => \&Trog::Routes::HTML::sessions,
  155. noindex => 1,
  156. nocache => 1,
  157. },
  158. '/admin/wyzzerdd' => {
  159. method => 'GET',
  160. auth => 1,
  161. callback => \&Trog::Routes::HTML::post_wizard,
  162. noindex => 1,
  163. nocache => 1,
  164. },
  165. '/admin/wyzzerdd/save' => {
  166. method => 'POST',
  167. auth => 1,
  168. callback => \&Trog::Routes::HTML::post_wizard_save,
  169. noindex => 1,
  170. nocache => 1,
  171. },
  172. #TODO transform into posts?
  173. '/sitemap',
  174. => {
  175. method => 'GET',
  176. callback => \&Trog::Routes::HTML::sitemap,
  177. },
  178. '/sitemap_index.xml',
  179. => {
  180. method => 'GET',
  181. callback => \&Trog::Routes::HTML::sitemap,
  182. data => { xml => 1 },
  183. },
  184. '/sitemap_index.xml.gz',
  185. => {
  186. method => 'GET',
  187. callback => \&Trog::Routes::HTML::sitemap,
  188. data => { xml => 1, compressed => 1 },
  189. },
  190. '/sitemap/static.xml' => {
  191. method => 'GET',
  192. callback => \&Trog::Routes::HTML::sitemap,
  193. data => { xml => 1, map => 'static' },
  194. },
  195. '/sitemap/static.xml.gz' => {
  196. method => 'GET',
  197. callback => \&Trog::Routes::HTML::sitemap,
  198. data => { xml => 1, compressed => 1, map => 'static' },
  199. },
  200. '/sitemap/(.*).xml' => {
  201. method => 'GET',
  202. callback => \&Trog::Routes::HTML::sitemap,
  203. data => { xml => 1 },
  204. captures => ['map'],
  205. },
  206. '/sitemap/(.*).xml.gz' => {
  207. method => 'GET',
  208. callback => \&Trog::Routes::HTML::sitemap,
  209. data => { xml => 1, compressed => 1 },
  210. captures => ['map'],
  211. },
  212. '/humans.txt' => {
  213. method => 'GET',
  214. callback => \&Trog::Routes::HTML::posts,
  215. data => { tag => ['about'] },
  216. },
  217. '/styles/avatars.css' => {
  218. method => 'GET',
  219. callback => \&Trog::Routes::HTML::avatars,
  220. data => { tag => ['about'] },
  221. },
  222. '/avatar/(.*)' => {
  223. method => 'GET',
  224. callback => \&Trog::Routes::HTML::libravatar,
  225. captures => ['avatar_hash'],
  226. noindex => 1,
  227. nocache => 1,
  228. },
  229. '/favicon.ico' => {
  230. method => 'GET',
  231. callback => \&Trog::Routes::HTML::icon,
  232. },
  233. '/totp_qr/(.*)' => {
  234. auth => 1,
  235. method => 'GET',
  236. callback => \&Trog::Routes::HTML::totp_qr,
  237. },
  238. '/styles/rss-style.xsl' => {
  239. method => 'GET',
  240. callback => \&Trog::Routes::HTML::rss_style,
  241. },
  242. );
  243. # Grab theme routes
  244. my $themed = 0;
  245. my $theme_dir = Trog::Themes::get_dir();
  246. if ($theme_dir) {
  247. my $theme_mod = "$theme_dir/routes.pm";
  248. if ( -f $theme_mod ) {
  249. use lib '.';
  250. require $theme_mod;
  251. @routes{ keys(%Theme::routes) } = values(%Theme::routes);
  252. $themed = 1;
  253. }
  254. else {
  255. # Use the special "default" theme
  256. require Theme;
  257. }
  258. }
  259. =head1 PRIMARY ROUTE
  260. =head2 _feedback_redirect($query, $to, $failure, $message)
  261. Redirect to $to, carrying the outcome of a save so the destination page can put
  262. it in the jsalert banner.
  263. We redirect rather than rendering in place so that a save stays a
  264. POST-redirect-GET -- refreshing the page the user lands on must not re-submit
  265. the post. That means the outcome has to travel in the URL, as there is nowhere
  266. else to put it.
  267. =cut
  268. sub _feedback_redirect ( $query, $to, $failure, $message ) {
  269. # The banner puts this in a JS string literal, so it has to be one line.
  270. $message //= '';
  271. $message =~ s/\s*\n+\s*/; /g;
  272. $message =~ s/;\s*$//;
  273. my $sep = $to =~ m/\?/ ? '&' : '?';
  274. my $key = $failure ? 'savefailed' : 'saved';
  275. return $query->{tpsgi}->see_also( $to . $sep . $key . '=' . URI::Escape::uri_escape($message) );
  276. }
  277. =head2 _absorb_feedback($query)
  278. Turn the parameters _feedback_redirect() put in the URL back into the failure
  279. and message the jsalert banner reads.
  280. Done in index() rather than in each route, so that a save can hand feedback to
  281. any destination that renders a page, whichever route ends up serving it.
  282. =cut
  283. sub _absorb_feedback ($query) {
  284. my ( $saved, $failed ) = ( $query->{saved}, $query->{savefailed} );
  285. return unless defined $saved || defined $failed;
  286. $query->{failure} = defined $failed ? 1 : 0;
  287. $query->{message} = ( defined $failed ? $failed : $saved ) || ( $query->{failure} ? 'Save failed.' : 'Saved.' );
  288. # Nothing further to navigate to -- we are already there. Without this the
  289. # banner's success branch would bounce us onwards.
  290. delete $query->{to};
  291. return;
  292. }
  293. =head2 index
  294. Implements the primary route used by all pages not behind auth.
  295. Most subsequent functions simply pass content to this function.
  296. =cut
  297. sub index ( $query, $content = '', $i_styles = [], $i_scripts = [] ) {
  298. $query->{theme_dir} = Trog::Themes::td();
  299. _absorb_feedback($query);
  300. my $to_render = $query->{template} // $landing_page;
  301. $content ||= Trog::Renderer->render( template => $to_render, data => $query, component => 1, contenttype => 'text/html' );
  302. return $content if ref $content eq "ARRAY";
  303. my @styles;
  304. unshift( @styles, qw{embed.css} ) if $query->{embed};
  305. unshift( @styles, qw{screen.css structure.css} );
  306. push( @styles, @$i_styles );
  307. my @p_styles = qw{structure.css print.css};
  308. unshift( @p_styles, qw{embed.css} ) if $query->{embed};
  309. my @series = _get_series(0);
  310. my $title = $query->{primary_post}{title} // $query->{title} // $Theme::default_title // 'tCMS';
  311. # Handle link "unfurling" correctly
  312. my ( $default_tags, $meta_desc, $meta_tags ) = _build_social_meta( $query, $title );
  313. #Do embed content
  314. my $tmpl = $query->{embed} ? 'embed.tx' : 'index.tx';
  315. $query->{theme_dir} =~ s/^\/www\///;
  316. # TO support theming we have to do things like this rather than with an include directive in the templates.
  317. my $htmltitle = Trog::Renderer->render( template => $htmltitle, data => $query, component => 1, contenttype => 'text/html' );
  318. return $htmltitle if ref $htmltitle eq 'ARRAY';
  319. my $midtitle = Trog::Renderer->render( template => $midtitle, data => $query, component => 1, contenttype => 'text/html' );
  320. return $midtitle if ref $midtitle eq 'ARRAY';
  321. my $rightbar = Trog::Renderer->render( template => $rightbar, data => $query, component => 1, contenttype => 'text/html' );
  322. return $rightbar if ref $rightbar eq 'ARRAY';
  323. my $leftbar = Trog::Renderer->render( template => $leftbar, data => $query, component => 1, contenttype => 'text/html' );
  324. return $leftbar if ref $leftbar eq 'ARRAY';
  325. my $topbar = Trog::Renderer->render( template => $topbar, data => $query, component => 1, contenttype => 'text/html' );
  326. return $topbar if ref $topbar eq 'ARRAY';
  327. my $footbar = Trog::Renderer->render( template => $footbar, data => $query, component => 1, contenttype => 'text/html' );
  328. return $footbar if ref $footbar eq 'ARRAY';
  329. my $categorybar = Trog::Renderer->render( template => $categorybar, data => { %$query, categories => \@series }, component => 1, contenttype => 'text/html' );
  330. return $categorybar if ref $categorybar eq 'ARRAY';
  331. # Grab the avatar class for the logged in user
  332. if ( $query->{user} ) {
  333. $query->{user_class} = Trog::Auth::username2classname( $query->{user} );
  334. }
  335. state $data;
  336. $data //= Trog::Data->new(Trog::Config::get());
  337. return finish_render(
  338. $tmpl,
  339. {
  340. %$query,
  341. search_lang => $data->lang(),
  342. search_help => $data->help(),
  343. theme_dir => Trog::Themes::td(),
  344. content => $content,
  345. title => $title,
  346. htmltitle => $htmltitle,
  347. midtitle => $midtitle,
  348. rightbar => $rightbar,
  349. leftbar => $leftbar,
  350. topbar => $topbar,
  351. footbar => $footbar,
  352. categorybar => $categorybar,
  353. categories => \@series,
  354. stylesheets => \@styles,
  355. print_styles => \@p_styles,
  356. scripts => $i_scripts,
  357. show_madeby => $Theme::show_madeby ? 1 : 0,
  358. embed => $query->{embed} ? 1 : 0,
  359. embed_video => $query->{primary_post}{is_video},
  360. default_tags => $default_tags,
  361. meta_desc => $meta_desc,
  362. meta_tags => $meta_tags,
  363. }
  364. );
  365. }
  366. sub _build_social_meta ( $query, $title ) {
  367. return ( undef, undef, undef ) unless $query->{social_meta} && $query->{route} && $query->{domain};
  368. my $default_tags = $Theme::default_tags;
  369. $default_tags .= ',' . join( ',', @{ $query->{primary_post}->{tags} } ) if $default_tags && $query->{primary_post}->{tags};
  370. my $primary_data = ref $query->{primary_post}{data} eq 'ARRAY' ? $query->{primary_post}{data}[0] : $query->{primary_post}{data};
  371. my $meta_desc = $primary_data // $Theme::description // "tCMS Site";
  372. $meta_desc = Trog::Utils::strip_and_trunc($meta_desc) || '';
  373. my $meta_tags = '';
  374. my $card_type = 'summary';
  375. $card_type = 'featured_image' if $query->{primary_post} && $query->{primary_post}{is_image};
  376. $card_type = 'player' if $query->{primary_post} && $query->{primary_post}{is_video};
  377. my $image = $Theme::default_image ? "https://$query->{domain}/" . Trog::Themes::get_dir() . "/$Theme::default_image" : '';
  378. $image = "https://$query->{domain}/$query->{primary_post}{preview}" if $query->{primary_post} && $query->{primary_post}{preview};
  379. $image = "https://$query->{domain}/$query->{primary_post}{href}" if $query->{primary_post} && $query->{primary_post}{is_image};
  380. my $primary_route = "https://$query->{domain}/$query->{route}";
  381. $primary_route =~ s/[\/]+/\//g;
  382. my $display_name = $Theme::display_name || 'Another tCMS Site';
  383. my $extra_tags = '';
  384. my %sopts = (
  385. site => '',
  386. image => '',
  387. fb_app_id => '',
  388. site_name => $display_name,
  389. app_name => $display_name,
  390. title => $title,
  391. description => $meta_desc,
  392. url => $primary_route,
  393. );
  394. $sopts{site} = $Theme::twitter_account if $Theme::twitter_account;
  395. $sopts{image} = $image if $image;
  396. $sopts{fb_app_id} = $Theme::fb_app_id if $Theme::fb_app_id;
  397. if ( $query->{primary_post} && $query->{primary_post}{is_video} ) {
  398. #$sopts{player} = "$primary_route?embed=1";
  399. $sopts{player} = "https://$query->{domain}/$query->{primary_post}{href}";
  400. #XXX don't hardcode this
  401. $sopts{player_width} = 1280;
  402. $sopts{player_height} = 720;
  403. $extra_tags .= "<meta property='og:video:type' content='$query->{primary_post}{content_type}' />\n";
  404. }
  405. my $social = HTML::SocialMeta->new(%sopts);
  406. $meta_tags = eval { $social->create($card_type) };
  407. $meta_tags =~ s/content="video"/content="video:other"/mg if $meta_tags;
  408. $meta_tags .= $extra_tags if $extra_tags;
  409. print STDERR "WARNING: Theme misconfigured, social media tags will not be included\n$@\n" if $theme_dir && !$meta_tags;
  410. return ( $default_tags, $meta_desc, $meta_tags );
  411. }
  412. =head1 NORMAL ROUTES
  413. These are expected to either return a 200, or redirect to something which does.
  414. =head2 setup
  415. One time setup page; should only display to the first user to visit the site which we presume to be the administrator.
  416. =cut
  417. sub setup ($query) {
  418. File::Touch::touch("config/setup");
  419. Trog::Renderer->render(
  420. template => 'notconfigured.tx',
  421. data => {
  422. title => 'tCMS Requires Setup to Continue...',
  423. stylesheets => _build_themed_styles( ['notconfigured.css'] ),
  424. %$query,
  425. },
  426. contenttype => 'text/html',
  427. code => 200,
  428. );
  429. }
  430. =head2 totp
  431. Enable 2 factor auth via TOTP for the currently authenticated user.
  432. Returns a page with a QR code & TOTP uri for pasting into your authenticator app of choice.
  433. =cut
  434. sub totp ($query) {
  435. my $active_user = $query->{user};
  436. my $domain = $query->{domain};
  437. $query->{failure} //= -1;
  438. my ( $uri, $qr, $failure, $message, $totp ) = Trog::Auth::totp( $active_user, $domain );
  439. my $now_tm = time;
  440. my $now_string = strftime("%a %b %e T%H:%M:%SZ %Y", gmtime($now_tm));
  441. return Trog::Routes::HTML::index(
  442. {
  443. title => 'Enable TOTP 2-Factor Auth',
  444. theme_dir => Trog::Themes::td(),
  445. uri => $uri,
  446. qr => $qr,
  447. failure => $failure,
  448. message => $message,
  449. template => 'totp.tx',
  450. is_admin => 1,
  451. cur_code => $totp->expected_totp_code($now_tm),
  452. timestamp => $now_string,
  453. %$query,
  454. },
  455. undef,
  456. [qw{post.css}],
  457. );
  458. }
  459. =head2 login
  460. 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.
  461. =cut
  462. sub login ($query) {
  463. # Redirect if we actually have a logged in user.
  464. # Note to future me -- this user value is overwritten explicitly in server.psgi.
  465. # If that ever changes, you will die
  466. $query->{to} //= $query->{route};
  467. $query->{to} = '/config' if List::Util::any { $query->{to} eq $_ } qw{/login /logout};
  468. if ( $query->{user} ) {
  469. DEBUG("Login by $query->{user}, redirecting to $query->{to}");
  470. return $query->{tpsgi}->see_also( $query->{to} );
  471. }
  472. #Check and see if we have no users. If so we will just accept whatever creds are passed.
  473. my $hasusers = -f "config/has_users";
  474. my $btnmsg = $hasusers ? "Log In" : "Register";
  475. my $headers;
  476. my $has_totp = 0;
  477. if ( $query->{username} && $query->{password} ) {
  478. if ( !$hasusers ) {
  479. # Make the first user
  480. Trog::Auth::useradd( $query->{username}, $query->{display_name}, $query->{password}, ['admin'], $query->{contact_email} );
  481. # Add a stub user page and the initial series.
  482. my $dat = Trog::Data->new(Trog::Config::get());
  483. _setup_initial_db( $dat, $query->{username}, $query->{display_name}, $query->{contact_email} );
  484. # Ensure we stop registering new users
  485. File::Touch::touch("config/has_users");
  486. }
  487. $query->{failed} = 1;
  488. my $cookie = Trog::Auth::mksession( $query->{username}, $query->{password}, $query->{token}, $query->{ip} // '' );
  489. if ($cookie) {
  490. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  491. my $secure = '';
  492. $secure = '; Secure' if $query->{scheme} eq 'https';
  493. $headers = {
  494. "Set-Cookie" => "tcmslogin=$cookie; HttpOnly; SameSite=Strict$secure",
  495. };
  496. $query->{failed} = 0;
  497. }
  498. }
  499. $query->{failed} //= -1;
  500. return Trog::Renderer->render(
  501. template => 'login.tx',
  502. data => {
  503. title => 'tCMS 2 ~ Login',
  504. to => $query->{to},
  505. failure => int( $query->{failed} ),
  506. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  507. btnmsg => $btnmsg,
  508. stylesheets => _build_themed_styles( [qw{structure.css screen.css login.css}] ),
  509. theme_dir => Trog::Themes::td(),
  510. has_users => $hasusers,
  511. %$query,
  512. },
  513. headers => $headers,
  514. contenttype => 'text/html',
  515. code => 200,
  516. nocache => $query->{nocache},
  517. );
  518. }
  519. sub _setup_initial_db ( $dat, $user, $display_name, $contact_email ) {
  520. $dat->add(
  521. {
  522. "aclname" => "series",
  523. "acls" => [],
  524. "callback" => "Trog::Routes::HTML::series",
  525. method => 'GET',
  526. "data" => "Series",
  527. "href" => "/series",
  528. "local_href" => "/series",
  529. "preview" => "/img/sys/testpattern.jpg",
  530. "tags" => [qw{series topbar}],
  531. visibility => 'public',
  532. "title" => "Series",
  533. user => $user,
  534. form => 'series.tx',
  535. child_form => 'series.tx',
  536. aliases => [],
  537. },
  538. {
  539. "aclname" => "about",
  540. "acls" => [],
  541. "callback" => "Trog::Routes::HTML::series",
  542. method => 'GET',
  543. "data" => "About",
  544. "href" => "/about",
  545. "local_href" => "/about",
  546. "preview" => "/img/sys/testpattern.jpg",
  547. "tags" => [qw{series topbar public}],
  548. visibility => 'public',
  549. "title" => "About",
  550. user => $user,
  551. form => 'series.tx',
  552. child_form => 'profile.tx',
  553. aliases => [],
  554. },
  555. {
  556. "aclname" => "config",
  557. acls => [],
  558. "callback" => "Trog::Routes::HTML::config",
  559. 'method' => 'GET',
  560. "content_type" => "text/html",
  561. "data" => "Config",
  562. "href" => "/config",
  563. "local_href" => "/config",
  564. "preview" => "/img/sys/testpattern.jpg",
  565. "tags" => [qw{admin}],
  566. visibility => 'private',
  567. "title" => "Configure tCMS",
  568. user => $user,
  569. aliases => [],
  570. },
  571. {
  572. title => $display_name,
  573. data => 'Default user',
  574. preview => '/img/avatar/humm.gif',
  575. wallpaper => '/img/sys/testpattern.jpg',
  576. tags => ['about'],
  577. visibility => 'public',
  578. acls => ['admin'],
  579. local_href => "/users/$display_name",
  580. display_name => $display_name,
  581. contact_email => $contact_email,
  582. callback => "Trog::Routes::HTML::users",
  583. method => 'GET',
  584. user => $user,
  585. form => 'profile.tx',
  586. aliases => [],
  587. },
  588. );
  589. }
  590. =head2 logout
  591. Deletes your users' session and opens the index.
  592. =cut
  593. sub logout ($query) {
  594. Trog::Auth::killsession( $query->{user}, $query->{ip} // '' ) if $query->{user};
  595. delete $query->{user};
  596. return Trog::Routes::HTML::index($query);
  597. }
  598. =head2 config
  599. Renders the configuration page, or redirects you back to the login page.
  600. =cut
  601. sub config ( $query = {} ) {
  602. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  603. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  604. $query->{failure} //= -1;
  605. #XXX ACHTUNG config::simple has this brain damaged behavior of returning a multiple element array when you access something that does not exist.
  606. #XXX straight up dying would be preferrable.
  607. #XXX anyways, this means you can NEVER NEVER NEVER access a param from within a hash directly. YOU HAVE BEEN WARNED!
  608. my $conf = Trog::Config::get();
  609. state $theme = $conf->param('general.theme') // '';
  610. state $dm = $conf->param('general.data_model') // 'DUMMY';
  611. state $embeds = $conf->param('security.allow_embeds_from') // '';
  612. state $hostname = $conf->param('general.hostname') // '';
  613. return Trog::Routes::HTML::index(
  614. {
  615. title => 'Configure tCMS',
  616. theme_dir => Trog::Themes::td(),
  617. stylesheets => [qw{config.css}],
  618. scripts => [qw{post.js}],
  619. themes => _get_themes() || [],
  620. data_models => _get_data_models(),
  621. current_theme => $theme,
  622. current_data_model => $dm,
  623. message => $query->{message},
  624. failure => $query->{failure},
  625. to => '/config',
  626. scheme => $query->{scheme},
  627. embeds => $embeds,
  628. is_admin => 1,
  629. template => 'config.tx',
  630. %$query,
  631. hostname => $hostname,
  632. },
  633. undef,
  634. [qw{config.css}],
  635. );
  636. }
  637. =head2 resetpass
  638. =head2 do_resetpass
  639. =head2 do_totp_clear
  640. Routes for user service of their authentication details.
  641. =cut
  642. sub resetpass ($query) {
  643. $query->{failure} //= -1;
  644. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  645. return Trog::Routes::HTML::index(
  646. {
  647. title => 'Request Authentication Resets',
  648. theme_dir => Trog::Themes::td(),
  649. stylesheets => [qw{config.css}],
  650. scripts => [qw{post.js}],
  651. message => $query->{message},
  652. failure => $query->{failure},
  653. scheme => $query->{scheme},
  654. template => 'resetpass.tx',
  655. is_admin => $is_admin,
  656. %$query,
  657. },
  658. undef,
  659. [qw{config.css}],
  660. );
  661. }
  662. sub do_resetpass ($query) {
  663. my $user = $query->{username};
  664. # User Does not exist
  665. return $query->{tpsgi}->forbidden($query) if !Trog::Auth::user_exists($user);
  666. # User exists, but is not logged in this session
  667. return $query->{tpsgi}->forbidden($query) if !$query->{user} && Trog::Auth::user_has_session($user);
  668. my $token = Trog::Utils::uuid();
  669. my $newpass = $query->{password} // Trog::Utils::uuid();
  670. my $res = Trog::Auth::add_change_request( type => 'reset_pass', user => $user, secret => $newpass, token => $token );
  671. die "Could not add auth change request!" unless $res;
  672. # If the user is logged in, just do the deed, otherwise send them the token in an email
  673. if ( $query->{user} ) {
  674. return $query->{tpsgi}->see_also("/api/auth_change_request/$token");
  675. }
  676. Trog::Email::contact(
  677. $user,
  678. "root\@$query->{domain}",
  679. "$query->{domain}: Password reset URL for $user",
  680. { uri => "$query->{scheme}://$query->{domain}/api/auth_change_request/$token", template => 'password_reset.tx' }
  681. );
  682. return $query->{tpsgi}->see_also("/processed");
  683. }
  684. sub do_totp_clear ($query) {
  685. my $user = $query->{username};
  686. # User Does not exist
  687. return $query->{tpsgi}->forbidden($query) if !Trog::Auth::user_exists($user);
  688. # User exists, but is not logged in this session
  689. return $query->{tpsgi}->forbidden($query) if !$query->{user} && Trog::Auth::user_has_session($user);
  690. my $token = Trog::Utils::uuid();
  691. my $res = Trog::Auth::add_change_request( type => 'clear_totp', user => $user, token => $token );
  692. die "Could not add auth change request!" unless $res;
  693. # If the user is logged in, just do the deed, otherwise send them the token in an email
  694. if ( $query->{user} ) {
  695. return $query->{tpsgi}->see_also("/api/auth_change_request/$token");
  696. }
  697. Trog::Email::contact(
  698. $user,
  699. "root\@$query->{domain}",
  700. "$query->{domain}: Password reset URL for $user",
  701. { uri => "$query->{scheme}://$query->{domain}/api/auth_change_request/$token", template => 'totp_reset.tx' }
  702. );
  703. return $query->{tpsgi}->see_also("/processed");
  704. }
  705. sub _get_series ( $edit = 0 ) {
  706. state $data;
  707. $data //= Trog::Data->new(Trog::Config::get());
  708. my @series = $data->get(
  709. acls => [qw{public}],
  710. tags => [qw{topbar}],
  711. limit => 10,
  712. page => 1,
  713. );
  714. @series = map { $_->{local_href} = "/post$_->{local_href}"; $_ } @series if $edit;
  715. return @series;
  716. }
  717. sub _get_themes {
  718. my $dir = 'www/themes';
  719. opendir( my $dh, $dir ) || do { die "Can't opendir $dir: $!" unless $!{ENOENT} };
  720. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  721. closedir $dh;
  722. return \@tdirs;
  723. }
  724. sub _get_data_models {
  725. foreach my $incdir (@INC) {
  726. my $dir = "$incdir/Trog/Data";
  727. next unless -d $dir;
  728. opendir( my $dh, $dir ) || die "Can't opendir $dir: $!";
  729. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  730. closedir $dh;
  731. return \@dmods;
  732. }
  733. die "Could not find tCMS data modules! Is tCMS in \@INC?";
  734. }
  735. =head2 config_save
  736. Implements /config/save route. Saves what little configuration we actually use to config/main.cfg
  737. =cut
  738. sub config_save ($query) {
  739. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  740. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  741. my $conf = Trog::Config::get();
  742. $conf->param( 'general.theme', $query->{theme} ) if defined $query->{theme};
  743. $conf->param( 'general.data_model', $query->{data_model} ) if $query->{data_model};
  744. $conf->param( 'security.allow_embeds_from', $query->{embeds} ) if $query->{embeds};
  745. $conf->param( 'general.hostname', $query->{hostname} ) if $query->{hostname};
  746. $query->{failure} = 1;
  747. $query->{message} = "Failed to save configuration!";
  748. if ( $conf->write($Trog::Config::home_cfg) ) {
  749. $query->{failure} = 0;
  750. $query->{message} = "Configuration updated succesfully.";
  751. }
  752. #We need to reap the children with outdated configuration.
  753. $query->{tpsgi}->signal_restart_parent();
  754. return config($query);
  755. }
  756. =head2 themeclone
  757. Clone a theme by copying a directory.
  758. =cut
  759. sub themeclone ($query) {
  760. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  761. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  762. my ( $theme, $newtheme ) = ( $query->{theme}, $query->{newtheme} );
  763. my $themedir = 'www/themes';
  764. $query->{failure} = 1;
  765. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  766. require File::Copy::Recursive;
  767. if ( $theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" ) ) {
  768. $query->{failure} = 0;
  769. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  770. }
  771. return $query->{tpsgi}->see_also('/config');
  772. }
  773. =head2 post_save
  774. Saves posts submitted via the /post pages
  775. =cut
  776. sub post_save ($qq) {
  777. return $qq->{tpsgi}->see_also('/login') unless $qq->{user};
  778. return $qq->{tpsgi}->forbidden($qq) unless grep { $_ eq 'admin' } @{ $qq->{user_acls} };
  779. my $query = clone($qq);
  780. my $to = delete $query->{to};
  781. #Copy this down since it will be deleted later
  782. my $acls = $query->{acls};
  783. $query->{tags} = Trog::Utils::coerce_array( $query->{tags} );
  784. # Support data with multiple pages like presentations
  785. $query->{data} = Trog::Utils::coerce_array( $query->{data} ) if $query->{data_is_array};
  786. $query->{attachments} = Trog::Utils::coerce_array( $query->{attachments} );
  787. # Filter bits and bobs XXX this is done deeper in, may require removal
  788. delete $query->{primary_post};
  789. delete $query->{social_meta};
  790. delete $query->{deflate};
  791. delete $query->{acls};
  792. # Ensure there are no null tags
  793. @{ $query->{tags} } = grep { defined $_ } @{ $query->{tags} };
  794. # Posts will always be GET
  795. $query->{method} = 'GET';
  796. state $data;
  797. $data //= Trog::Data->new(Trog::Config::get());
  798. # A post that doesn't match its type's schema is the user's mistake, not a
  799. # server error, so hand the validation errors back rather than dying.
  800. local $@;
  801. eval { $data->add($query); 1 } or do {
  802. my @errors = Ref::Util::is_arrayref($@) ? @{$@} : ($@);
  803. my $why = "Post failed validation:\n" . join( "\n", @errors );
  804. # The full detail goes to the log; the user gets it in the banner on
  805. # the page they came from, rather than a dead-end 400.
  806. WARN("Rejected post from $qq->{user}: $why");
  807. return _feedback_redirect( $qq, '/secure' . $to, 1, $why );
  808. };
  809. # Instruct tpsgi to invalidate the cached render.
  810. $qq->{tpsgi}->add_post_close_callback(sub {
  811. # XXX there is not a great way to find what needs to be re-rendered because posts can include other posts.
  812. # As such we just have to nuke all the .html renders.
  813. $qq->{tpsgi}->invalidate_renders('html');
  814. });
  815. # Force a reload of the routing table
  816. $qq->{tpsgi}->signal_restart_parent();
  817. return _feedback_redirect( $qq, '/secure' . $to, 0, "Saved post '$query->{title}'." );
  818. }
  819. =head2 profile
  820. Saves / updates new users.
  821. =cut
  822. sub profile ($query) {
  823. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  824. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  825. # Find the user's post and edit it
  826. state $data;
  827. $data //= Trog::Data->new(Trog::Config::get());
  828. my @userposts = $data->get( tags => ['about'], acls => [qw{admin}] );
  829. # Users are always self-authored, you see
  830. my $user_obj = List::Util::first { ( $_->{user} || '' ) eq $query->{username} } @userposts;
  831. my $username = $query->{username};
  832. my $password = $query->{password};
  833. my $changed = $username ne ( $user_obj->{user} // '' )
  834. || $password
  835. || ( $query->{contact_email} // '' ) ne ( $user_obj->{contact_email} // '' )
  836. || ( $query->{display_name} // '' ) ne ( $user_obj->{display_name} // '' );
  837. #Make sure it is "self-authored", redact pw
  838. $query->{user} = delete $query->{username};
  839. delete $query->{password};
  840. # Use the display name as the title
  841. $query->{title} = $query->{display_name};
  842. my %merged = (
  843. %$user_obj,
  844. %$query,
  845. $query->{display_name} ? ( local_href => "/users/$query->{display_name}" ) : ( local_href => $user_obj->{local_href} ),
  846. );
  847. # Validate before touching the auth database, not after. useradd() does an
  848. # INSERT OR REPLACE on the user row, which cascades to the session table and
  849. # logs the user straight out -- doing that and *then* rejecting the post
  850. # leaves the credentials disagreeing with the profile post they came from.
  851. my @errors = Trog::DataModule::validate( clone( \%merged ) );
  852. if (@errors) {
  853. my $why = "Post failed validation:\n" . join( "\n", @errors );
  854. WARN("Rejected profile update from $query->{user}: $why");
  855. return $query->{tpsgi}->badrequest( $query, $why );
  856. }
  857. if ($changed) {
  858. my $for_user = Trog::Auth::acls4user($username);
  859. #TODO support non-admin users
  860. my @acls = @$for_user ? @$for_user : qw{admin};
  861. Trog::Auth::useradd( $username, $merged{display_name}, $password, \@acls, $merged{contact_email} );
  862. }
  863. return post_save( \%merged );
  864. }
  865. =head2 post_delete
  866. deletes posts.
  867. =cut
  868. sub post_delete ($query) {
  869. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  870. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  871. state $data;
  872. $data //= Trog::Data->new(Trog::Config::get());
  873. $data->delete($query) and die "Could not delete post";
  874. return $query->{tpsgi}->see_also( $query->{to} );
  875. }
  876. my %enrich = (
  877. 'invoice.tx' => sub {
  878. my ($post,$query) = @_;
  879. # TODO it's probably a performance problem doing this per post rather than only for the series entry
  880. my %ret = ( entities => [ _post_helper({ form => 'entities.tx', visibility => 'public' }, [], $query->{user_acls}) ] );
  881. return %ret unless ref $post->{data} eq 'ARRAY';
  882. # Figure out the payee/payor
  883. $ret{payee_entity} = List::Util::first { $_->{id} eq $post->{payee} } @{$ret{entities}};
  884. $ret{payor_entity} = List::Util::first { $_->{id} eq $post->{payor} } @{$ret{entities}};
  885. # Build total
  886. my $denom;
  887. my @prices = map {
  888. my $price = 0;
  889. ($denom, $price) = m/^Price:\s*(\D)(\d+)/mix;
  890. $price;
  891. } @{$post->{data}};
  892. $denom //= '$';
  893. $ret{total} = $denom.(List::Util::sum(@prices) // 0);
  894. return %ret;
  895. },
  896. );
  897. =head2 series
  898. Series specific view, much like the users/ route
  899. Displays identified series, not all series.
  900. =cut
  901. sub series ($query) {
  902. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  903. # rip away /secure if present
  904. $query->{route} =~ s|^/secure||;
  905. #we are either viewed one of two ways, /post/$id or /$aclname
  906. my ( undef, $aclname, $id ) = split( /\//, $query->{route} );
  907. $query->{aclname} = $aclname if !$id;
  908. $query->{id} = $id if $id;
  909. # Don't show topbar series on the series page. That said, don't exclude it from direct series view.
  910. $query->{exclude_tags} = ['topbar'] if !$is_admin && $aclname && $aclname eq 'series';
  911. #XXX I'd prefer to overload id to actually *be* the aclname...
  912. # but this way, accomodates things like the flat file time-indexing hack.
  913. # TODO I should probably have it for all posts, and make *everything* a series.
  914. # WE can then do threaded comments/posts.
  915. # That will essentially necessitate it *becoming* the ID for real.
  916. #Grab the relevant tag (aclname), then pass that to posts
  917. my @posts = _post_helper( $query, ['series'], $query->{user_acls} );
  918. # Enrich posts with additional data based on the template if necessary
  919. if (exists $enrich{$posts[0]->{child_form}}) {
  920. my $callback = $enrich{$posts[0]->{child_form}};
  921. my %extra_data = $callback->($posts[0], $query);
  922. foreach my $key (keys(%extra_data)) {
  923. $posts[0]->{$key} = $extra_data{$key};
  924. }
  925. }
  926. delete $query->{id};
  927. delete $query->{aclname};
  928. $query->{subhead} = $posts[0]->{data};
  929. $query->{title} = $posts[0]->{title};
  930. $query->{tag} = $posts[0]->{aclname};
  931. $query->{primary_post} = $posts[0];
  932. $query->{in_series} = 1;
  933. return posts($query);
  934. }
  935. =head2 avatars
  936. Returns the avatars.css.
  937. =cut
  938. sub avatars ($query) {
  939. push( @{ $query->{user_acls} }, 'public' );
  940. my $tags = Trog::Utils::coerce_array( $query->{tag} );
  941. my @posts = _post_helper( $query, $tags, $query->{user_acls} );
  942. if (@posts) {
  943. # Set the eTag so that we don't get a re-fetch
  944. $query->{etag} = "$posts[0]{id}-$posts[0]{version}";
  945. }
  946. @posts = map { $_->{id} =~ tr/-/_/; $_->{id} = "a_$_->{id}"; $_ } @posts;
  947. return Trog::Renderer->render(
  948. template => 'avatars.tx',
  949. data => {
  950. users => \@posts,
  951. %$query,
  952. },
  953. code => 200,
  954. contenttype => 'text/css',
  955. );
  956. }
  957. =head2 libravatar
  958. Implements the libravatar protocol (https://wiki.libravatar.org/running_your_own/).
  959. Accepts GET /avatar/{hash} where {hash} is the MD5 or SHA-256 of the user's
  960. lowercased email address, and redirects to their profile avatar image.
  961. Returns 404 when no matching user is found or the user has no avatar.
  962. =cut
  963. sub libravatar ($query) {
  964. my $hash = lc( $query->{avatar_hash} // '' );
  965. my $users = Trog::Auth::users_with_emails();
  966. my $matched_user;
  967. for my $u (@$users) {
  968. next unless $u->{contact_email};
  969. my $email = lc( $u->{contact_email} );
  970. if ( $hash eq sha256_hex($email) || $hash eq md5_hex($email) ) {
  971. $matched_user = $u->{name};
  972. last;
  973. }
  974. }
  975. return $query->{tpsgi}->notfound($query) unless $matched_user;
  976. my @posts = _post_helper( { author => $matched_user }, ['about'], [qw{public admin}] );
  977. my $preview = @posts ? $posts[0]->{preview} : '';
  978. return $query->{tpsgi}->notfound($query) unless $preview;
  979. return $query->{tpsgi}->redirect_permanent("/$preview");
  980. }
  981. =head2 users
  982. Implements direct user profile view.
  983. =cut
  984. sub users ($query) {
  985. # rip away /secure if present
  986. $query->{route} =~ s|^/secure||;
  987. # Capture the username
  988. my ( undef, undef, $display_name ) = split( /\//, $query->{route} );
  989. $display_name = URI::Escape::uri_unescape($display_name);
  990. my $username = Trog::Auth::display2username($display_name);
  991. return $query->{tpsgi}->notfound($query) unless $username;
  992. $query->{username} //= $username;
  993. push( @{ $query->{user_acls} }, 'public' );
  994. $query->{exclude_tags} = ['about'];
  995. # Don't show topbar series on the series page. That said, don't exclude it from direct series view.
  996. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  997. push( @{ $query->{exclude_tags} }, 'topbar' ) if !$is_admin;
  998. my @posts = _post_helper( { author => $query->{username} }, ['about'], $query->{user_acls} );
  999. $query->{id} = $posts[0]->{id};
  1000. $query->{title} = $posts[0]->{display_name};
  1001. $posts[0]->{title} = $posts[0]->{display_name};
  1002. $query->{user_obj} = $posts[0];
  1003. $query->{primary_post} = $posts[0];
  1004. $query->{in_series} = 1;
  1005. return posts($query);
  1006. }
  1007. =head2 posts
  1008. Display multi or single posts, supports RSS and pagination.
  1009. =cut
  1010. sub posts ( $query, $direct = 0 ) {
  1011. # Before we build the render data, not after: posts.tx is rendered here and
  1012. # handed to index() as content, so index()'s own absorb would be too late.
  1013. _absorb_feedback($query);
  1014. # Allow rss.xml to tell what posts to loop over
  1015. my $fmt = $query->{format} || '';
  1016. #Process the input URI to capture tag/id
  1017. $query->{route} //= $query->{to};
  1018. # rip away /secure if present
  1019. $query->{route} =~ s|^/secure||;
  1020. my ( undef, undef, $id ) = split( /\//, $query->{route} );
  1021. my $tags = Trog::Utils::coerce_array( $query->{tag} );
  1022. $query->{id} = $id if $id && !$query->{in_series};
  1023. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1024. push( @{ $query->{user_acls} }, 'public' );
  1025. push( @{ $query->{user_acls} }, 'unlisted' ) if $query->{id};
  1026. push( @{ $query->{user_acls} }, 'private' ) if $is_admin;
  1027. my @posts;
  1028. # Discover this user's visibility, so we can make them post in this category by default
  1029. my $user_visibility = 'public';
  1030. if ( $query->{user_obj} ) {
  1031. #Optimize the /users/* route
  1032. @posts = ( $query->{user_obj} );
  1033. $user_visibility = $query->{user_obj}->{visibility};
  1034. }
  1035. else {
  1036. if ( $query->{user} ) {
  1037. my @me = _post_helper( { author => $query->{user} }, ['about'], $query->{user_acls} );
  1038. $user_visibility = $me[0]->{visibility};
  1039. }
  1040. @posts = _post_helper( $query, $tags, $query->{user_acls} );
  1041. }
  1042. if ( $query->{id} ) {
  1043. $query->{primary_post} = $posts[0] if @posts;
  1044. }
  1045. #OK, so if we have a user as the ID we found, go grab the rest of their posts
  1046. if ( $query->{id} && @posts && List::Util::any { $_ eq 'about' } @{ $posts[0]->{tags} } ) {
  1047. my $user = shift(@posts);
  1048. my $id = delete $query->{id};
  1049. $query->{author} = $user->{user};
  1050. @posts = _post_helper( $query, $tags, $query->{user_acls} );
  1051. @posts = grep { $_->{id} ne $id } @posts;
  1052. unshift @posts, $user;
  1053. }
  1054. if ( !$is_admin ) {
  1055. return $query->{tpsgi}->notfound($query) unless @posts;
  1056. }
  1057. # Set the eTag so that we don't get a re-fetch
  1058. $query->{etag} = "$posts[0]{id}-$posts[0]{version}" if @posts;
  1059. #Correct page headers
  1060. my $ph = $themed ? _themed_title( $query->{route} ) : $query->{route};
  1061. return _rss( $query, $ph, \@posts ) if $fmt eq 'rss';
  1062. #XXX Is used by the sitemap, maybe just fix there?
  1063. my @post_aliases = map { $_->{local_href} } _get_series();
  1064. # Allow themes to put in custom headers/footers on posts
  1065. my ( $header, $footer );
  1066. $header = Trog::Renderer->render(
  1067. template => 'headers/' . $query->{primary_post}{header},
  1068. data => { theme_dir => Trog::Themes::td(), %$query },
  1069. component => 1,
  1070. contenttype => 'text/html',
  1071. ) if $query->{primary_post}{header};
  1072. return $header if ref $header eq 'ARRAY';
  1073. $footer = Trog::Renderer->render(
  1074. template => 'footers/' . $query->{primary_post}{footer},
  1075. data => { theme_dir => Trog::Themes::td(), %$query },
  1076. component => 1,
  1077. contenttype => 'text/html',
  1078. ) if $query->{primary_post}{footer};
  1079. return $header if ref $footer eq 'ARRAY';
  1080. # List the available headers/footers
  1081. my $headers = Trog::Themes::themed_templates_in_dir( "headers", 'text/html', 1 );
  1082. my $footers = Trog::Themes::themed_templates_in_dir( "footers", 'text/html', 1 );
  1083. #XXX used to be post.css, but probably not good anymore?
  1084. my $styles = [];
  1085. # Build page title if it wasn't set by a wrapping sub
  1086. $query->{title} = "$query->{domain} : $query->{title}" if $query->{title} && $query->{domain};
  1087. $query->{title} ||= @$tags && $query->{domain} ? "$query->{domain} : @$tags" : undef;
  1088. #Handle paginator vars
  1089. $query->{limit} ||= 25;
  1090. my $limit = int( $query->{limit} );
  1091. my $now_year = ( localtime(time) )[5] + 1900;
  1092. my $oldest_year = $now_year - 20; #XXX actually find oldest post year
  1093. # Handle post style.
  1094. if ( $query->{style} ) {
  1095. undef $header;
  1096. undef $footer;
  1097. }
  1098. my $older = !@posts ? 0 : $posts[-1]->{created};
  1099. $query->{failure} //= -1;
  1100. $query->{id} //= '';
  1101. my $newer = !@posts ? 0 : $posts[0]->{created};
  1102. #XXX messed up data has to be fixed unfortunately
  1103. @$tags = List::Util::uniq @$tags;
  1104. #Filter displaying visibility tags
  1105. my @visibuddies = qw{public unlisted private};
  1106. foreach my $post (@posts) {
  1107. @{ $post->{tags} } = grep {
  1108. my $tag = $_;
  1109. !grep { $tag eq $_ } @visibuddies
  1110. } @{ $post->{tags} };
  1111. }
  1112. #XXX note that we are explicitly relying on the first tag to be the ACL
  1113. my $aclselected = $tags->[0] || '';
  1114. my @acls = map {
  1115. $_->{selected} = $_->{aclname} eq $aclselected ? 'selected' : '';
  1116. $_
  1117. } _post_helper( {}, ['series'], $query->{user_acls} );
  1118. my $forms = Trog::Themes::themed_templates_in_dir( "forms", 'text/html', 1 );
  1119. my $edittype = $query->{primary_post} ? $query->{primary_post}->{child_form} : $query->{form};
  1120. my $tiled = $query->{primary_post} ? !$is_admin && $query->{primary_post}->{tiled} : 0;
  1121. state $data;
  1122. $data //= Trog::Data->new(Trog::Config::get());
  1123. # Grab the rest of the tags to dump into the edit form
  1124. my @tags_all = $data->tags();
  1125. #Filter out the visibilities and special series tags
  1126. @tags_all = grep {
  1127. my $subj = $_;
  1128. scalar( grep { $_ eq $subj } qw{public private unlisted admin series about topbar} ) == 0
  1129. } @tags_all;
  1130. @posts = map {
  1131. my $subject = $_;
  1132. my @et = grep {
  1133. my $subj = $_;
  1134. grep { $subj eq $_ } @tags_all
  1135. } @{ $subject->{tags} };
  1136. @et = grep { $_ ne $aclselected } @et;
  1137. $_->{extra_tags} = \@et;
  1138. $_
  1139. } @posts;
  1140. my @et = List::MoreUtils::singleton( @$tags, @tags_all );
  1141. $query->{author} = $query->{primary_post}{user} // $posts[0]{user};
  1142. my $picker = Trog::Component::EmojiPicker::render();
  1143. return $picker if ref $picker eq 'ARRAY';
  1144. # Enrich posts with additional data based on the template if necessary
  1145. foreach my $poast (@posts) {
  1146. if (exists $enrich{$poast->{form}}) {
  1147. my $callback = $enrich{$poast->{form}};
  1148. my %extra_data = $callback->($poast, $query);
  1149. foreach my $key (keys(%extra_data)) {
  1150. $poast->{$key} = $extra_data{$key};
  1151. }
  1152. }
  1153. }
  1154. #XXX the only reason this is needed is due to direct=1
  1155. #XXX is this even used?
  1156. my $content = Trog::Renderer->render(
  1157. template => 'posts.tx',
  1158. data => {
  1159. acls => \@acls,
  1160. can_edit => $is_admin,
  1161. forms => $forms,
  1162. post => { tags => $tags, extra_tags => \@et, form => $edittype, visibility => $user_visibility, addpost => 1 },
  1163. post_visibilities => \@visibuddies,
  1164. failure => $query->{failure},
  1165. to => $query->{to},
  1166. message => $query->{message} // ( $query->{failure} ? "Failed to add post!" : "Successfully added Post as $query->{id}" ),
  1167. direct => $direct,
  1168. title => $query->{title},
  1169. author => $query->{primary_post}{user} // $posts[0]{user},
  1170. primary_post => $query->{primary_post},
  1171. style => $query->{style},
  1172. posts => \@posts,
  1173. like => $query->{like},
  1174. in_series => exists $query->{in_series} || !!( $query->{route} =~ m/^\/series\// ),
  1175. route => $query->{route},
  1176. limit => $limit,
  1177. pages => scalar(@posts) == $limit,
  1178. older => $older,
  1179. newer => $newer,
  1180. sizes => [ 25, 50, 100 ],
  1181. rss => !$query->{id} && !$query->{older},
  1182. tiled => $tiled,
  1183. category => $ph,
  1184. subhead => $query->{subhead},
  1185. header => $header,
  1186. footer => $footer,
  1187. headers => $headers,
  1188. footers => $footers,
  1189. years => [ reverse( $oldest_year .. $now_year ) ],
  1190. months => [ 0 .. 11 ],
  1191. emoji_picker => $picker,
  1192. embed => $query->{embed},
  1193. nochrome => $query->{nochrome},
  1194. },
  1195. contenttype => 'text/html',
  1196. component => 1,
  1197. );
  1198. # Something exploded
  1199. return $content if ref $content eq "ARRAY";
  1200. return $content if $direct;
  1201. return Trog::Routes::HTML::index( $query, $content, $styles );
  1202. }
  1203. sub _themed_title ($path) {
  1204. return $path unless %Theme::paths;
  1205. return $Theme::paths{$path} ? $Theme::paths{$path} : $path;
  1206. }
  1207. sub _post_helper ( $query, $tags, $acls ) {
  1208. state $data;
  1209. $data //= Trog::Data->new(Trog::Config::get());
  1210. $query->{page} ||= 1;
  1211. $query->{limit} ||= 25;
  1212. my @d = $data->get(
  1213. older => $query->{older},
  1214. newer => $query->{newer},
  1215. page => int( $query->{page} ),
  1216. limit => int( $query->{limit} ),
  1217. tags => $tags,
  1218. exclude_tags => $query->{exclude_tags},
  1219. acls => $acls,
  1220. aclname => $query->{aclname},
  1221. like => $query->{like},
  1222. author => $query->{author},
  1223. id => $query->{id},
  1224. version => $query->{version},
  1225. form => $query->{form},
  1226. );
  1227. return map {
  1228. my $subj = $_;
  1229. $subj->{local_href} = "/secure$_->{local_href}";
  1230. $subj
  1231. } @d if $query->{user};
  1232. return @d;
  1233. }
  1234. =head2 sitemap
  1235. Return the sitemap index unless the static or a set of dynamic routes is requested.
  1236. We have a maximum of 99,990,000 posts we can make under this model
  1237. As we have 10,000 * 10,000 posts which are indexable via the sitemap format.
  1238. 1 top level index slot (10k posts) is taken by our static routes, the rest will be /posts.
  1239. Passing ?xml=1 will result in an appropriate sitemap.xml instead.
  1240. This is used to generate the static sitemaps as expected by search engines.
  1241. Passing compressed=1 will gzip the output.
  1242. =cut
  1243. sub sitemap ($query) {
  1244. state $data;
  1245. $data //= Trog::Data->new(Trog::Config::get());
  1246. state $etag = "sitemap-" . time();
  1247. my ( @to_map, $is_index, $route_type );
  1248. my $warning = '';
  1249. $query->{map} //= '';
  1250. if ( $query->{map} eq 'static' ) {
  1251. # Return the map of static routes
  1252. $route_type = 'Static Routes';
  1253. @to_map = grep { !defined $routes{$_}->{captures} && !$routes{$_}->{auth} && !$routes{$_}->{noindex} && !$routes{$_}->{nomap} } keys(%routes);
  1254. }
  1255. elsif ( !$query->{map} ) {
  1256. # Return the index instead
  1257. @to_map = ('static');
  1258. my $tot = $data->count();
  1259. my $size = 50000;
  1260. my $pages = int( $tot / $size ) + ( ( $tot % $size ) ? 1 : 0 );
  1261. # Truncate pages at 10k due to standard
  1262. my $clamped = $pages > 49999 ? 49999 : $pages;
  1263. $warning = "More posts than possible to represent in sitemaps & index! Old posts have been truncated." if $pages > 49999;
  1264. foreach my $page ( $clamped .. 1 ) {
  1265. push( @to_map, "$page" );
  1266. }
  1267. $is_index = 1;
  1268. }
  1269. else {
  1270. $route_type = "Posts: Page $query->{map}";
  1271. # Return the map of the particular range of dynamic posts
  1272. $query->{limit} = 50000;
  1273. $query->{page} = $query->{map};
  1274. @to_map = _post_helper( $query, [], ['public'] );
  1275. }
  1276. if ( $query->{xml} ) {
  1277. DEBUG("RENDER SITEMAP XML");
  1278. my $sm;
  1279. my $xml_date = time();
  1280. my $fmt = "xml";
  1281. $fmt .= ".gz" if $query->{compressed};
  1282. if ( !$query->{map} ) {
  1283. require WWW::SitemapIndex::XML;
  1284. $sm = WWW::SitemapIndex::XML->new();
  1285. foreach my $url (@to_map) {
  1286. $sm->add(
  1287. loc => "http://$query->{domain}/sitemap/$url.$fmt",
  1288. lastmod => $xml_date,
  1289. );
  1290. }
  1291. }
  1292. else {
  1293. require WWW::Sitemap::XML;
  1294. $sm = WWW::Sitemap::XML->new();
  1295. my $changefreq = $query->{map} eq 'static' ? 'monthly' : 'daily';
  1296. foreach my $url (@to_map) {
  1297. my $true_uri = "http://$query->{domain}$url";
  1298. if ( ref $url eq 'HASH' ) {
  1299. my $is_user_page = grep { $_ eq 'about' } @{ $url->{tags} };
  1300. $true_uri = "http://$query->{domain}/posts/$url->{id}";
  1301. $true_uri = "http://$query->{domain}/users/$url->{title}" if $is_user_page;
  1302. }
  1303. my %out = (
  1304. loc => $true_uri,
  1305. lastmod => $xml_date,
  1306. mobile => 1,
  1307. changefreq => $changefreq,
  1308. priority => 1.0,
  1309. );
  1310. if ( ref $url eq 'HASH' ) {
  1311. #add video & preview image if applicable
  1312. $out{images} = [
  1313. {
  1314. loc => "http://$query->{domain}$url->{href}",
  1315. caption => $url->{data},
  1316. title => substr( $url->{title}, 0, 100 ),
  1317. }
  1318. ]
  1319. if $url->{is_image};
  1320. # Truncate descriptions
  1321. my $desc = substr( $url->{data}, 0, 2048 ) || '';
  1322. my $href = $url->{href} || '';
  1323. my $preview = $url->{preview} || '';
  1324. my $domain = $query->{domain} || '';
  1325. $out{videos} = [
  1326. {
  1327. content_loc => "http://$domain$href",
  1328. thumbnail_loc => "http://$domain$preview",
  1329. title => substr( $url->{title}, 0, 100 ) || '',
  1330. description => $desc,
  1331. }
  1332. ]
  1333. if $url->{is_video};
  1334. }
  1335. $sm->add(%out);
  1336. }
  1337. }
  1338. my $xml = $sm->as_xml();
  1339. require IO::String;
  1340. my $buf = IO::String->new();
  1341. my $ct = 'application/xml';
  1342. $xml->toFH( $buf, 0 );
  1343. seek $buf, 0, 0;
  1344. if ( $query->{compressed} ) {
  1345. require IO::Compress::Gzip;
  1346. my $compressed = IO::String->new();
  1347. IO::Compress::Gzip::gzip( $buf => $compressed );
  1348. $ct = 'application/gzip';
  1349. $buf = $compressed;
  1350. seek $compressed, 0, 0;
  1351. }
  1352. #XXX This is one of the few exceptions where we don't use finish_render, as it *requires* gzip.
  1353. return [ 200, [ "Content-type" => $ct, 'ETag' => $etag ], $buf ];
  1354. }
  1355. @to_map = sort @to_map unless $is_index;
  1356. my $styles = ['sitemap.css'];
  1357. $query->{title} = "$query->{domain} : Sitemap";
  1358. $query->{template} = 'sitemap.tx',
  1359. $query->{to_map} = \@to_map,
  1360. $query->{is_index} = $is_index,
  1361. $query->{route_type} = $route_type,
  1362. $query->{etag} = $etag;
  1363. return Trog::Routes::HTML::index( $query, undef, $styles );
  1364. }
  1365. sub _rss ( $query, $subtitle, $posts ) {
  1366. require XML::RSS;
  1367. my $rss = XML::RSS->new( version => '2.0', stylesheet => '/styles/rss-style.xsl' );
  1368. my $now = DateTime->from_epoch( epoch => time() );
  1369. my $port = $query->{port} ? ":$query->{port}" : '';
  1370. $rss->channel(
  1371. title => "$query->{domain}",
  1372. subtitle => $subtitle,
  1373. link => "http://$query->{domain}$port/$query->{route}?format=xml",
  1374. language => 'en', #TODO localization
  1375. description => "$query->{domain} : $query->{route}",
  1376. pubDate => $now,
  1377. lastBuildDate => $now,
  1378. );
  1379. $rss->image(
  1380. title => $query->{domain},
  1381. url => "/favicon.ico",
  1382. link => "http://$query->{domain}$port",
  1383. width => 32,
  1384. height => 32,
  1385. description => "$query->{domain} favicon",
  1386. );
  1387. foreach my $post (@$posts) {
  1388. my $url = "http://$query->{domain}$port$post->{local_href}";
  1389. _post2rss( $rss, $url, $post );
  1390. next unless ref $post->{aliases} eq 'ARRAY';
  1391. foreach my $alias ( @{ $post->{aliases} } ) {
  1392. $url = "http://$query->{domain}$port$alias";
  1393. _post2rss( $rss, $url, $post );
  1394. }
  1395. }
  1396. return Trog::Renderer->render(
  1397. template => 'raw.tx',
  1398. data => {
  1399. etag => $query->{etag},
  1400. body => encode_utf8( $rss->as_string ),
  1401. scheme => $query->{scheme},
  1402. },
  1403. headers => { 'Content-Disposition' => 'inline; filename="rss.xml"' },
  1404. #XXX if you do the "proper" content-type of application/rss+xml, browsers download rather than display.
  1405. contenttype => "text/xml",
  1406. code => 200,
  1407. );
  1408. }
  1409. sub _post2rss ( $rss, $url, $post ) {
  1410. $rss->add_item(
  1411. title => $post->{title},
  1412. permaLink => $url,
  1413. link => $url,
  1414. enclosure => { url => $url, type => "text/html" },
  1415. description => "<![CDATA[$post->{data}]]>",
  1416. pubDate => DateTime->from_epoch( epoch => $post->{created} ), #TODO format like Thu, 23 Aug 1999 07:00:00 GMT
  1417. author => $post->{user}, #TODO translate to "email (user)" format
  1418. );
  1419. }
  1420. =head2 manual
  1421. Implements the /manual and /lib/* routes.
  1422. Basically a thin wrapper around Pod::Html.
  1423. =cut
  1424. sub manual ($query) {
  1425. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1426. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1427. require Pod::Html;
  1428. require Capture::Tiny;
  1429. #Fix links from Pod::HTML
  1430. $query->{module} =~ s/\.html$//g if $query->{module};
  1431. $query->{failure} //= -1;
  1432. my $infile = $query->{module} ? "$query->{module}.pm" : 'tCMS/Manual.pod';
  1433. my $found = 0;
  1434. foreach my $libdir (@INC) {
  1435. $found = $libdir if -f "$libdir/$infile";
  1436. last if $found;
  1437. }
  1438. return $query->{tpsgi}->notfound($query) unless $found;
  1439. my $content = capture { Pod::Html::pod2html( qw{--podpath=lib --podroot=.}, "--infile=$found/$infile" ) };
  1440. return Trog::Routes::HTML::index(
  1441. {
  1442. title => 'tCMS Manual',
  1443. theme_dir => Trog::Themes::td(),
  1444. content => $content,
  1445. template => 'manual.tx',
  1446. is_admin => 1,
  1447. %$query,
  1448. },
  1449. undef,
  1450. ['post.css'],
  1451. );
  1452. }
  1453. =head2 processed
  1454. Implements /processed.
  1455. The "we got it, go check your email" page, shown after a request that finishes
  1456. out of band -- password and TOTP resets, chiefly. Deliberately says nothing
  1457. about whether the account existed.
  1458. =cut
  1459. sub processed ($query) {
  1460. return Trog::Routes::HTML::index(
  1461. {
  1462. title => "Your request has been processed",
  1463. theme_dir => Trog::Themes::td(),
  1464. },
  1465. "Your request has been processed.<br /><br />You will recieve subsequent communications about this matter via means you have provided earlier.",
  1466. ['post.css']
  1467. );
  1468. }
  1469. =head2 metrics
  1470. Implements /metrics. Admin only.
  1471. Renders the request metrics dashboard. The page pulls its actual numbers from
  1472. /api/requests_per over XHR and draws them with chart.js, so there's nothing to
  1473. compute here.
  1474. =cut
  1475. sub metrics ($query) {
  1476. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1477. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1478. $query->{failure} //= -1;
  1479. return Trog::Routes::HTML::index(
  1480. {
  1481. title => 'tCMS Metrics',
  1482. theme_dir => Trog::Themes::td(),
  1483. template => 'metrics.tx',
  1484. is_admin => 1,
  1485. %$query,
  1486. },
  1487. undef,
  1488. ['post.css'],
  1489. ['chart.js'],
  1490. );
  1491. }
  1492. =head2 sessions
  1493. Implements /sessions. Admin only.
  1494. The session audit log: logins, logouts and failures, most recent first.
  1495. Filterable by username and event type via the filter_user and filter_event
  1496. parameters, and capped by limit (100 by default).
  1497. Timestamps are formatted here rather than in the template, and session ids are
  1498. truncated to their first 8 characters -- there's no reason to put a live
  1499. session id on a page.
  1500. =cut
  1501. sub sessions ($query) {
  1502. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1503. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1504. my $limit = int( $query->{limit} // 100 );
  1505. my $events = Trog::Auth::audit_log(
  1506. limit => $limit,
  1507. username => $query->{filter_user} // '',
  1508. event_type => $query->{filter_event} // '',
  1509. );
  1510. # Format timestamps for display
  1511. @$events = map {
  1512. my $e = {%$_};
  1513. my @t = localtime( $e->{event_time} );
  1514. $e->{event_ts} = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $t[5] + 1900, $t[4] + 1, $t[3], $t[2], $t[1], $t[0] );
  1515. $e->{session_short} = $e->{session_id} ? substr( $e->{session_id}, 0, 8 ) . '...' : '';
  1516. $e
  1517. } @$events;
  1518. return Trog::Routes::HTML::index(
  1519. {
  1520. title => 'tCMS Session Audit Log',
  1521. theme_dir => Trog::Themes::td(),
  1522. template => 'sessions.tx',
  1523. is_admin => 1,
  1524. events => $events,
  1525. limit => $limit,
  1526. filter_user => $query->{filter_user} // '',
  1527. filter_event => $query->{filter_event} // '',
  1528. %$query,
  1529. },
  1530. undef,
  1531. ['post.css'],
  1532. );
  1533. }
  1534. # The canned includes the wizard is willing to splice into a generated form.
  1535. # Deliberately a whitelist keyed on the checkbox name -- the include name ends
  1536. # up interpolated straight into a template file, so it can never come from the
  1537. # submitted data.
  1538. our %wizard_includes = (
  1539. inc_preview => 'preview.tx',
  1540. inc_visibility => 'visibility.tx',
  1541. inc_acls => 'acls.tx',
  1542. inc_tags => 'tags.tx',
  1543. inc_aliases => 'aliases.tx',
  1544. inc_attachments => 'attachments.tx',
  1545. );
  1546. # Emitted in this order, so generated forms read like the hand-written ones.
  1547. our @wizard_include_order = qw{inc_preview inc_visibility inc_acls inc_tags inc_aliases inc_attachments};
  1548. # Every checkbox on the wizard, and which of them start out ticked.
  1549. our @wizard_checkboxes = ( qw{wrapper inc_post_title inc_post_tags inc_title_input}, @wizard_include_order, 'overwrite' );
  1550. our %wizard_checked_by_default = map { $_ => 1 } qw{wrapper inc_post_title inc_post_tags inc_title_input inc_preview inc_visibility inc_acls inc_tags inc_aliases};
  1551. # Which HTML input the wizard emits, and what that field is in the sidecar's
  1552. # OpenAPIv3 schema. No 'file': _process() in Trog::DataModule only knows how to
  1553. # turn the four hardcoded upload fields into hrefs, so a custom file field would
  1554. # store an HTTP::Body::OctetStream that nothing ever picks up. Point folks at
  1555. # the attachment uploader instead.
  1556. our %wizard_field_types = (
  1557. text => { type => 'string' },
  1558. url => { type => 'string' },
  1559. date => { type => 'string' },
  1560. textarea => { type => 'string' },
  1561. number => { type => 'integer' },
  1562. checkbox => { type => 'boolean' },
  1563. );
  1564. # Field names which aren't in %schema but would still collide with something.
  1565. our @wizard_reserved = qw{app to form data_is_array addpost extra_tags is_image is_video is_audio is_profile content_type version};
  1566. =head2 post_wizard
  1567. Implements /admin/wyzzerdd. Admin only.
  1568. The post type wizard: lists the post types which currently exist and offers a
  1569. form for building a new one. See post_wizard_save() for what happens when that
  1570. form comes back.
  1571. Re-rendered by post_wizard_save() on both success and failure, so it keeps the
  1572. submitted values and checkbox states rather than making the admin retype
  1573. everything after a rejected submission.
  1574. =cut
  1575. sub post_wizard ($query) {
  1576. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1577. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1578. $query->{failure} //= -1;
  1579. # Get the existing post types
  1580. my $forms = Trog::Themes::themed_templates_in_dir( "forms", 'text/html', 1 );
  1581. # Sticky checkboxes. Nothing is submitted on a fresh GET, so fall back to
  1582. # the defaults rather than rendering everything unticked.
  1583. my %checked = map { $_ => ( $query->{wizard_submitted} ? $query->{$_} : $wizard_checked_by_default{$_} ) ? 'checked' : '' } @wizard_checkboxes;
  1584. return Trog::Routes::HTML::index(
  1585. {
  1586. # Sticky form values first, so a failed submission doesn't lose the
  1587. # admin's work -- but everything the template actually depends on is
  1588. # set *after* this, as the whole of %$query is attacker controlled.
  1589. %$query,
  1590. title => 'tCMS Post Wizard',
  1591. theme_dir => Trog::Themes::td(),
  1592. template => 'post_wizard.tx',
  1593. is_admin => 1,
  1594. forms => $forms,
  1595. forms_dir => Trog::Themes::forms_dir(),
  1596. checked => \%checked,
  1597. name => _wizard_scalar( $query->{name} ),
  1598. title_placeholder => _wizard_scalar( $query->{title_placeholder} ),
  1599. body_form => _wizard_scalar( $query->{body_form} ),
  1600. display => _wizard_scalar( $query->{display} ),
  1601. failure => $query->{failure},
  1602. message => $query->{message} // '',
  1603. to => $query->{to} // '',
  1604. },
  1605. undef,
  1606. ['post.css'],
  1607. );
  1608. }
  1609. =head2 post_wizard_save
  1610. Implements POST /admin/wyzzerdd/save.
  1611. Writes a new post type template into whichever forms directory is currently in
  1612. use, along with a JSON sidecar naming its custom fields so that
  1613. Trog::DataModule::schema_for will merge it over the base post schema, so the
  1614. type's own fields survive validation at save time.
  1615. =cut
  1616. sub post_wizard_save ($query) {
  1617. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1618. return $query->{tpsgi}->forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1619. # Anchored capture rather than a substitution, so anything containing a '/'
  1620. # or a '..' simply fails to match instead of being silently scrubbed into
  1621. # something that still escapes the directory.
  1622. my ($name) = _wizard_scalar( $query->{name} ) =~ m/^([A-Za-z0-9_-]+)$/;
  1623. return _wizard_fail( $query, "Post type names may only contain letters, numbers, '-' and '_'." ) unless $name;
  1624. # Whichever forms dir is in use: the theme's if it has one, the stock one
  1625. # otherwise. Never mkdir it -- silently conjuring a forms/ dir inside a
  1626. # theme is not something an admin asked for by pressing this button.
  1627. my $dir = Trog::Themes::forms_dir();
  1628. return _wizard_fail( $query, "Forms directory '$dir' does not exist, or is not writable." ) unless -d $dir && -w $dir;
  1629. my $tx_file = "$dir/$name.tx";
  1630. my $json_file = "$dir/$name.json";
  1631. my $overwriting = -e $tx_file;
  1632. return _wizard_fail( $query, "Post type '$name.tx' already exists. Tick 'Overwrite' if you meant to replace it." )
  1633. if $overwriting && !$query->{overwrite};
  1634. my $fields = _wizard_fields($query);
  1635. my @includes = grep { $query->{$_} } @wizard_include_order;
  1636. my $body_form = _wizard_scalar( $query->{body_form} ) eq 'form_multi.tx' ? 'form_multi.tx' : 'form_common.tx';
  1637. my $spec = _wizard_sidecar( $name, $fields, \@includes, $body_form );
  1638. local $@;
  1639. eval {
  1640. Path::Tiny::path($tx_file)->spew_utf8( _wizard_template( $query, $fields, \@includes, $body_form ) );
  1641. Path::Tiny::path($json_file)->spew_utf8( JSON::MaybeXS->new( pretty => 1, canonical => 1 )->encode($spec) );
  1642. 1;
  1643. } or return _wizard_fail( $query, "Failed to write post type '$name': $@" );
  1644. INFO("Post type '$name' written to $tx_file by $query->{user}");
  1645. # Nothing else is needed to publish a new type: themed_templates_in_dir()
  1646. # re-reads
  1647. # the directory every call, and Xslate resolves includes lazily, so both the
  1648. # wizard's own list and the series child_form dropdown pick it up on the
  1649. # next request without a restart. Overwriting an *existing* type is another
  1650. # matter -- that changes how already-rendered anonymous pages should look.
  1651. if ($overwriting) {
  1652. $query->{tpsgi}->add_post_close_callback(
  1653. sub {
  1654. $query->{tpsgi}->invalidate_renders('html');
  1655. }
  1656. );
  1657. }
  1658. return post_wizard(
  1659. {
  1660. %$query,
  1661. wizard_submitted => 1,
  1662. failure => 0,
  1663. message => "Created post type '$name.tx'.",
  1664. to => '/admin/wyzzerdd',
  1665. }
  1666. );
  1667. }
  1668. # Repeated params arrive as arrayrefs; anywhere we want one string, insist on one string.
  1669. sub _wizard_scalar ( $value = '' ) {
  1670. return '' if !defined $value || ref $value;
  1671. return $value;
  1672. }
  1673. sub _wizard_fail ( $query, $message ) {
  1674. WARN($message);
  1675. return post_wizard(
  1676. {
  1677. %$query,
  1678. wizard_submitted => 1,
  1679. failure => 1,
  1680. message => $message,
  1681. }
  1682. );
  1683. }
  1684. =head2 _kolon_safe
  1685. Make a submitted string safe to splice into a generated Kolon template.
  1686. Newlines have to go, as a ':' at the start of a line is a Kolon directive, and
  1687. the angle brackets have to go so that '<:' can never be reassembled.
  1688. =cut
  1689. sub _kolon_safe ( $string = '' ) {
  1690. $string = _wizard_scalar($string);
  1691. $string =~ s/[\r\n]+/ /g;
  1692. $string =~ s/&/&amp;/g;
  1693. $string =~ s/</&lt;/g;
  1694. $string =~ s/>/&gt;/g;
  1695. $string =~ s/"/&quot;/g;
  1696. return $string;
  1697. }
  1698. =head2 _wizard_fields
  1699. Zip the parallel param_* arrays submitted by the wizard back into a list of
  1700. field definitions. Every row always submits exactly one of each param, so the
  1701. arrays stay aligned even when a row is left blank.
  1702. =cut
  1703. sub _wizard_fields ($query) {
  1704. my $names = Trog::Utils::coerce_array( $query->{param_name} );
  1705. my $types = Trog::Utils::coerce_array( $query->{param_type} );
  1706. my $labels = Trog::Utils::coerce_array( $query->{param_label} );
  1707. my $phs = Trog::Utils::coerce_array( $query->{param_placeholder} );
  1708. my $reqs = Trog::Utils::coerce_array( $query->{param_required} );
  1709. my ( @fields, %seen );
  1710. foreach my $index ( 0 .. $#$names ) {
  1711. my ($fname) = lc( _wizard_scalar( $names->[$index] ) ) =~ m/^([a-z][a-z0-9_]{0,31})$/;
  1712. # Blank and bogus rows just get dropped.
  1713. next unless $fname;
  1714. next if $seen{$fname}++;
  1715. # Never let a custom field shadow a core post attribute.
  1716. next if exists $Trog::DataModule::post_schema{properties}{$fname};
  1717. next if grep { $fname eq $_ } @wizard_reserved;
  1718. my $type = _wizard_scalar( $types->[$index] );
  1719. $type = 'text' unless $wizard_field_types{$type};
  1720. push(
  1721. @fields,
  1722. {
  1723. name => $fname,
  1724. type => $type,
  1725. label => _kolon_safe( $labels->[$index] ) || ucfirst($fname),
  1726. placeholder => _kolon_safe( $phs->[$index] ),
  1727. required => _wizard_scalar( $reqs->[$index] ) ? 1 : 0,
  1728. }
  1729. );
  1730. }
  1731. return \@fields;
  1732. }
  1733. =head2 _wizard_sidecar
  1734. Turn the wizard's field list into the post type's JSON sidecar: an OpenAPIv3
  1735. object schema describing what this type ingests, with the wizard's own UI
  1736. metadata hung off x- extension keys so there's only one file to keep in sync.
  1737. Trog::DataModule::schema_for() merges this over the base post schema.
  1738. =cut
  1739. sub _wizard_sidecar ( $name, $fields, $includes, $body_form ) {
  1740. my %properties;
  1741. my @required;
  1742. foreach my $field (@$fields) {
  1743. my $property = { %{ $wizard_field_types{ $field->{type} } } };
  1744. $property->{'x-tcms-input'} = $field->{type};
  1745. $property->{'x-tcms-label'} = $field->{label};
  1746. $property->{'x-tcms-placeholder'} = $field->{placeholder} if length $field->{placeholder};
  1747. $properties{ $field->{name} } = $property;
  1748. push( @required, $field->{name} ) if $field->{required};
  1749. }
  1750. my %spec = (
  1751. 'x-tcms-post-type' => {
  1752. name => $name,
  1753. generated => JSON::MaybeXS::true(),
  1754. generator => 'Trog::Routes::HTML::post_wizard_save',
  1755. body_form => $body_form,
  1756. includes => [ map { $wizard_includes{$_} } @$includes ],
  1757. },
  1758. type => 'object',
  1759. properties => \%properties,
  1760. );
  1761. $spec{required} = \@required if @required;
  1762. return \%spec;
  1763. }
  1764. sub _wizard_field_html ($field) {
  1765. my ( $n, $t, $l, $p ) = @$field{qw{name type label placeholder}};
  1766. my $required = $field->{required} ? 'required ' : '';
  1767. return qq| $l<br /><textarea ${required}class="cooltext" name="$n" placeholder="$p"><: \$post.$n :></textarea>\n|
  1768. if $t eq 'textarea';
  1769. return qq| <label for="<: \$post.id :>-$n">$l<input id="<: \$post.id :>-$n" class="coolcb" type="checkbox" name="$n" value="1" <: if ( \$post.$n ) { "checked" } :> /></label><br />\n|
  1770. if $t eq 'checkbox';
  1771. return qq| $l<br /><input ${required}class="cooltext" type="$t" name="$n" placeholder="$p" value="<: \$post.$n :>" />\n|;
  1772. }
  1773. =head2 _wizard_template
  1774. Assemble the actual .tx file, following the shape of the hand-written forms:
  1775. a display half guarded by !$post.addpost, and an edit half guarded by $can_edit.
  1776. =cut
  1777. sub _wizard_template ( $query, $fields, $includes, $body_form ) {
  1778. my $placeholder = _kolon_safe( $query->{title_placeholder} ) || 'Iowa Man Destroys Moon';
  1779. # NOT escaped, on purpose. Letting an admin write template code is the
  1780. # entire point of the wizard, and it is no more privileged than the data
  1781. # field of any post, which already gets run through render_it(). Both
  1782. # sides of this route are behind the admin ACL.
  1783. my $display = _wizard_scalar( $query->{display} );
  1784. my $out = "<!-- Generated by the tCMS Post Type Wizard. Regenerating this type will overwrite any hand edits. -->\n";
  1785. $out .= qq|<div class="post <: \$style :>">\n| if $query->{wrapper};
  1786. $out .= qq| : if ( !\$post.addpost ) {\n|;
  1787. $out .= qq| : include "post_title.tx";\n| if $query->{inc_post_title};
  1788. $out .= qq| : include "post_tags.tx";\n| if $query->{inc_post_tags};
  1789. $out .= "$display\n" if $display;
  1790. $out .= qq| : }\n\n|;
  1791. $out .= qq| : if ( \$can_edit ) {\n|;
  1792. $out .= qq| <div class="postedit">\n|;
  1793. $out .= qq| : include "edit_head.tx";\n|;
  1794. $out .= qq| <form class="Submissions" action="/post/save" method="POST" enctype="multipart/form-data">\n|;
  1795. $out .= qq| Title *<br /><input required class="cooltext" type="text" name="title" placeholder="$placeholder" value="<: \$post.title :>" />\n|
  1796. if $query->{inc_title_input};
  1797. $out .= _wizard_field_html($_) foreach @$fields;
  1798. foreach my $include (@$includes) {
  1799. $out .= qq| : include "$wizard_includes{$include}";\n|;
  1800. }
  1801. # Always last, and never optional: this is what carries the post body, the
  1802. # app/to/id/form hiddens and the submit button.
  1803. $out .= qq| : include "$body_form";\n|;
  1804. $out .= qq| </form>\n|;
  1805. $out .= qq| : include "edit_foot.tx";\n|;
  1806. $out .= qq| </div>\n|;
  1807. $out .= qq| : }\n|;
  1808. $out .= qq|</div>\n| if $query->{wrapper};
  1809. return $out;
  1810. }
  1811. # basically a file rewrite rule for themes
  1812. =head2 icon
  1813. Implements the /img/icon/* routes.
  1814. Serves a themed icon, falling back to the stock one. A rewrite rule with extra
  1815. steps, essentially, so that themes can replace individual icons.
  1816. =cut
  1817. sub icon ($query) {
  1818. my $path = $query->{route};
  1819. my $tpath = Trog::Themes::themed("img/icon/$path");
  1820. return $query->{tpsgi}->serve( $path, $tpath, $query->{start}, $query->{streaming}, $query->{ranges}, $query->{last_fetched}, $query->{deflate} );
  1821. }
  1822. =head2 totp_qr
  1823. Implements the /totp/* routes.
  1824. Serves the QR code generated when a user enables TOTP. These live outside
  1825. www/, so they go out through serve() rather than the static file handler --
  1826. handing someone else's enrolment QR out to the world would be handing them the
  1827. shared secret.
  1828. =cut
  1829. sub totp_qr ($query) {
  1830. my $fname = basename($query->{route});
  1831. # For authenticated content, we have to now do a serve().
  1832. return $query->{tpsgi}->serve(
  1833. "totp/$fname",
  1834. "totp/$fname",
  1835. $query->{start},
  1836. $query->{streaming},
  1837. $query->{ranges},
  1838. $query->{last_fetched},
  1839. $query->{deflate},
  1840. );
  1841. }
  1842. =head2 rss_style
  1843. Implements /styles/rss-style.xsl.
  1844. The XSL stylesheet which makes the RSS feed legible in a browser. The header
  1845. and footer are rendered here and passed in as strings because the output is
  1846. XSL rather than HTML, so an include directive isn't available.
  1847. =cut
  1848. sub rss_style ($query) {
  1849. $query->{port} = ":$query->{port}" if $query->{port};
  1850. $query->{title} = qq{<xsl:value-of select="rss/channel/title"/>};
  1851. $query->{no_doctype} = 1;
  1852. # Due to this being html rather than XML, we can't use an include directive.
  1853. $query->{header} = Trog::Renderer->render( template => 'header.tx', data => $query, contenttype => 'text/html', component => 1 );
  1854. $query->{footer} = Trog::Renderer->render( template => 'footer.tx', data => $query, contenttype => 'text/html', component => 1 );
  1855. return Trog::Renderer->render(
  1856. template => 'rss-style.tx',
  1857. contenttype => 'text/xsl',
  1858. data => $query,
  1859. code => 200,
  1860. );
  1861. }
  1862. sub _build_themed_styles ($styles) {
  1863. my @styles = map { ( Trog::Themes::themed_style("$_") ) } @{ Trog::Utils::coerce_array($styles) };
  1864. return \@styles;
  1865. }
  1866. sub _build_themed_scripts ($scripts) {
  1867. my @scripts = map { Trog::Themes::themed_script("$_") } @{ Trog::Utils::coerce_array($scripts) };
  1868. return \@scripts;
  1869. }
  1870. =head2 finish_render($template, $vars, %headers)
  1871. Render a full page, as opposed to a component.
  1872. Fills in the defaults every page needs (lang, title, status code, content type,
  1873. cache control), resolves stylesheet and script names through the theme, makes
  1874. their paths absolute, renders the header and footer, and hands the lot to
  1875. Trog::Renderer.
  1876. Just about everything in this module ends up here; index() is the usual way in.
  1877. =cut
  1878. sub finish_render ( $template, $vars, %headers ) {
  1879. #XXX default vars that need to be pulled from config
  1880. $vars->{lang} //= 'en-US';
  1881. $vars->{title} //= 'tCMS';
  1882. $vars->{stylesheets} //= [];
  1883. $vars->{print_styles} //= [qw{structure.css print.css}];
  1884. $vars->{scripts} //= [];
  1885. # Theme-ize the paths
  1886. $vars->{stylesheets} = [ @{ _build_themed_styles( $vars->{stylesheets} ) } ];
  1887. $vars->{print_styles} = [ @{ _build_themed_styles( $vars->{print_styles} ) } ];
  1888. $vars->{scripts} = [ map { s/^www\///; $_ } @{ _build_themed_scripts( $vars->{scripts} ) } ];
  1889. # Add in avatars.css, it's special
  1890. push( @{ $vars->{stylesheets} }, "/styles/avatars.css" );
  1891. # Absolute-ize the paths for scripts & stylesheets
  1892. @{ $vars->{stylesheets} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{stylesheets} };
  1893. @{ $vars->{print_styles} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{print_styles} };
  1894. @{ $vars->{scripts} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{scripts} };
  1895. # TODO Smash together the stylesheets and minify
  1896. $vars->{contenttype} //= $Trog::Vars::content_types{html};
  1897. $vars->{cachecontrol} //= $Trog::Vars::cache_control{revalidate};
  1898. $vars->{code} ||= 200;
  1899. $vars->{theme_dir} =~ s/^\/www\/// if $vars->{theme_dir};
  1900. $vars->{header} = Trog::Renderer->render( template => 'header.tx', data => $vars, contenttype => 'text/html', component => 1 );
  1901. $vars->{footer} = Trog::Renderer->render( template => 'footer.tx', data => $vars, contenttype => 'text/html', component => 1 );
  1902. return Trog::Renderer->render( template => $template, data => $vars, contenttype => 'text/html', code => $vars->{code} );
  1903. }
  1904. 1;