HTML.pm 96 KB

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