HTML.pm 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523
  1. package Trog::Routes::HTML;
  2. use 5.040;
  3. use re '/aasx';
  4. use warnings FATAL => 'all';
  5. no warnings qw{once};
  6. use POSIX qw{strftime};
  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 URI();
  22. use URI::Escape();
  23. use FindBin::libs;
  24. use Trog::Log qw{:all};
  25. use Trog::Utils;
  26. use Trog::Config;
  27. use Trog::Auth;
  28. use Trog::Data;
  29. use Trog::Themes;
  30. use Trog::Bundle;
  31. use Trog::Renderer;
  32. use Trog::Email;
  33. use Trog::DataSource;
  34. use CGI::Cookie ();
  35. our $landing_page = 'default.tx';
  36. # Note to maintainers: never ever remove backends from this list.
  37. # the auth => 1 is a crucial protection.
  38. our %routes = (
  39. default => {
  40. callback => \&Trog::Routes::HTML::setup,
  41. nomap => 1,
  42. },
  43. '/index' => {
  44. method => 'GET',
  45. callback => \&Trog::Routes::HTML::index,
  46. },
  47. # This should only be enabled to debug
  48. # '/setup' => {
  49. # method => 'GET',
  50. # callback => \&Trog::Routes::HTML::setup,
  51. # },
  52. '/login' => {
  53. method => 'GET',
  54. callback => \&Trog::Routes::HTML::login,
  55. noindex => 1,
  56. },
  57. '/logout' => {
  58. method => 'GET',
  59. callback => \&Trog::Routes::HTML::logout,
  60. noindex => 1,
  61. nocache => 1,
  62. },
  63. '/auth' => {
  64. method => 'POST',
  65. callback => \&Trog::Routes::HTML::login,
  66. nocache => 1,
  67. noindex => 1,
  68. },
  69. '/totp' => {
  70. method => 'GET',
  71. auth => 1,
  72. # The one page a user who has not enrolled yet is allowed to reach.
  73. totp_exempt => 1,
  74. callback => \&Trog::Routes::HTML::totp,
  75. },
  76. '/secrets' => {
  77. method => 'GET',
  78. auth => 1,
  79. nocache => 1,
  80. noindex => 1,
  81. callback => \&Trog::Routes::HTML::secrets,
  82. },
  83. '/secrets/save' => {
  84. method => 'POST',
  85. auth => 1,
  86. nocache => 1,
  87. noindex => 1,
  88. callback => \&Trog::Routes::HTML::secrets_save,
  89. },
  90. '/secrets/forget' => {
  91. method => 'POST',
  92. auth => 1,
  93. nocache => 1,
  94. noindex => 1,
  95. callback => \&Trog::Routes::HTML::secrets_forget,
  96. },
  97. '/post/save' => {
  98. method => 'POST',
  99. auth => 1,
  100. callback => \&Trog::Routes::HTML::post_save,
  101. },
  102. '/post/delete' => {
  103. method => 'POST',
  104. auth => 1,
  105. callback => \&Trog::Routes::HTML::post_delete,
  106. },
  107. '/config/save' => {
  108. method => 'POST',
  109. auth => 1,
  110. callback => \&Trog::Routes::HTML::config_save,
  111. },
  112. '/themeclone' => {
  113. method => 'POST',
  114. auth => 1,
  115. callback => \&Trog::Routes::HTML::themeclone,
  116. },
  117. '/profile' => {
  118. method => 'POST',
  119. auth => 1,
  120. callback => \&Trog::Routes::HTML::profile,
  121. },
  122. '/manual' => {
  123. method => 'GET',
  124. auth => 1,
  125. callback => \&Trog::Routes::HTML::manual,
  126. },
  127. '/lib/{module+}' => {
  128. method => 'GET',
  129. auth => 1,
  130. callback => \&Trog::Routes::HTML::manual,
  131. },
  132. '/password_reset' => {
  133. method => 'GET',
  134. callback => \&Trog::Routes::HTML::resetpass,
  135. noindex => 1,
  136. },
  137. # When we are logged in, we get a diff ver of the page.
  138. '/secure/password_reset' => {
  139. method => 'GET',
  140. callback => \&Trog::Routes::HTML::resetpass,
  141. auth => 1,
  142. },
  143. '/request_password_reset' => {
  144. method => 'POST',
  145. callback => \&Trog::Routes::HTML::do_resetpass,
  146. noindex => 1,
  147. nocache => 1,
  148. },
  149. '/processed' => {
  150. method => 'GET',
  151. callback => \&Trog::Routes::HTML::processed,
  152. noindex => 1,
  153. },
  154. '/metrics' => {
  155. method => 'GET',
  156. auth => 1,
  157. callback => \&Trog::Routes::HTML::metrics,
  158. },
  159. '/admin/sessions' => {
  160. method => 'GET',
  161. auth => 1,
  162. callback => \&Trog::Routes::HTML::sessions,
  163. noindex => 1,
  164. nocache => 1,
  165. },
  166. # 'guest', not 'domain': the router sets $query->{domain} to the request's
  167. # own host *after* it applies the path parameters, so a variable by that
  168. # name never survives to the callback.
  169. '/guest/screenshot/{hypervisor}/{guest}' => {
  170. method => 'GET',
  171. auth => 1,
  172. callback => \&Trog::Routes::HTML::guest_screenshot,
  173. noindex => 1,
  174. nocache => 1,
  175. },
  176. '/guest/act' => {
  177. method => 'POST',
  178. auth => 1,
  179. callback => \&Trog::Routes::HTML::guest_act,
  180. noindex => 1,
  181. nocache => 1,
  182. },
  183. '/guest/reprovision' => {
  184. method => 'POST',
  185. auth => 1,
  186. callback => \&Trog::Routes::HTML::guest_reprovision,
  187. noindex => 1,
  188. nocache => 1,
  189. },
  190. # 'guest', not 'domain', for the reason the screenshot route names it that
  191. # way.
  192. '/guest/reprovision/log/{guest}' => {
  193. method => 'GET',
  194. auth => 1,
  195. callback => \&Trog::Routes::HTML::guest_reprovision_log,
  196. robot_name => '/guest/reprovision/log/',
  197. noindex => 1,
  198. nocache => 1,
  199. },
  200. '/admin/wyzzerdd' => {
  201. method => 'GET',
  202. auth => 1,
  203. callback => \&Trog::Routes::HTML::post_wizard,
  204. noindex => 1,
  205. nocache => 1,
  206. },
  207. '/admin/wyzzerdd/save' => {
  208. method => 'POST',
  209. auth => 1,
  210. callback => \&Trog::Routes::HTML::post_wizard_save,
  211. noindex => 1,
  212. nocache => 1,
  213. },
  214. #TODO transform into posts?
  215. '/sitemap',
  216. => {
  217. method => 'GET',
  218. callback => \&Trog::Routes::HTML::sitemap,
  219. },
  220. '/sitemap_index.xml',
  221. => {
  222. method => 'GET',
  223. callback => \&Trog::Routes::HTML::sitemap,
  224. data => { xml => 1 },
  225. },
  226. '/sitemap_index.xml.gz',
  227. => {
  228. method => 'GET',
  229. callback => \&Trog::Routes::HTML::sitemap,
  230. data => { xml => 1, compressed => 1 },
  231. },
  232. '/sitemap/static.xml' => {
  233. method => 'GET',
  234. callback => \&Trog::Routes::HTML::sitemap,
  235. data => { xml => 1, map => 'static' },
  236. },
  237. '/sitemap/static.xml.gz' => {
  238. method => 'GET',
  239. callback => \&Trog::Routes::HTML::sitemap,
  240. data => { xml => 1, compressed => 1, map => 'static' },
  241. },
  242. '/sitemap/{map}.xml' => {
  243. method => 'GET',
  244. callback => \&Trog::Routes::HTML::sitemap,
  245. data => { xml => 1 },
  246. },
  247. '/sitemap/{map}.xml.gz' => {
  248. method => 'GET',
  249. callback => \&Trog::Routes::HTML::sitemap,
  250. data => { xml => 1, compressed => 1 },
  251. },
  252. '/humans.txt' => {
  253. method => 'GET',
  254. callback => \&Trog::Routes::HTML::posts,
  255. data => { tag => ['about'] },
  256. },
  257. '/styles/avatars.css' => {
  258. method => 'GET',
  259. callback => \&Trog::Routes::HTML::avatars,
  260. data => { tag => ['about'] },
  261. },
  262. '/avatar/{avatar_hash}' => {
  263. method => 'GET',
  264. callback => \&Trog::Routes::HTML::libravatar,
  265. noindex => 1,
  266. nocache => 1,
  267. },
  268. '/favicon.ico' => {
  269. method => 'GET',
  270. callback => \&Trog::Routes::HTML::icon,
  271. },
  272. '/totp_qr/{file}' => {
  273. auth => 1,
  274. method => 'GET',
  275. # The QR on that page, so it has to be reachable from it.
  276. totp_exempt => 1,
  277. callback => \&Trog::Routes::HTML::totp_qr,
  278. },
  279. '/styles/rss-style.xsl' => {
  280. method => 'GET',
  281. callback => \&Trog::Routes::HTML::rss_style,
  282. },
  283. '/bundle/{version}/{names}.js' => {
  284. method => 'GET',
  285. callback => \&Trog::Routes::HTML::bundle,
  286. },
  287. );
  288. # Grab theme routes
  289. my $themed = 0;
  290. my $theme_dir = Trog::Themes::get_dir();
  291. if ($theme_dir) {
  292. my $theme_mod = "$theme_dir/routes.pm";
  293. if ( -f $theme_mod ) { ## no critic (ProhibitFiletest_f) -- theme routes, else the default theme
  294. # get_dir() is relative to the tCMS root, which require only searches from '.'.
  295. local @INC = ( '.', @INC );
  296. require $theme_mod;
  297. @routes{ keys(%Theme::routes) } = values(%Theme::routes);
  298. $themed = 1;
  299. }
  300. else {
  301. # Use the special "default" theme
  302. require Theme;
  303. }
  304. }
  305. =head1 PRIMARY ROUTE
  306. =head2 feedback_redirect($query, $to, $failure, $message)
  307. Redirect to $to, carrying the outcome of a save so the destination page can put
  308. it in the jsalert banner.
  309. We redirect rather than rendering in place so that a save stays a
  310. POST-redirect-GET -- refreshing the page the user lands on must not re-submit
  311. the post. That means the outcome has to travel in the URL, as there is nowhere
  312. else to put it.
  313. =cut
  314. my sub feedback_redirect ( $query, $to, $failure, $message ) {
  315. my $cookie = feedback_cookie( $failure, $message );
  316. # Appended to what see_also() built rather than replacing it, so this still
  317. # logs and still redirects the way every other redirect in here does.
  318. my $response = $query->{tpsgi}->see_also($to);
  319. push( @{ $response->[1] }, 'Set-Cookie' => $cookie );
  320. return $response;
  321. }
  322. =head2 feedback_cookie($failure, $message) = STRING
  323. The Set-Cookie which carries a save's outcome to the page it redirects to.
  324. A cookie because a redirect's own headers are gone by the time the destination
  325. renders, and a cookie is the one header that survives the hop. It used to be a
  326. query parameter, which meant a save's message was in the URL: a validation error
  327. carrying a Carp::Always stack trace built a URL of several thousand characters,
  328. and tPSGI answered the redirect it had just issued with a 419. The user was
  329. shown neither the page nor the error.
  330. Trimmed to one line, because the banner puts it in a JS string literal, and
  331. capped at $feedback_max characters, because a cookie has a size limit of its own
  332. and nothing a person needs to read is longer than that. The whole of it is in
  333. the log either way.
  334. =cut
  335. our $feedback_max = 512;
  336. sub feedback_cookie ( $failure, $message ) {
  337. $message //= '';
  338. $message =~ s/\s*\n+\s*/; /g;
  339. $message =~ s/;\s*$//;
  340. $message = substr( $message, 0, $feedback_max - 3 ) . '...' if length($message) > $feedback_max;
  341. my $value = ( $failure ? 1 : 0 ) . ':' . URI::Escape::uri_escape($message);
  342. # HttpOnly because the banner is rendered server side and no script has any
  343. # business reading it; Max-Age because a message nobody collected should not
  344. # follow them around; Path=/ because the destination is wherever they were.
  345. return "tcmsfeedback=$value; Path=/; HttpOnly; SameSite=Lax; Max-Age=30";
  346. }
  347. =head2 absorb_feedback($query)
  348. Turn the parameters feedback_redirect() put in the URL back into the failure
  349. and message the jsalert banner reads.
  350. Done in index() rather than in each route, so that a save can hand feedback to
  351. any destination that renders a page, whichever route ends up serving it.
  352. =cut
  353. my sub absorb_feedback ($query) {
  354. my ( $failure, $message ) = feedback_from_cookie( $query->{cookies} );
  355. # The query parameters are still read, for a redirect issued by a worker
  356. # which had not been restarted yet, and for anyone who has one bookmarked.
  357. if ( !defined $failure ) {
  358. my ( $saved, $failed ) = ( $query->{saved}, $query->{savefailed} );
  359. return unless defined $saved || defined $failed;
  360. $failure = defined $failed ? 1 : 0;
  361. $message = defined $failed ? $failed : $saved;
  362. }
  363. $query->{failure} = $failure;
  364. $query->{message} = $message || ( $failure ? 'Save failed.' : 'Saved.' );
  365. # A page showing a banner is not a page to cache: the banner is for the one
  366. # person who just saved something, and a static of it would be served to
  367. # everybody. The query parameter form was accidentally safe here, since a
  368. # query string skips the render cache on its own; a cookie is not.
  369. $query->{nocache} = 1;
  370. # Read once. Without this the banner reappears on every page until the
  371. # cookie expires.
  372. $query->{feedback_seen} = 1;
  373. # Nothing further to navigate to -- we are already there. Without this the
  374. # banner's success branch would bounce us onwards.
  375. delete $query->{to};
  376. return;
  377. }
  378. =head2 feedback_from_cookie($cookies) = ($failure, $message)
  379. Pull a save's outcome back out of the cookie feedback_redirect set.
  380. Returns nothing when there isn't one, so that the caller can fall back to the
  381. query parameters this replaced.
  382. =cut
  383. sub feedback_from_cookie ($cookies) {
  384. return () unless $cookies;
  385. local $@;
  386. my $jar = eval { CGI::Cookie->parse($cookies) };
  387. return () unless ref $jar eq 'HASH' && $jar->{tcmsfeedback};
  388. my $value = $jar->{tcmsfeedback}->value // '';
  389. my ( $failure, $message ) = $value =~ m/^([01]):(.*)$/s;
  390. return () unless defined $failure;
  391. return ( int($failure), URI::Escape::uri_unescape($message) );
  392. }
  393. my sub build_social_meta ( $query, $title ) { ## no critic (ProhibitSingleUseLexicalSubs) -- 55 lines, which would overcomplicate index()
  394. return ( undef, undef, undef ) unless $query->{social_meta} && $query->{route} && $query->{domain};
  395. my $default_tags = $Theme::default_tags;
  396. $default_tags .= ',' . join( ',', @{ $query->{primary_post}->{tags} } ) if $default_tags && $query->{primary_post}->{tags};
  397. my $primary_data = ref $query->{primary_post}{data} eq 'ARRAY' ? $query->{primary_post}{data}[0] : $query->{primary_post}{data};
  398. my $meta_desc = $primary_data // $Theme::description // "tCMS Site";
  399. $meta_desc = Trog::Utils::strip_and_trunc($meta_desc) || '';
  400. my $meta_tags = '';
  401. my $card_type = 'summary';
  402. $card_type = 'featured_image' if $query->{primary_post} && $query->{primary_post}{is_image};
  403. $card_type = 'player' if $query->{primary_post} && $query->{primary_post}{is_video};
  404. my $image = $Theme::default_image ? "https://$query->{domain}/" . Trog::Themes::get_dir() . "/$Theme::default_image" : '';
  405. $image = "https://$query->{domain}/$query->{primary_post}{preview}" if $query->{primary_post} && $query->{primary_post}{preview};
  406. $image = "https://$query->{domain}/$query->{primary_post}{href}" if $query->{primary_post} && $query->{primary_post}{is_image};
  407. my $primary_route = "https://$query->{domain}/$query->{route}";
  408. $primary_route =~ s/[\/]+/\//g;
  409. my $display_name = $Theme::display_name || 'Another tCMS Site';
  410. my $extra_tags = '';
  411. my %sopts = (
  412. site => '',
  413. image => '',
  414. fb_app_id => '',
  415. site_name => $display_name,
  416. app_name => $display_name,
  417. title => $title,
  418. description => $meta_desc,
  419. url => $primary_route,
  420. );
  421. $sopts{site} = $Theme::twitter_account if $Theme::twitter_account;
  422. $sopts{image} = $image if $image;
  423. $sopts{fb_app_id} = $Theme::fb_app_id if $Theme::fb_app_id;
  424. if ( $query->{primary_post} && $query->{primary_post}{is_video} ) {
  425. $sopts{player} = "https://$query->{domain}/$query->{primary_post}{href}";
  426. #XXX don't hardcode this
  427. $sopts{player_width} = 1280;
  428. $sopts{player_height} = 720;
  429. $extra_tags .= "<meta property='og:video:type' content='$query->{primary_post}{content_type}' />\n";
  430. }
  431. my $social = HTML::SocialMeta->new(%sopts);
  432. $meta_tags = eval { $social->create($card_type) };
  433. $meta_tags =~ s/content="video"/content="video:other"/mg if $meta_tags;
  434. $meta_tags .= $extra_tags if $extra_tags;
  435. WARN("Theme misconfigured, social media tags will not be included: $@") if $theme_dir && !$meta_tags;
  436. return ( $default_tags, $meta_desc, $meta_tags );
  437. }
  438. my sub get_series ( $edit = 0 ) { ## no critic (ProhibitSingleUseLexicalSubs) -- 13 lines, which would overcomplicate index()
  439. state $data;
  440. $data //= Trog::Data->new( Trog::Config::get() );
  441. my @series = $data->get(
  442. acls => [qw{public}],
  443. tags => [qw{topbar}],
  444. limit => 10,
  445. page => 1,
  446. );
  447. @series = map { $_->{local_href} = "/post$_->{local_href}"; $_ } @series if $edit;
  448. return @series;
  449. }
  450. =head2 index
  451. Implements the primary route used by all pages not behind auth.
  452. Most subsequent functions simply pass content to this function.
  453. =cut
  454. sub index ( $query, $content = '', $i_styles = [], $i_scripts = [] ) {
  455. $query->{theme_dir} = Trog::Themes::td();
  456. absorb_feedback($query);
  457. my $to_render = $query->{template} // $landing_page;
  458. $content ||= Trog::Renderer->render( template => $to_render, data => $query, component => 1, contenttype => 'text/html' );
  459. return $content if ref $content eq "ARRAY";
  460. my @styles;
  461. unshift( @styles, qw{embed.css} ) if $query->{embed};
  462. unshift( @styles, qw{screen.css structure.css} );
  463. push( @styles, @$i_styles );
  464. my @p_styles = qw{structure.css print.css};
  465. unshift( @p_styles, qw{embed.css} ) if $query->{embed};
  466. my @series = get_series(0);
  467. my $title = $query->{primary_post}{title} // $query->{title} // $Theme::default_title // 'tCMS';
  468. # Handle link "unfurling" correctly
  469. my ( $default_tags, $meta_desc, $meta_tags ) = build_social_meta( $query, $title );
  470. #Do embed content
  471. my $tmpl = $query->{embed} ? 'embed.tx' : 'index.tx';
  472. $query->{theme_dir} =~ s/^\/www\///;
  473. # Grab the avatar class for the logged in user
  474. if ( $query->{user} ) {
  475. $query->{user_class} = Trog::Auth::username2classname( $query->{user} );
  476. }
  477. state $data;
  478. $data //= Trog::Data->new( Trog::Config::get() );
  479. my ( $search_lang, $search_help ) = search_language($query);
  480. # Consumed, so expire it: otherwise the banner reappears on every page the
  481. # reader visits until the cookie times out on its own.
  482. my %headers;
  483. %headers = ( 'Set-Cookie' => 'tcmsfeedback=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0' ) if $query->{feedback_seen};
  484. return finish_render(
  485. $tmpl,
  486. {
  487. %$query,
  488. search_lang => $search_lang,
  489. search_help => $search_help,
  490. theme_dir => Trog::Themes::td(),
  491. content => $content,
  492. title => $title,
  493. categories => \@series,
  494. stylesheets => \@styles,
  495. print_styles => \@p_styles,
  496. scripts => $i_scripts,
  497. show_madeby => $Theme::show_madeby ? 1 : 0,
  498. embed => $query->{embed} ? 1 : 0,
  499. embed_video => $query->{primary_post}{is_video},
  500. default_tags => $default_tags,
  501. meta_desc => $meta_desc,
  502. meta_tags => $meta_tags,
  503. },
  504. %headers,
  505. );
  506. }
  507. my sub build_themed_styles ($styles) {
  508. my @styles = map { ( Trog::Themes::themed_style("$_") ) } @{ Trog::Utils::coerce_array($styles) };
  509. return \@styles;
  510. }
  511. =head1 NORMAL ROUTES
  512. These are expected to either return a 200, or redirect to something which does.
  513. =head2 setup
  514. One time setup page; should only display to the first user to visit the site which we presume to be the administrator.
  515. =cut
  516. sub setup ($query) {
  517. File::Touch::touch("config/setup");
  518. return Trog::Renderer->render(
  519. template => 'notconfigured.tx',
  520. data => {
  521. title => 'tCMS Requires Setup to Continue...',
  522. stylesheets => build_themed_styles( ['notconfigured.css'] ),
  523. %$query,
  524. },
  525. contenttype => 'text/html',
  526. code => 200,
  527. );
  528. }
  529. =head2 totp
  530. Enable 2 factor auth via TOTP for the currently authenticated user.
  531. Returns a page with a QR code & TOTP uri for pasting into your authenticator app of choice.
  532. Every user has to enroll, so this is where a login without one lands and the only
  533. page it can reach until it has one. Showing the same enrollment again is the
  534. point rather than a fallback: a user who lost their authenticator scans it again
  535. and is back where they were.
  536. =cut
  537. sub totp ($query) {
  538. my $active_user = $query->{user};
  539. my $domain = $query->{domain};
  540. $query->{failure} //= -1;
  541. my ( $uri, $qr, $failure, $message, $totp ) = Trog::Auth::totp( $active_user, $domain );
  542. my $now_tm = time;
  543. my $now_string = strftime( "%a %b %e T%H:%M:%SZ %Y", gmtime($now_tm) );
  544. return Trog::Routes::HTML::index(
  545. {
  546. title => 'Enable TOTP 2-Factor Auth',
  547. theme_dir => Trog::Themes::td(),
  548. uri => $uri,
  549. qr => $qr,
  550. failure => $failure,
  551. message => $message,
  552. template => 'totp.tx',
  553. is_admin => 1,
  554. cur_code => $totp->expected_totp_code($now_tm),
  555. timestamp => $now_string,
  556. %$query,
  557. },
  558. undef,
  559. [qw{post.css}],
  560. );
  561. }
  562. my sub setup_initial_db ( $dat, $user, $display_name, $contact_email ) { ## no critic (ProhibitSingleUseLexicalSubs) -- 72 lines, which would overcomplicate login()
  563. $dat->add(
  564. {
  565. "aclname" => "series",
  566. "acls" => [],
  567. "callback" => "Trog::Routes::HTML::series",
  568. method => 'GET',
  569. "data" => "Series",
  570. "href" => "/series",
  571. "local_href" => "/series",
  572. "preview" => "/img/sys/testpattern.jpg",
  573. "tags" => [qw{series topbar}],
  574. visibility => 'public',
  575. "title" => "Series",
  576. user => $user,
  577. form => 'series.tx',
  578. child_form => 'series.tx',
  579. aliases => [],
  580. },
  581. {
  582. "aclname" => "about",
  583. "acls" => [],
  584. "callback" => "Trog::Routes::HTML::series",
  585. method => 'GET',
  586. "data" => "About",
  587. "href" => "/about",
  588. "local_href" => "/about",
  589. "preview" => "/img/sys/testpattern.jpg",
  590. "tags" => [qw{series topbar public}],
  591. visibility => 'public',
  592. "title" => "About",
  593. user => $user,
  594. form => 'series.tx',
  595. child_form => 'profile.tx',
  596. aliases => [],
  597. },
  598. {
  599. "aclname" => "config",
  600. acls => [],
  601. "callback" => "Trog::Routes::HTML::config",
  602. 'method' => 'GET',
  603. "content_type" => "text/html",
  604. "data" => "Config",
  605. "href" => "/config",
  606. "local_href" => "/config",
  607. "preview" => "/img/sys/testpattern.jpg",
  608. "tags" => [qw{admin}],
  609. visibility => 'private',
  610. "title" => "Configure tCMS",
  611. user => $user,
  612. aliases => [],
  613. },
  614. {
  615. title => $display_name,
  616. data => 'Default user',
  617. preview => '/img/avatar/humm.gif',
  618. wallpaper => '/img/sys/testpattern.jpg',
  619. tags => ['about'],
  620. visibility => 'public',
  621. acls => ['admin'],
  622. local_href => "/users/$display_name",
  623. display_name => $display_name,
  624. contact_email => $contact_email,
  625. callback => "Trog::Routes::HTML::users",
  626. method => 'GET',
  627. user => $user,
  628. form => 'profile.tx',
  629. aliases => [],
  630. },
  631. );
  632. return 1;
  633. }
  634. =head2 login
  635. 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.
  636. =cut
  637. sub login ($query) {
  638. # Redirect if we actually have a logged in user.
  639. # Note to future me -- this user value is overwritten explicitly in server.psgi.
  640. # If that ever changes, you will die
  641. $query->{to} //= $query->{route};
  642. $query->{to} = '/config' if List::Util::any { $query->{to} eq $_ } qw{/login /logout};
  643. if ( $query->{user} ) {
  644. DEBUG("Login by $query->{user}, redirecting to $query->{to}");
  645. return $query->{tpsgi}->see_also( $query->{to} );
  646. }
  647. #Check and see if we have no users. If so we will just accept whatever creds are passed.
  648. my $hasusers = -f "config/has_users"; ## no critic (ProhibitFiletest_f) -- a flag file, only ever touched
  649. my $btnmsg = $hasusers ? "Log In" : "Register";
  650. my $headers;
  651. if ( $query->{username} && $query->{password} ) {
  652. if ( !$hasusers ) {
  653. # Make the first user
  654. Trog::Auth::useradd( $query->{username}, $query->{display_name}, $query->{password}, ['admin'], $query->{contact_email} );
  655. # Add a stub user page and the initial series.
  656. my $dat = Trog::Data->new( Trog::Config::get() );
  657. setup_initial_db( $dat, $query->{username}, $query->{display_name}, $query->{contact_email} );
  658. # Ensure we stop registering new users
  659. File::Touch::touch("config/has_users");
  660. }
  661. $query->{failed} = 1;
  662. my $cookie = Trog::Auth::mksession( $query->{username}, $query->{password}, $query->{token}, $query->{ip} // '' );
  663. if ($cookie) {
  664. # A login is how you get to enrol, since the QR is not something to
  665. # hand out to whoever asks for it -- so a user with no enrolment yet
  666. # gets a session and goes straight there rather than where they were
  667. # headed. The dispatcher keeps them there until they have one.
  668. $query->{to} = '/totp' unless Trog::Auth::has_totp( $query->{username} );
  669. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  670. my $secure = '';
  671. $secure = '; Secure' if $query->{scheme} eq 'https';
  672. $headers = {
  673. "Set-Cookie" => "tcmslogin=$cookie; HttpOnly; SameSite=Strict$secure",
  674. };
  675. $query->{failed} = 0;
  676. }
  677. }
  678. $query->{failed} //= -1;
  679. return Trog::Renderer->render(
  680. template => 'login.tx',
  681. data => {
  682. title => 'tCMS 2 ~ Login',
  683. to => $query->{to},
  684. failure => int( $query->{failed} ),
  685. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  686. btnmsg => $btnmsg,
  687. stylesheets => build_themed_styles( [qw{structure.css screen.css login.css}] ),
  688. theme_dir => Trog::Themes::td(),
  689. has_users => $hasusers,
  690. %$query,
  691. },
  692. headers => $headers,
  693. contenttype => 'text/html',
  694. code => 200,
  695. nocache => $query->{nocache},
  696. );
  697. }
  698. =head2 logout
  699. Deletes your users' session and opens the index.
  700. =cut
  701. sub logout ($query) {
  702. Trog::Auth::killsession( $query->{user}, $query->{ip} // '' ) if $query->{user};
  703. delete $query->{user};
  704. return Trog::Routes::HTML::index($query);
  705. }
  706. my sub get_themes {
  707. my $dir = 'www/themes';
  708. return [] unless -e $dir;
  709. return [ map { $_->basename } grep { $_->is_dir } Path::Tiny::path($dir)->children(qr/\A[^.]/) ];
  710. }
  711. =head2 config
  712. Renders the configuration page, or redirects you back to the login page.
  713. =cut
  714. sub config ( $query = {} ) {
  715. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  716. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  717. $query->{failure} //= -1;
  718. return Trog::Routes::HTML::index(
  719. {
  720. title => 'Configure tCMS',
  721. theme_dir => Trog::Themes::td(),
  722. stylesheets => [qw{config.css}],
  723. themes => get_themes() || [],
  724. config_sections => config_sections(),
  725. message => $query->{message},
  726. failure => $query->{failure},
  727. to => '/config',
  728. scheme => $query->{scheme},
  729. is_admin => 1,
  730. template => 'config.tx',
  731. %$query,
  732. },
  733. undef,
  734. [qw{config.css}],
  735. );
  736. }
  737. # The settings which are a choice among what this instance actually has
  738. # installed rather than free text. default.cfg can say a key exists, but not
  739. # that it has to be one of the themes on disk, so that part lives here.
  740. my %config_choices = (
  741. 'general.theme' => sub { return [ '', @{ get_themes() || [] } ] },
  742. 'general.data_model' => sub {
  743. foreach my $incdir (@INC) {
  744. my $dir = "$incdir/Trog/Data";
  745. next unless -d $dir;
  746. return [ map { $_->basename('.pm') } grep { -f } Path::Tiny::path($dir)->children(qr/[.]pm\z/) ]; ## no critic (ProhibitFiletest_f) -- building a menu of module names
  747. }
  748. die "Could not find tCMS data modules! Is tCMS in \@INC?";
  749. },
  750. );
  751. my sub config_title ($name) {
  752. $name =~ s/[_-]/ /g;
  753. return join( ' ', map { ucfirst } split( ' ', $name ) );
  754. }
  755. =head2 config_sections() = ARRAYREF
  756. The configuration editor's form, one entry per section of config/default.cfg,
  757. each holding the fields that section describes:
  758. { section => 'general', title => 'General', fields => [ { name, key, title, comment, value, options, multiline } ] }
  759. Fields carry the value this instance is running with, defaulting to what
  760. default.cfg ships. A field with 'options' renders as a menu, one with
  761. 'multiline' as a textarea -- a list of embed sources is not something to edit
  762. through a one line input.
  763. =cut
  764. sub config_sections {
  765. my %configured = Trog::Config::get()->vars();
  766. my @sections;
  767. foreach my $section ( @{ Trog::Config::schema() } ) {
  768. my @fields;
  769. foreach my $field ( @{ $section->{fields} } ) {
  770. # A setting never configured takes the default, but one set to nothing
  771. # stays empty, or the editor would quietly restore the default to
  772. # anyone who cleared it. XXX ACHTUNG config::simple's param() answers
  773. # a key which does not exist with a multi element array, so vars() is
  774. # what tells the two apart. A key holding commas is an arrayref too.
  775. my $name = $field->{name};
  776. my $value =
  777. !exists $configured{$name} ? $field->{default}
  778. : ref $configured{$name} eq 'ARRAY' ? join( ', ', @{ $configured{$name} } )
  779. : ref $configured{$name} ? ''
  780. : $configured{$name} // '';
  781. my %rendered = (
  782. %$field,
  783. title => config_title( $field->{key} ),
  784. value => $value,
  785. );
  786. if ( my $choices = $config_choices{ $field->{name} } ) {
  787. $rendered{options} = [
  788. map {
  789. {
  790. value => $_,
  791. label => $_ ? $_ : 'default',
  792. selected => $_ eq $value ? 1 : 0,
  793. }
  794. } @{ $choices->() }
  795. ];
  796. }
  797. else {
  798. # Long values (an embed allowlist, a list of paths) are miserable
  799. # to edit in a box you can only see the end of.
  800. $rendered{multiline} = length($value) > 60 ? 1 : 0;
  801. }
  802. push( @fields, \%rendered );
  803. }
  804. push(
  805. @sections,
  806. {
  807. section => $section->{section},
  808. title => config_title( $section->{section} ),
  809. fields => \@fields,
  810. }
  811. );
  812. }
  813. return \@sections;
  814. }
  815. my sub stamp ($epoch) {
  816. my @t = localtime($epoch);
  817. return sprintf( '%04d-%02d-%02d %02d:%02d', $t[5] + 1900, $t[4] + 1, $t[3], $t[2], $t[1] );
  818. }
  819. =head2 resetpass
  820. =head2 do_resetpass
  821. Routes for user service of their authentication details.
  822. There is no route here for turning TOTP off. Everybody has it, and losing an
  823. authenticator is not a reason to stop having a second factor -- bin/totp reads a
  824. user their existing enrollment back out of band, which is the same enrollment
  825. rather than a new one.
  826. =cut
  827. =head2 secrets
  828. =head2 secrets_save
  829. =head2 secrets_forget
  830. Implements /secrets, where a user manages what tCMS remembers on their behalf.
  831. These are passwords that are not tCMS's -- the KeePass passphrase a provisioning
  832. recipe's secret: values are behind, to begin with. Storing one means the next
  833. thing that needs it asks for a TOTP code instead, which is a thing you have on
  834. you rather than a thing you have to have written down somewhere.
  835. Everything here is that user's own. There is no route by which one person's
  836. secrets are listed, opened or deleted by another, admin included: the username
  837. is taken from the session and never from the request, and it is bound into the
  838. ciphertext, so a row is not readable as anybody but its owner.
  839. Nothing ever renders a value back. A secret you can read off a screen is one
  840. you did not need us to keep -- if they have forgotten it, the answer is to
  841. replace it, not to be shown it.
  842. =cut
  843. sub secrets ($query) {
  844. require Trog::Vault;
  845. my @secrets = map {
  846. my $secret = {%$_};
  847. $secret->{stored} = stamp( $secret->{created} );
  848. $secret->{used} = $secret->{last_used} ? stamp( $secret->{last_used} ) : 'never';
  849. $secret
  850. } @{ Trog::Vault::list( $query->{user} ) };
  851. return Trog::Routes::HTML::index(
  852. {
  853. title => 'Stored Secrets',
  854. theme_dir => Trog::Themes::td(),
  855. template => 'secrets.tx',
  856. stylesheets => [qw{config.css}],
  857. secrets => \@secrets,
  858. has_vault => Trog::Vault::has_key(),
  859. failure => $query->{failure} // -1,
  860. %$query,
  861. },
  862. undef,
  863. [qw{config.css}],
  864. );
  865. }
  866. sub secrets_save ($query) {
  867. require Trog::Vault;
  868. my ( $ok, $message ) = Trog::Vault::set( $query->{user}, $query->{name} // '', $query->{secret} // '' );
  869. # This hash is cloned, logged around and handed to renderers.
  870. delete $query->{secret};
  871. return feedback_redirect( $query, '/secrets', $ok ? 0 : 1, $message );
  872. }
  873. sub secrets_forget ($query) {
  874. require Trog::Vault;
  875. my $name = $query->{name} // '';
  876. my $gone = Trog::Vault::forget( $query->{user}, $name );
  877. return feedback_redirect( $query, '/secrets', $gone ? 0 : 1, $gone ? "'$name' forgotten" : "there was nothing stored as '$name'" );
  878. }
  879. sub resetpass ($query) {
  880. $query->{failure} //= -1;
  881. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  882. return Trog::Routes::HTML::index(
  883. {
  884. title => 'Request Authentication Resets',
  885. theme_dir => Trog::Themes::td(),
  886. stylesheets => [qw{config.css}],
  887. message => $query->{message},
  888. failure => $query->{failure},
  889. scheme => $query->{scheme},
  890. template => 'resetpass.tx',
  891. is_admin => $is_admin,
  892. %$query,
  893. },
  894. undef,
  895. [qw{config.css}],
  896. );
  897. }
  898. sub do_resetpass ($query) {
  899. my $user = $query->{username};
  900. # User Does not exist
  901. return $query->{tpsgi}->forbidden($query) if !Trog::Auth::user_exists($user);
  902. # User exists, but is not logged in this session
  903. return $query->{tpsgi}->forbidden($query) if !$query->{user} && Trog::Auth::user_has_session($user);
  904. my $token = Trog::Utils::uuid();
  905. my $newpass = $query->{password} // Trog::Utils::uuid();
  906. my $res = Trog::Auth::add_change_request( type => 'reset_pass', user => $user, secret => $newpass, token => $token );
  907. die "Could not add auth change request!" unless $res;
  908. # If the user is logged in, just do the deed, otherwise send them the token in an email
  909. if ( $query->{user} ) {
  910. return $query->{tpsgi}->see_also("/api/auth_change_request/$token");
  911. }
  912. Trog::Email::contact(
  913. $user,
  914. "root\@$query->{domain}",
  915. "$query->{domain}: Password reset URL for $user",
  916. { uri => "$query->{scheme}://$query->{domain}/api/auth_change_request/$token", template => 'password_reset.tx' }
  917. );
  918. return $query->{tpsgi}->see_also("/processed");
  919. }
  920. =head2 get_datasources
  921. Every Trog::DataSource::* module on disk.
  922. The wizard offers these as somewhere other than the datastore for a post type
  923. to get its posts from, and post_wizard_save checks a submitted one against this
  924. list -- the name ends up in a sidecar and is later require()d, so it has to be
  925. something we found rather than something we were told.
  926. =cut
  927. sub get_datasources {
  928. my %found;
  929. foreach my $incdir (@INC) {
  930. my $dir = "$incdir/Trog/DataSource";
  931. next unless -d $dir;
  932. my @modules = eval {
  933. grep { -f } Path::Tiny::path($dir)->children(qr/[.]pm\z/); ## no critic (ProhibitFiletest_f) -- building an allowlist of names
  934. } or next;
  935. $found{ "Trog::DataSource::" . $_->basename('.pm') } = 1 foreach @modules;
  936. }
  937. return [ sort keys(%found) ];
  938. }
  939. =head2 datasource_editable($module)
  940. Whether a post type backed by $module should be given an editor.
  941. A datasource says so with an EDITABLE method. One that does not say is
  942. assumed editable, since that is what a post type is unless it has a reason not
  943. to be.
  944. =cut
  945. sub datasource_editable ($module) {
  946. return 1 unless $module;
  947. return 1 unless Trog::DataSource::load($module);
  948. return 1 unless $module->can('EDITABLE');
  949. return $module->EDITABLE ? 1 : 0;
  950. }
  951. =head2 config_save
  952. Implements /config/save route. Saves the configuration to config/main.cfg.
  953. Only the keys config/default.cfg describes are saved, so a form which posts
  954. something the defaults never heard of writes nothing -- the schema is what is
  955. editable, not whatever turned up in the request.
  956. =cut
  957. sub config_save ($query) {
  958. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  959. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  960. my $conf = Trog::Config::get();
  961. config_apply( $conf, $query );
  962. $query->{failure} = 1;
  963. $query->{message} = "Failed to save configuration!";
  964. if ( $conf->write($Trog::Config::home_cfg) ) {
  965. $query->{failure} = 0;
  966. $query->{message} = "Configuration updated succesfully.";
  967. }
  968. #We need to reap the children with outdated configuration.
  969. $query->{tpsgi}->signal_restart_parent();
  970. return config($query);
  971. }
  972. =head2 config_apply( Config::Simple conf, HASHREF query )
  973. Copy whatever settings the form posted onto $conf, keyed by their full
  974. 'section.key' name.
  975. The schema is the allowlist: a request naming something config/default.cfg does
  976. not describe writes nothing, so a stray form field cannot invent configuration.
  977. Values are taken as posted, empty string included -- clearing a setting is how
  978. you go back to having none.
  979. =cut
  980. sub config_apply ( $conf, $query ) {
  981. foreach my $section ( @{ Trog::Config::schema() } ) {
  982. foreach my $field ( @{ $section->{fields} } ) {
  983. my $value = $query->{ $field->{name} };
  984. next unless defined $value;
  985. # Duplicate inputs arrive as an array; the last one wins, same as
  986. # the browser's own idea of which field you filled in last.
  987. $value = $value->[-1] if ref $value eq 'ARRAY';
  988. next if ref $value;
  989. $conf->param( $field->{name}, $value );
  990. }
  991. }
  992. return;
  993. }
  994. =head2 themeclone
  995. Clone a theme by copying a directory.
  996. =cut
  997. sub themeclone ($query) {
  998. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  999. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  1000. my ( $theme, $newtheme ) = ( $query->{theme}, $query->{newtheme} );
  1001. my $themedir = 'www/themes';
  1002. $query->{failure} = 1;
  1003. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  1004. require File::Copy::Recursive;
  1005. if ( $theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" ) ) {
  1006. $query->{failure} = 0;
  1007. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  1008. }
  1009. return $query->{tpsgi}->see_also('/config');
  1010. }
  1011. =head2 post_save
  1012. Saves posts submitted via the /post pages
  1013. =cut
  1014. sub post_save ($qq) {
  1015. return $qq->{tpsgi}->see_also('/login') unless $qq->{user};
  1016. return $qq->{tpsgi}->forbidden($qq) unless List::Util::any { $_ eq 'admin' } @{ $qq->{user_acls} };
  1017. my $query = clone($qq);
  1018. my $to = delete $query->{to};
  1019. $query->{tags} = Trog::Utils::coerce_array( $query->{tags} );
  1020. # Support data with multiple pages like presentations
  1021. $query->{data} = Trog::Utils::coerce_array( $query->{data} ) if $query->{data_is_array};
  1022. $query->{attachments} = Trog::Utils::coerce_array( $query->{attachments} );
  1023. # Filter bits and bobs XXX this is done deeper in, may require removal
  1024. delete $query->{primary_post};
  1025. delete $query->{social_meta};
  1026. delete $query->{deflate};
  1027. delete $query->{acls};
  1028. # Ensure there are no null tags
  1029. @{ $query->{tags} } = grep { defined $_ } @{ $query->{tags} };
  1030. # Posts will always be GET
  1031. $query->{method} = 'GET';
  1032. state $data;
  1033. $data //= Trog::Data->new( Trog::Config::get() );
  1034. # A post that doesn't match its type's schema is the user's mistake, not a
  1035. # server error, so hand the validation errors back rather than dying.
  1036. local $@;
  1037. eval { $data->add($query); 1 } or do {
  1038. my @errors = Ref::Util::is_arrayref($@) ? @{$@} : ($@);
  1039. my $why = "Post failed validation:\n" . join( "\n", map { short_error($_) } @errors );
  1040. # The full detail goes to the log; the user gets it in the banner on
  1041. # the page they came from, rather than a dead-end 400.
  1042. WARN("Rejected post from $qq->{user}: $why");
  1043. return feedback_redirect( $qq, '/secure' . $to, 1, $why );
  1044. };
  1045. # Instruct tpsgi to invalidate the cached render.
  1046. $qq->{tpsgi}->add_post_close_callback(
  1047. sub {
  1048. # XXX there is not a great way to find what needs to be re-rendered because posts can include other posts.
  1049. # As such we just have to nuke all the .html renders.
  1050. $qq->{tpsgi}->invalidate_renders('html');
  1051. }
  1052. );
  1053. # Force a reload of the routing table
  1054. $qq->{tpsgi}->signal_restart_parent();
  1055. return feedback_redirect( $qq, '/secure' . $to, 0, "Saved post '$query->{title}'." );
  1056. }
  1057. =head2 profile
  1058. Saves / updates new users.
  1059. =cut
  1060. sub profile ($query) {
  1061. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1062. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  1063. # Find the user's post and edit it
  1064. state $data;
  1065. $data //= Trog::Data->new( Trog::Config::get() );
  1066. my @userposts = $data->get( tags => ['about'], acls => [qw{admin}] );
  1067. # Users are always self-authored, you see
  1068. my $user_obj = List::Util::first { ( $_->{user} || '' ) eq $query->{username} } @userposts;
  1069. my $username = $query->{username};
  1070. my $password = $query->{password};
  1071. my $changed =
  1072. $username ne ( $user_obj->{user} // '' )
  1073. || $password
  1074. || ( $query->{contact_email} // '' ) ne ( $user_obj->{contact_email} // '' )
  1075. || ( $query->{display_name} // '' ) ne ( $user_obj->{display_name} // '' );
  1076. #Make sure it is "self-authored", redact pw
  1077. $query->{user} = delete $query->{username};
  1078. delete $query->{password};
  1079. # Use the display name as the title
  1080. $query->{title} = $query->{display_name};
  1081. my %merged = (
  1082. %$user_obj,
  1083. %$query,
  1084. $query->{display_name} ? ( local_href => "/users/$query->{display_name}" ) : ( local_href => $user_obj->{local_href} ),
  1085. );
  1086. # Validate before touching the auth database, not after. useradd() does an
  1087. # INSERT OR REPLACE on the user row, which cascades to the session table and
  1088. # logs the user straight out -- doing that and *then* rejecting the post
  1089. # leaves the credentials disagreeing with the profile post they came from.
  1090. my @errors = Trog::DataModule::validate( clone( \%merged ) );
  1091. if (@errors) {
  1092. my $why = "Post failed validation:\n" . join( "\n", @errors );
  1093. WARN("Rejected profile update from $query->{user}: $why");
  1094. return $query->{tpsgi}->badrequest( $query, $why );
  1095. }
  1096. if ($changed) {
  1097. my $for_user = Trog::Auth::acls4user($username);
  1098. #TODO support non-admin users
  1099. my @acls = @$for_user ? @$for_user : qw{admin};
  1100. Trog::Auth::useradd( $username, $merged{display_name}, $password, \@acls, $merged{contact_email} );
  1101. }
  1102. return post_save( \%merged );
  1103. }
  1104. =head2 post_delete
  1105. deletes posts.
  1106. =cut
  1107. sub post_delete ($query) {
  1108. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1109. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  1110. state $data;
  1111. $data //= Trog::Data->new( Trog::Config::get() );
  1112. $data->delete($query) and die "Could not delete post";
  1113. return $query->{tpsgi}->see_also( $query->{to} );
  1114. }
  1115. # Anything a type needs computed rather than merely fetched. The sub is named
  1116. # in the sidecar, so validate it the same way a post's own callback field is --
  1117. # a sidecar naming an arbitrary sub is a privilege question, not a typo.
  1118. my sub enrich_callback ( $post, $query ) { ## no critic (ProhibitSingleUseLexicalSubs) -- 33 lines, which would overcomplicate enrich_post()
  1119. my $meta = Trog::DataModule::type_meta_for( $post->{form} );
  1120. my $sub = $meta->{'x-tcms-post-type'}{enrich};
  1121. return if !$sub || ref $sub;
  1122. my ($modname) = $sub =~ m/^([\w:]+)::\w+$/;
  1123. if ( !$modname ) {
  1124. WARN("Post type '$post->{form}' declares a malformed enrich sub '$sub'");
  1125. return;
  1126. }
  1127. my $modpath = $modname;
  1128. $modpath =~ s{::}{/}g;
  1129. $modpath .= '.pm';
  1130. local $@;
  1131. eval { require $modpath; 1 } or do {
  1132. WARN("Post type '$post->{form}' declares enrich sub '$sub', but $modname will not load: $@");
  1133. return;
  1134. };
  1135. no strict 'refs';
  1136. if ( !defined &{$sub} ) {
  1137. WARN("Post type '$post->{form}' declares enrich sub '$sub', which does not exist");
  1138. return;
  1139. }
  1140. my %extra = &{$sub}( $post, $query );
  1141. use strict;
  1142. @$post{ keys(%extra) } = values(%extra);
  1143. return;
  1144. }
  1145. =head2 enrich_post($post, $query, $cache)
  1146. Resolve a post type's declared relations onto the post, and run its enrich sub
  1147. if it has one.
  1148. A type says what it depends on in its sidecar rather than in code here -- see
  1149. Trog::DataModule::relations_for. An entry naming a 'from' field resolves the
  1150. UUID in that field into the post it refers to; one without gets every post of
  1151. the target type, which is what an editor picker or a "show me all of these"
  1152. display wants.
  1153. $cache is a per-request memo of the per-type lookups. Without it a page of
  1154. invoices re-scans every entities post once per invoice.
  1155. =cut
  1156. sub enrich_post ( $post, $query, $cache = {} ) {
  1157. return unless Ref::Util::is_hashref($post) && $post->{form};
  1158. my $relations = Trog::DataModule::relations_for( $post->{form} );
  1159. foreach my $as ( keys(%$relations) ) {
  1160. my $relation = $relations->{$as};
  1161. next unless Ref::Util::is_hashref($relation);
  1162. my ($target) = ( $relation->{form} // '' ) =~ m/^([\w-]+\.tx)$/;
  1163. next unless $target;
  1164. $cache->{$target} //= [ post_helper( { form => $target }, [], $query->{user_acls} ) ];
  1165. # No 'from' means the relation is the whole set rather than one of them.
  1166. my $from = $relation->{from};
  1167. if ( !$from ) {
  1168. $post->{$as} = $cache->{$target};
  1169. next;
  1170. }
  1171. my $wanted = $post->{$from};
  1172. $post->{$as} = defined $wanted ? List::Util::first { $_->{id} eq $wanted } @{ $cache->{$target} } : undef;
  1173. }
  1174. enrich_callback( $post, $query );
  1175. return;
  1176. }
  1177. =head2 series
  1178. Series specific view, much like the users/ route
  1179. Displays identified series, not all series.
  1180. =cut
  1181. sub series ($query) {
  1182. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1183. # rip away /secure if present
  1184. $query->{route} =~ s|^/secure||;
  1185. #we are either viewed one of two ways, /post/$id or /$aclname
  1186. my ( undef, $aclname, $id ) = split( m{/}, $query->{route} );
  1187. $query->{aclname} = $aclname if !$id;
  1188. $query->{id} = $id if $id;
  1189. # Don't show topbar series on the series page. That said, don't exclude it from direct series view.
  1190. $query->{exclude_tags} = ['topbar'] if !$is_admin && $aclname && $aclname eq 'series';
  1191. #XXX I'd prefer to overload id to actually *be* the aclname...
  1192. # but this way, accomodates things like the flat file time-indexing hack.
  1193. # TODO I should probably have it for all posts, and make *everything* a series.
  1194. # WE can then do threaded comments/posts.
  1195. # That will essentially necessitate it *becoming* the ID for real.
  1196. #Grab the relevant tag (aclname), then pass that to posts
  1197. #
  1198. # Deliberately not $query: this is looking up the one series post named by
  1199. # the route, and handing it the reader's pagination pages *that* lookup.
  1200. # Asking for page two of a single post gets nothing, so a series carrying a
  1201. # ?page= in its URL could not find itself and 404'd on its own page. Latent
  1202. # until something started emitting page numbers -- see paginate_offset.
  1203. my @posts = post_helper( { %$query, page => 1, limit => 1 }, ['series'], [ viewer_acls( $query, 1 ) ] );
  1204. # The series post carries its *children's* relations, so that an editor
  1205. # picker rendered on this page has something to populate from -- that is
  1206. # what $primary_post.entities is on an invoice series. Keyed on child_form
  1207. # rather than form: the series is a series.tx, its children are what
  1208. # declare the dependency.
  1209. if ( $posts[0] ) {
  1210. my $relations = Trog::DataModule::relations_for( $posts[0]{child_form} );
  1211. if (%$relations) {
  1212. # Resolve against a stand-in wearing the child's form, then copy
  1213. # only the relation keys back, so nothing else about the series
  1214. # post gets overwritten.
  1215. my $stand_in = { %{ $posts[0] }, form => $posts[0]{child_form} };
  1216. enrich_post( $stand_in, { %$query, user_acls => [ viewer_acls($query) ] } );
  1217. @{ $posts[0] }{ keys(%$relations) } = @{$stand_in}{ keys(%$relations) };
  1218. }
  1219. }
  1220. delete $query->{id};
  1221. delete $query->{aclname};
  1222. $query->{subhead} = $posts[0]->{data};
  1223. $query->{title} = $posts[0]->{title};
  1224. $query->{tag} = $posts[0]->{aclname};
  1225. $query->{primary_post} = $posts[0];
  1226. $query->{in_series} = 1;
  1227. return posts($query);
  1228. }
  1229. =head2 avatars
  1230. Returns the avatars.css.
  1231. =cut
  1232. sub avatars ($query) {
  1233. $query->{user_acls} = [ viewer_acls($query) ];
  1234. my $tags = Trog::Utils::coerce_array( $query->{tag} );
  1235. my @posts = post_helper( $query, $tags, $query->{user_acls} );
  1236. if (@posts) {
  1237. # Set the eTag so that we don't get a re-fetch
  1238. $query->{etag} = "$posts[0]{id}-$posts[0]{version}";
  1239. }
  1240. @posts = map { $_->{id} =~ tr/-/_/; $_->{id} = "a_$_->{id}"; $_ } @posts;
  1241. return Trog::Renderer->render(
  1242. template => 'avatars.tx',
  1243. data => {
  1244. users => \@posts,
  1245. %$query,
  1246. },
  1247. code => 200,
  1248. contenttype => 'text/css',
  1249. );
  1250. }
  1251. =head2 libravatar
  1252. Implements the libravatar protocol (https://wiki.libravatar.org/running_your_own/).
  1253. Accepts GET /avatar/{hash} where {hash} is the MD5 or SHA-256 of the user's
  1254. lowercased email address, and redirects to their profile avatar image.
  1255. Returns 404 when no matching user is found or the user has no avatar.
  1256. =cut
  1257. sub libravatar ($query) {
  1258. my $hash = lc( $query->{avatar_hash} // '' );
  1259. my $users = Trog::Auth::users_with_emails();
  1260. my $matched_user;
  1261. for my $u (@$users) {
  1262. next unless $u->{contact_email};
  1263. my $email = lc( $u->{contact_email} );
  1264. if ( $hash eq sha256_hex($email) || $hash eq md5_hex($email) ) {
  1265. $matched_user = $u->{name};
  1266. last;
  1267. }
  1268. }
  1269. return $query->{tpsgi}->notfound($query) unless $matched_user;
  1270. my @posts = post_helper( { author => $matched_user }, ['about'], [qw{public admin}] );
  1271. my $preview = @posts ? $posts[0]->{preview} : '';
  1272. return $query->{tpsgi}->notfound($query) unless $preview;
  1273. return $query->{tpsgi}->redirect_permanent("/$preview");
  1274. }
  1275. =head2 users
  1276. Implements direct user profile view.
  1277. =cut
  1278. sub users ($query) {
  1279. # rip away /secure if present
  1280. $query->{route} =~ s|^/secure||;
  1281. # Capture the username
  1282. my ( undef, undef, $display_name ) = split( m{/}, $query->{route} );
  1283. $display_name = URI::Escape::uri_unescape($display_name);
  1284. my $username = Trog::Auth::display2username($display_name);
  1285. return $query->{tpsgi}->notfound($query) unless $username;
  1286. $query->{username} //= $username;
  1287. $query->{user_acls} = [ viewer_acls($query) ];
  1288. $query->{exclude_tags} = ['about'];
  1289. # Don't show topbar series on the series page. That said, don't exclude it from direct series view.
  1290. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1291. push( @{ $query->{exclude_tags} }, 'topbar' ) if !$is_admin;
  1292. my @posts = post_helper( { author => $query->{username} }, ['about'], $query->{user_acls} );
  1293. $query->{id} = $posts[0]->{id};
  1294. $query->{title} = $posts[0]->{display_name};
  1295. $posts[0]->{title} = $posts[0]->{display_name};
  1296. $query->{user_obj} = $posts[0];
  1297. $query->{primary_post} = $posts[0];
  1298. $query->{in_series} = 1;
  1299. return posts($query);
  1300. }
  1301. my sub post2rss ( $rss, $url, $post ) {
  1302. $rss->add_item(
  1303. title => $post->{title},
  1304. permaLink => $url,
  1305. link => $url,
  1306. enclosure => { url => $url, type => "text/html" },
  1307. description => "<![CDATA[$post->{data}]]>",
  1308. pubDate => DateTime->from_epoch( epoch => $post->{created} ), #TODO format like Thu, 23 Aug 1999 07:00:00 GMT
  1309. author => $post->{user}, #TODO translate to "email (user)" format
  1310. );
  1311. return 1;
  1312. }
  1313. my sub _rss ( $query, $subtitle, $posts ) { ## no critic (ProhibitSingleUseLexicalSubs) -- 49 lines, which would overcomplicate posts()
  1314. require XML::RSS;
  1315. my $rss = XML::RSS->new( version => '2.0', stylesheet => '/styles/rss-style.xsl' );
  1316. my $now = DateTime->from_epoch( epoch => time() );
  1317. my $port = $query->{port} ? ":$query->{port}" : '';
  1318. $rss->channel(
  1319. title => "$query->{domain}",
  1320. subtitle => $subtitle,
  1321. link => "http://$query->{domain}$port/$query->{route}?format=xml",
  1322. language => 'en', #TODO localization
  1323. description => "$query->{domain} : $query->{route}",
  1324. pubDate => $now,
  1325. lastBuildDate => $now,
  1326. );
  1327. $rss->image(
  1328. title => $query->{domain},
  1329. url => "/favicon.ico",
  1330. link => "http://$query->{domain}$port",
  1331. width => 32,
  1332. height => 32,
  1333. description => "$query->{domain} favicon",
  1334. );
  1335. foreach my $post (@$posts) {
  1336. my $url = "http://$query->{domain}$port$post->{local_href}";
  1337. post2rss( $rss, $url, $post );
  1338. next unless ref $post->{aliases} eq 'ARRAY';
  1339. foreach my $alias ( @{ $post->{aliases} } ) {
  1340. $url = "http://$query->{domain}$port$alias";
  1341. post2rss( $rss, $url, $post );
  1342. }
  1343. }
  1344. return Trog::Renderer->render(
  1345. template => 'raw.tx',
  1346. data => {
  1347. etag => $query->{etag},
  1348. body => encode_utf8( $rss->as_string ),
  1349. scheme => $query->{scheme},
  1350. },
  1351. headers => { 'Content-Disposition' => 'inline; filename="rss.xml"' },
  1352. #XXX if you do the "proper" content-type of application/rss+xml, browsers download rather than display.
  1353. contenttype => "text/xml",
  1354. code => 200,
  1355. );
  1356. }
  1357. =head2 posts
  1358. Display multi or single posts, supports RSS and pagination.
  1359. =cut
  1360. sub posts ( $query, $direct = 0 ) {
  1361. # Before we build the render data, not after: posts.tx is rendered here and
  1362. # handed to index() as content, so index()'s own absorb would be too late.
  1363. absorb_feedback($query);
  1364. # Allow rss.xml to tell what posts to loop over
  1365. my $fmt = $query->{format} || '';
  1366. #Process the input URI to capture tag/id
  1367. $query->{route} //= $query->{to};
  1368. # rip away /secure if present
  1369. $query->{route} =~ s|^/secure||;
  1370. my ( undef, undef, $id ) = split( m{/}, $query->{route} );
  1371. my $tags = Trog::Utils::coerce_array( $query->{tag} );
  1372. $query->{id} = $id if $id && !$query->{in_series};
  1373. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1374. $query->{user_acls} = [ viewer_acls( $query, $query->{id} ) ];
  1375. my @posts;
  1376. # Discover this user's visibility, so we can make them post in this category by default
  1377. my $user_visibility = 'public';
  1378. if ( $query->{user_obj} ) {
  1379. #Optimize the /users/* route
  1380. @posts = ( $query->{user_obj} );
  1381. $user_visibility = $query->{user_obj}->{visibility};
  1382. }
  1383. else {
  1384. if ( $query->{user} ) {
  1385. my @me = post_helper( { author => $query->{user} }, ['about'], $query->{user_acls} );
  1386. $user_visibility = $me[0]->{visibility};
  1387. }
  1388. @posts = post_helper( $query, $tags, $query->{user_acls} );
  1389. }
  1390. # A post type can say its posts come from somewhere other than the
  1391. # datastore -- see Trog::DataSource::Virt, which builds them out of libvirt
  1392. # guests. The series is still an ordinary post; only its children are
  1393. # synthesized, and they are rebuilt on every view rather than stored.
  1394. @posts = datasource_posts( $query, \@posts );
  1395. if ( $query->{id} ) {
  1396. $query->{primary_post} = $posts[0] if @posts;
  1397. }
  1398. #OK, so if we have a user as the ID we found, go grab the rest of their posts
  1399. if ( $query->{id} && @posts && List::Util::any { $_ eq 'about' } @{ $posts[0]->{tags} } ) {
  1400. my $user = shift(@posts);
  1401. my $profile_id = delete $query->{id};
  1402. $query->{author} = $user->{user};
  1403. @posts = post_helper( $query, $tags, $query->{user_acls} );
  1404. @posts = grep { $_->{id} ne $profile_id } @posts;
  1405. unshift @posts, $user;
  1406. }
  1407. if ( !$is_admin ) {
  1408. return $query->{tpsgi}->notfound($query) unless @posts;
  1409. }
  1410. # Set the eTag so that we don't get a re-fetch
  1411. $query->{etag} = "$posts[0]{id}-$posts[0]{version}" if @posts;
  1412. #Correct page headers
  1413. my $ph = ( $themed && $Theme::paths{ $query->{route} } ) || $query->{route};
  1414. return _rss( $query, $ph, \@posts ) if $fmt eq 'rss';
  1415. # List the available headers/footers
  1416. my $headers = Trog::Themes::themed_templates_in_dir( "headers", 'text/html', 1 );
  1417. my $footers = Trog::Themes::themed_templates_in_dir( "footers", 'text/html', 1 );
  1418. #XXX used to be post.css, but probably not good anymore?
  1419. my $styles = [];
  1420. # Build page title if it wasn't set by a wrapping sub
  1421. $query->{title} = "$query->{domain} : $query->{title}" if $query->{title} && $query->{domain};
  1422. $query->{title} ||= @$tags && $query->{domain} ? "$query->{domain} : @$tags" : undef;
  1423. #Handle paginator vars
  1424. $query->{limit} ||= 25;
  1425. my $limit = int( $query->{limit} );
  1426. my $now_year = ( localtime(time) )[5] + 1900;
  1427. my $oldest_year = $now_year - 20; #XXX actually find oldest post year
  1428. # Datasource pages page by offset, everything else by the created cursor.
  1429. # See paginate_offset() for why they cannot share.
  1430. my ( $paginate_offset, $page_of, $pages_total ) = ( 0, 1, 1 );
  1431. if ( $query->{is_datasource} ) {
  1432. $paginate_offset = 1;
  1433. ( $page_of, $pages_total, @posts ) = paginate_offset( $query, $limit, @posts );
  1434. }
  1435. my $older = !@posts ? 0 : $posts[-1]->{created};
  1436. $query->{failure} //= -1;
  1437. $query->{id} //= '';
  1438. my $newer = !@posts ? 0 : $posts[0]->{created};
  1439. #XXX messed up data has to be fixed unfortunately
  1440. @$tags = List::Util::uniq @$tags;
  1441. #Filter displaying visibility tags
  1442. my @visibuddies = qw{public unlisted private};
  1443. foreach my $post (@posts) {
  1444. @{ $post->{tags} } = grep {
  1445. my $tag = $_;
  1446. List::Util::none { $tag eq $_ } @visibuddies
  1447. } @{ $post->{tags} };
  1448. }
  1449. #XXX note that we are explicitly relying on the first tag to be the ACL
  1450. my $aclselected = $tags->[0] || '';
  1451. my @acls = map {
  1452. $_->{selected} = $_->{aclname} eq $aclselected ? 'selected' : '';
  1453. $_
  1454. } post_helper( {}, ['series'], $query->{user_acls} );
  1455. my $forms = Trog::Themes::themed_templates_in_dir( "forms", 'text/html', 1 );
  1456. my $edittype = $query->{primary_post} ? $query->{primary_post}->{child_form} : $query->{form};
  1457. my $tiled = $query->{primary_post} ? !$is_admin && $query->{primary_post}->{tiled} : 0;
  1458. state $data;
  1459. $data //= Trog::Data->new( Trog::Config::get() );
  1460. # Grab the rest of the tags to dump into the edit form
  1461. my @tags_all = $data->tags();
  1462. #Filter out the visibilities and special series tags
  1463. @tags_all = grep {
  1464. my $subj = $_;
  1465. scalar( grep { $_ eq $subj } qw{public private unlisted admin series about topbar} ) == 0
  1466. } @tags_all;
  1467. @posts = map {
  1468. my $subject = $_;
  1469. my @et = grep {
  1470. my $subj = $_;
  1471. grep { $subj eq $_ } @tags_all
  1472. } @{ $subject->{tags} };
  1473. @et = grep { $_ ne $aclselected } @et;
  1474. $_->{extra_tags} = \@et;
  1475. $_
  1476. } @posts;
  1477. my @et = List::MoreUtils::singleton( @$tags, @tags_all );
  1478. $query->{author} = $query->{primary_post}{user} // $posts[0]{user};
  1479. # Resolve each post's declared relations. One cache for the whole page, so
  1480. # 25 invoices don't mean 25 scans of every entities post.
  1481. my %relation_cache;
  1482. enrich_post( $_, $query, \%relation_cache ) foreach @posts;
  1483. #XXX the only reason this is needed is due to direct=1
  1484. # Last thing before the data becomes a page: anything a type marks private
  1485. # goes no further for a reader who cannot edit. Deliberately after the
  1486. # datasource has run -- a datasource may well need a private field, like
  1487. # the connection uri it takes to reach a hypervisor, to produce anything
  1488. # at all.
  1489. if ( !$is_admin ) {
  1490. my %seen;
  1491. redact_private( $_, \%seen ) foreach ( @posts, $query->{primary_post} );
  1492. }
  1493. #XXX is this even used?
  1494. my $content = Trog::Renderer->render(
  1495. template => 'posts.tx',
  1496. data => {
  1497. acls => \@acls,
  1498. can_edit => $is_admin,
  1499. forms => $forms,
  1500. post => { tags => $tags, extra_tags => \@et, form => $edittype, visibility => $user_visibility, addpost => 1 },
  1501. post_visibilities => \@visibuddies,
  1502. failure => $query->{failure},
  1503. to => $query->{to},
  1504. message => $query->{message} // ( $query->{failure} ? "Failed to add post!" : "Successfully added Post as $query->{id}" ),
  1505. direct => $direct,
  1506. title => $query->{title},
  1507. author => $query->{primary_post}{user} // $posts[0]{user},
  1508. primary_post => $query->{primary_post},
  1509. style => $query->{style},
  1510. posts => \@posts,
  1511. like => $query->{like},
  1512. in_series => exists $query->{in_series} || !!( $query->{route} =~ m/^\/series\// ),
  1513. route => $query->{route},
  1514. limit => $limit,
  1515. pages => $paginate_offset ? $pages_total > 1 : scalar(@posts) == $limit,
  1516. paginate_offset => $paginate_offset,
  1517. page => $page_of,
  1518. pages_total => $pages_total,
  1519. older => $older,
  1520. newer => $newer,
  1521. sizes => [ 25, 50, 100 ],
  1522. rss => !$query->{id} && !$query->{older},
  1523. tiled => $tiled,
  1524. category => $ph,
  1525. subhead => $query->{subhead},
  1526. headers => $headers,
  1527. footers => $footers,
  1528. years => [ reverse( $oldest_year .. $now_year ) ],
  1529. months => [ 0 .. 11 ],
  1530. embed => $query->{embed},
  1531. nochrome => $query->{nochrome},
  1532. },
  1533. contenttype => 'text/html',
  1534. component => 1,
  1535. );
  1536. # Something exploded
  1537. return $content if ref $content eq "ARRAY";
  1538. return $content if $direct;
  1539. my @scripts = ( ( $is_admin ? qw{post.js post_relations.js} : () ), qw{highlight.min.js reveal.min.js} );
  1540. return Trog::Routes::HTML::index( $query, $content, $styles, \@scripts );
  1541. }
  1542. =head2 redact_private($post, $seen)
  1543. Drop the fields a post type marks private, for a reader who isn't an editor.
  1544. Done to the data on its way to the template rather than with a guard inside the
  1545. template: a type can be rendered by more than one template, templates get
  1546. edited by people who did not write the type, and a value that was never handed
  1547. over cannot be printed by mistake. It walks into the post's relations too,
  1548. because they are posts and carry their own private fields.
  1549. =cut
  1550. sub redact_private ( $post, $seen = {} ) {
  1551. my @todo = ($post);
  1552. for ( my $i = 0; $i < scalar(@todo); $i++ ) {
  1553. my $node = $todo[$i];
  1554. next unless Ref::Util::is_hashref($node);
  1555. # Relations can point back at what pulled them in.
  1556. next if $seen->{$node}++;
  1557. if ( $node->{form} ) {
  1558. delete $node->{$_} foreach @{ Trog::DataModule::private_fields_for( $node->{form} ) };
  1559. }
  1560. foreach my $value ( values(%$node) ) {
  1561. if ( Ref::Util::is_hashref($value) ) { push( @todo, $value ) }
  1562. elsif ( Ref::Util::is_arrayref($value) ) { push( @todo, @$value ) }
  1563. }
  1564. }
  1565. return;
  1566. }
  1567. =head2 datasource_posts($query, $posts)
  1568. Swap a series' children for whatever its datasource says they are, if its child
  1569. type declares one.
  1570. Returns the posts unchanged for every ordinary type, which is nearly all of
  1571. them -- this is a hook, not a detour every page takes.
  1572. =cut
  1573. sub datasource_posts ( $query, $posts ) {
  1574. my $series = $query->{primary_post};
  1575. return @$posts unless Ref::Util::is_hashref($series) && $series->{child_form};
  1576. my $source = Trog::DataSource::for_type( $series->{child_form} );
  1577. return @$posts unless $source;
  1578. return @$posts unless Trog::DataSource::load($source);
  1579. my $builder = $source->can('posts');
  1580. if ( !$builder ) {
  1581. WARN("Datasource '$source' has no posts() to call");
  1582. return @$posts;
  1583. }
  1584. local $@;
  1585. my @synthesized = eval { $builder->( $series, $query ) };
  1586. if ($@) {
  1587. my $err = "$@";
  1588. $err =~ s/\n.*//s;
  1589. WARN("Datasource '$source' failed: $err");
  1590. return @$posts;
  1591. }
  1592. # The search the reader typed was applied to the datastore by get(), and
  1593. # then thrown away with the posts it filtered -- these are built fresh and
  1594. # have never been near it. Ask the source to apply it, or apply the default
  1595. # on its behalf, so that searching a datasource page searches the page.
  1596. my $filter = $source->can('filter') // \&Trog::DataSource::filter;
  1597. my @filtered = eval { $filter->( $query, @synthesized ) };
  1598. if ($@) {
  1599. my $err = "$@";
  1600. $err =~ s/\n.*//s;
  1601. WARN("Datasource '$source' could not filter its posts: $err");
  1602. @filtered = @synthesized;
  1603. }
  1604. # Pagination hands out page 2 of an order, so settle on one.
  1605. my $order = $source->can('order') // \&Trog::DataSource::order;
  1606. my @ordered = eval { $order->( $query, @filtered ) };
  1607. if ($@) {
  1608. my $err = "$@";
  1609. $err =~ s/\n.*//s;
  1610. WARN("Datasource '$source' could not order its posts: $err");
  1611. @ordered = @filtered;
  1612. }
  1613. # Which the paginator below reads, since these page by offset rather than by
  1614. # the created cursor stored posts use.
  1615. $query->{is_datasource} = 1;
  1616. # A source which cannot say when its posts go stale must not have its pages
  1617. # saved as statics: nothing else would ever invalidate them, so the cached
  1618. # copy could never become right again. See Trog::DataSource::cacheable.
  1619. $query->{nocache} = 1 unless Trog::DataSource::cacheable($source);
  1620. return @ordered;
  1621. }
  1622. =head2 paginate_offset($query, $limit, @posts) = ($page, $pages_total, @page_of_posts)
  1623. The slice of @posts the reader asked for, by page number.
  1624. Stored posts page by a cursor: the datastore is asked for the $limit posts older
  1625. than a timestamp, and the paginator hands back the oldest one on the page as the
  1626. next cursor. That is the right shape when the alternative is reading the whole
  1627. datastore to skip most of it.
  1628. It is the wrong shape for a datasource, which has already built every post by
  1629. the time we see them -- and it does not work at all for one which stamps them
  1630. all with the time it built them, as libvirt guests are. Every cursor on such a
  1631. page is the same instant, so Prev asks for everything older than now and gets
  1632. nothing. Offset costs nothing here and moves.
  1633. =cut
  1634. sub paginate_offset ( $query, $limit, @posts ) {
  1635. $limit = 25 if !$limit || $limit < 1;
  1636. my $total = scalar(@posts);
  1637. my $pages_total = $total ? int( ( $total + $limit - 1 ) / $limit ) : 1;
  1638. # Straight off a query string, so digits only -- the same coercion older and
  1639. # newer get, rather than int() warning its way through a word. Past the end
  1640. # shows the last page rather than an empty one, which is what a stale
  1641. # bookmark deserves.
  1642. ( my $wanted = $query->{page} // '' ) =~ s/\D//g;
  1643. my $page = $wanted ? int($wanted) : 1;
  1644. $page = 1 if $page < 1;
  1645. $page = $pages_total if $page > $pages_total;
  1646. my $offset = ( $page - 1 ) * $limit;
  1647. my @slice = $offset < $total ? @posts[ $offset .. List::Util::min( $offset + $limit, $total ) - 1 ] : ();
  1648. return ( $page, $pages_total, @slice );
  1649. }
  1650. =head2 search_language($query)
  1651. What to tell the reader the search box searches, as (language, help link).
  1652. The data model's answer describes what it can do to the datastore, which is the
  1653. right answer for nearly every page. It is the wrong one for a page whose posts
  1654. are built by a datasource rather than read out of the datastore, so such a page
  1655. gets to say so.
  1656. =cut
  1657. sub search_language ($query) {
  1658. state $data;
  1659. $data //= Trog::Data->new( Trog::Config::get() );
  1660. my $series = $query->{primary_post};
  1661. my $source = Ref::Util::is_hashref($series) && $series->{child_form} ? Trog::DataSource::for_type( $series->{child_form} ) : undef;
  1662. return ( $data->lang(), $data->help() ) unless $source && Trog::DataSource::load($source);
  1663. my $lang = $source->can('lang') // \&Trog::DataSource::lang;
  1664. my $help = $source->can('help') // \&Trog::DataSource::help;
  1665. return ( scalar $lang->(), scalar $help->() );
  1666. }
  1667. =head2 viewer_acls($query, $direct) = LIST
  1668. The acls to fetch posts for this viewer with: their own, and public, plus
  1669. unlisted when the route names one post directly, plus private for an admin.
  1670. A logged out visitor holds no acls of their own, and would see nothing without
  1671. this.
  1672. =cut
  1673. sub viewer_acls ( $query, $direct = 0 ) {
  1674. my @acls = ( @{ $query->{user_acls} // [] }, 'public' );
  1675. push( @acls, 'unlisted' ) if $direct;
  1676. push( @acls, 'private' ) if List::Util::any { $_ eq 'admin' } @acls;
  1677. return List::Util::uniq(@acls);
  1678. }
  1679. =head2 post_helper($query, $tags, $acls) = LIST
  1680. The posts that a listing shows: those tagged one of @$tags that @$acls can
  1681. see, filtered and paged by the fields of $query. page defaults to 1 and limit
  1682. to 25. For a logged in user, each local_href is under /secure.
  1683. =cut
  1684. sub post_helper ( $query, $tags, $acls ) {
  1685. state $data;
  1686. $data //= Trog::Data->new( Trog::Config::get() );
  1687. $query->{page} ||= 1;
  1688. $query->{limit} ||= 25;
  1689. my @d = $data->get(
  1690. older => $query->{older},
  1691. newer => $query->{newer},
  1692. page => int( $query->{page} ),
  1693. limit => int( $query->{limit} ),
  1694. tags => $tags,
  1695. exclude_tags => $query->{exclude_tags},
  1696. acls => $acls,
  1697. aclname => $query->{aclname},
  1698. like => $query->{like},
  1699. author => $query->{author},
  1700. id => $query->{id},
  1701. version => $query->{version},
  1702. form => $query->{form},
  1703. );
  1704. return map {
  1705. my $subj = $_;
  1706. $subj->{local_href} = "/secure$_->{local_href}";
  1707. $subj
  1708. } @d if $query->{user};
  1709. return @d;
  1710. }
  1711. =head2 sitemap
  1712. Return the sitemap index unless the static or a set of dynamic routes is requested.
  1713. We have a maximum of 99,990,000 posts we can make under this model
  1714. As we have 10,000 * 10,000 posts which are indexable via the sitemap format.
  1715. 1 top level index slot (10k posts) is taken by our static routes, the rest will be /posts.
  1716. Passing ?xml=1 will result in an appropriate sitemap.xml instead.
  1717. This is used to generate the static sitemaps as expected by search engines.
  1718. Passing compressed=1 will gzip the output.
  1719. =cut
  1720. sub sitemap ($query) {
  1721. state $data;
  1722. $data //= Trog::Data->new( Trog::Config::get() );
  1723. state $etag = "sitemap-" . time();
  1724. my ( @to_map, $is_index, $route_type );
  1725. my $warning = '';
  1726. $query->{map} //= '';
  1727. if ( $query->{map} eq 'static' ) {
  1728. # Return the map of static routes
  1729. $route_type = 'Static Routes';
  1730. @to_map = grep { CORE::index( $_, '{' ) < 0 && !$routes{$_}->{auth} && !$routes{$_}->{noindex} && !$routes{$_}->{nomap} } keys(%routes);
  1731. }
  1732. elsif ( !$query->{map} ) {
  1733. # Return the index instead
  1734. @to_map = ('static');
  1735. my $tot = $data->count();
  1736. my $size = 50000;
  1737. my $pages = int( $tot / $size ) + ( ( $tot % $size ) ? 1 : 0 );
  1738. # Truncate pages at 10k due to standard
  1739. my $clamped = $pages > 49999 ? 49999 : $pages;
  1740. $warning = "More posts than possible to represent in sitemaps & index! Old posts have been truncated." if $pages > 49999;
  1741. foreach my $page ( $clamped .. 1 ) {
  1742. push( @to_map, "$page" );
  1743. }
  1744. $is_index = 1;
  1745. }
  1746. else {
  1747. $route_type = "Posts: Page $query->{map}";
  1748. # Return the map of the particular range of dynamic posts
  1749. $query->{limit} = 50000;
  1750. $query->{page} = $query->{map};
  1751. @to_map = post_helper( $query, [], ['public'] );
  1752. }
  1753. if ( $query->{xml} ) {
  1754. DEBUG("RENDER SITEMAP XML");
  1755. my $sm;
  1756. my $xml_date = time();
  1757. my $fmt = "xml";
  1758. $fmt .= ".gz" if $query->{compressed};
  1759. if ( !$query->{map} ) {
  1760. require WWW::SitemapIndex::XML;
  1761. $sm = WWW::SitemapIndex::XML->new();
  1762. foreach my $url (@to_map) {
  1763. $sm->add(
  1764. loc => "http://$query->{domain}/sitemap/$url.$fmt",
  1765. lastmod => $xml_date,
  1766. );
  1767. }
  1768. }
  1769. else {
  1770. require WWW::Sitemap::XML;
  1771. $sm = WWW::Sitemap::XML->new();
  1772. my $changefreq = $query->{map} eq 'static' ? 'monthly' : 'daily';
  1773. foreach my $url (@to_map) {
  1774. my $true_uri = "http://$query->{domain}$url";
  1775. if ( ref $url eq 'HASH' ) {
  1776. my $is_user_page = grep { $_ eq 'about' } @{ $url->{tags} };
  1777. $true_uri = "http://$query->{domain}/posts/$url->{id}";
  1778. $true_uri = "http://$query->{domain}/users/$url->{title}" if $is_user_page;
  1779. }
  1780. my %out = (
  1781. loc => $true_uri,
  1782. lastmod => $xml_date,
  1783. mobile => 1,
  1784. changefreq => $changefreq,
  1785. priority => 1.0,
  1786. );
  1787. if ( ref $url eq 'HASH' ) {
  1788. #add video & preview image if applicable
  1789. $out{images} = [
  1790. {
  1791. loc => "http://$query->{domain}$url->{href}",
  1792. caption => $url->{data},
  1793. title => substr( $url->{title}, 0, 100 ),
  1794. }
  1795. ]
  1796. if $url->{is_image};
  1797. # Truncate descriptions
  1798. my $desc = substr( $url->{data}, 0, 2048 ) || '';
  1799. my $href = $url->{href} || '';
  1800. my $preview = $url->{preview} || '';
  1801. my $domain = $query->{domain} || '';
  1802. $out{videos} = [
  1803. {
  1804. content_loc => "http://$domain$href",
  1805. thumbnail_loc => "http://$domain$preview",
  1806. title => substr( $url->{title}, 0, 100 ) || '',
  1807. description => $desc,
  1808. }
  1809. ]
  1810. if $url->{is_video};
  1811. }
  1812. $sm->add(%out);
  1813. }
  1814. }
  1815. my $xml = $sm->as_xml();
  1816. require IO::String;
  1817. my $buf = IO::String->new();
  1818. my $ct = 'application/xml';
  1819. $xml->toFH( $buf, 0 );
  1820. seek $buf, 0, 0;
  1821. if ( $query->{compressed} ) {
  1822. require IO::Compress::Gzip;
  1823. my $compressed = IO::String->new();
  1824. IO::Compress::Gzip::gzip( $buf => $compressed );
  1825. $ct = 'application/gzip';
  1826. $buf = $compressed;
  1827. seek $compressed, 0, 0;
  1828. }
  1829. #XXX This is one of the few exceptions where we don't use finish_render, as it *requires* gzip.
  1830. return [ 200, [ "Content-type" => $ct, 'ETag' => $etag ], $buf ];
  1831. }
  1832. @to_map = sort @to_map unless $is_index;
  1833. my $styles = ['sitemap.css'];
  1834. $query->{title} = "$query->{domain} : Sitemap";
  1835. $query->{template} = 'sitemap.tx';
  1836. $query->{to_map} = \@to_map;
  1837. $query->{is_index} = $is_index;
  1838. $query->{route_type} = $route_type;
  1839. $query->{etag} = $etag;
  1840. return Trog::Routes::HTML::index( $query, undef, $styles );
  1841. }
  1842. =head2 manual
  1843. Implements the /manual and /lib/* routes.
  1844. Basically a thin wrapper around Pod::Html.
  1845. =cut
  1846. sub manual ($query) {
  1847. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1848. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  1849. require Pod::Html;
  1850. require Capture::Tiny;
  1851. #Fix links from Pod::HTML
  1852. $query->{module} =~ s/\.html$//g if $query->{module};
  1853. $query->{failure} //= -1;
  1854. my $infile = $query->{module} ? "$query->{module}.pm" : 'tCMS/Manual.pod';
  1855. my $found = 0;
  1856. foreach my $libdir (@INC) {
  1857. $found = $libdir if -f "$libdir/$infile"; ## no critic (ProhibitFiletest_f) -- which @INC dir supplies the pod
  1858. last if $found;
  1859. }
  1860. return $query->{tpsgi}->notfound($query) unless $found;
  1861. my $content = capture { Pod::Html::pod2html( qw{--podpath=lib --podroot=.}, "--infile=$found/$infile" ) };
  1862. return Trog::Routes::HTML::index(
  1863. {
  1864. title => 'tCMS Manual',
  1865. theme_dir => Trog::Themes::td(),
  1866. content => $content,
  1867. template => 'manual.tx',
  1868. is_admin => 1,
  1869. %$query,
  1870. },
  1871. undef,
  1872. ['post.css'],
  1873. );
  1874. }
  1875. =head2 processed
  1876. Implements /processed.
  1877. The "we got it, go check your email" page, shown after a request that finishes
  1878. out of band -- password and TOTP resets, chiefly. Deliberately says nothing
  1879. about whether the account existed.
  1880. =cut
  1881. sub processed {
  1882. return Trog::Routes::HTML::index(
  1883. {
  1884. title => "Your request has been processed",
  1885. theme_dir => Trog::Themes::td(),
  1886. },
  1887. "Your request has been processed.<br /><br />You will recieve subsequent communications about this matter via means you have provided earlier.",
  1888. ['post.css']
  1889. );
  1890. }
  1891. =head2 metrics
  1892. Implements /metrics. Admin only.
  1893. Renders the request metrics dashboard. The page pulls its actual numbers from
  1894. /api/requests_per over XHR and draws them with chart.js, so there's nothing to
  1895. compute here.
  1896. =cut
  1897. sub metrics ($query) {
  1898. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1899. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  1900. $query->{failure} //= -1;
  1901. return Trog::Routes::HTML::index(
  1902. {
  1903. title => 'tCMS Metrics',
  1904. theme_dir => Trog::Themes::td(),
  1905. template => 'metrics.tx',
  1906. is_admin => 1,
  1907. %$query,
  1908. },
  1909. undef,
  1910. ['post.css'],
  1911. ['chart.min.js'],
  1912. );
  1913. }
  1914. =head2 sessions
  1915. Implements /sessions. Admin only.
  1916. The session audit log: logins, logouts and failures, most recent first.
  1917. Filterable by username and event type via the filter_user and filter_event
  1918. parameters, and capped by limit (100 by default).
  1919. Timestamps are formatted here rather than in the template, and session ids are
  1920. truncated to their first 8 characters -- there's no reason to put a live
  1921. session id on a page.
  1922. =cut
  1923. sub sessions ($query) {
  1924. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  1925. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  1926. my $limit = int( $query->{limit} // 100 );
  1927. my $events = Trog::Auth::audit_log(
  1928. limit => $limit,
  1929. username => $query->{filter_user} // '',
  1930. event_type => $query->{filter_event} // '',
  1931. );
  1932. # Format timestamps for display
  1933. @$events = map {
  1934. my $e = {%$_};
  1935. my @t = localtime( $e->{event_time} );
  1936. $e->{event_ts} = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $t[5] + 1900, $t[4] + 1, $t[3], $t[2], $t[1], $t[0] );
  1937. $e->{session_short} = $e->{session_id} ? substr( $e->{session_id}, 0, 8 ) . '...' : '';
  1938. $e
  1939. } @$events;
  1940. return Trog::Routes::HTML::index(
  1941. {
  1942. title => 'tCMS Session Audit Log',
  1943. theme_dir => Trog::Themes::td(),
  1944. template => 'sessions.tx',
  1945. is_admin => 1,
  1946. events => $events,
  1947. limit => $limit,
  1948. filter_user => $query->{filter_user} // '',
  1949. filter_event => $query->{filter_event} // '',
  1950. %$query,
  1951. },
  1952. undef,
  1953. ['post.css'],
  1954. );
  1955. }
  1956. # The canned includes the wizard is willing to splice into a generated form.
  1957. # Deliberately a whitelist keyed on the checkbox name -- the include name ends
  1958. # up interpolated straight into a template file, so it can never come from the
  1959. # submitted data.
  1960. our %wizard_includes = (
  1961. inc_preview => 'preview.tx',
  1962. inc_visibility => 'visibility.tx',
  1963. inc_acls => 'acls.tx',
  1964. inc_tags => 'tags.tx',
  1965. inc_aliases => 'aliases.tx',
  1966. inc_attachments => 'attachments.tx',
  1967. );
  1968. # Emitted in this order, so generated forms read like the hand-written ones.
  1969. our @wizard_include_order = qw{inc_preview inc_visibility inc_acls inc_tags inc_aliases inc_attachments};
  1970. # Every checkbox on the wizard, and which of them start out ticked.
  1971. # Every post has a title, a visibility and a set of acls, so a type does not
  1972. # get to decide whether its editor collects them -- see post_wizard_save.
  1973. our @wizard_mandatory = qw{inc_title_input inc_visibility inc_acls};
  1974. our @wizard_optional_includes = grep {
  1975. my $include = $_;
  1976. List::Util::none { $include eq $_ } @wizard_mandatory
  1977. } @wizard_include_order;
  1978. # The checkboxes which are not editor includes: the wrapper div, and the two
  1979. # canned blocks a type splices into its display half. Read back out of the
  1980. # template by wizard_display_of(), since %wizard_includes covers only the
  1981. # blocks that go into the editor.
  1982. our @wizard_display_checkboxes = qw{wrapper inc_post_title inc_post_tags};
  1983. our @wizard_checkboxes = ( @wizard_display_checkboxes, @wizard_optional_includes, 'overwrite' );
  1984. our %wizard_checked_by_default = map { $_ => 1 } qw{wrapper inc_post_title inc_post_tags inc_preview inc_tags inc_aliases};
  1985. # Which HTML input the wizard emits, and what that field is in the sidecar's
  1986. # OpenAPIv3 schema. No 'file': process() in Trog::DataModule only knows how to
  1987. # turn the four hardcoded upload fields into hrefs, so a custom file field would
  1988. # store an HTTP::Body::OctetStream that nothing ever picks up. Point folks at
  1989. # the attachment uploader instead.
  1990. our %wizard_field_types = (
  1991. relation => { type => 'relation' },
  1992. text => { type => 'string' },
  1993. url => { type => 'string' },
  1994. date => { type => 'string' },
  1995. textarea => { type => 'string' },
  1996. number => { type => 'integer' },
  1997. checkbox => { type => 'boolean' },
  1998. );
  1999. # Field names which aren't in %schema but would still collide with something.
  2000. our @wizard_reserved = qw{app to form data_is_array addpost extra_tags is_image is_video is_audio is_profile content_type version};
  2001. # The hypervisor post a guest route was asked about. Looked up rather than
  2002. # taken from the request: the connection URI is not something a form gets to
  2003. # hand us.
  2004. my sub guest_hypervisor ( $query, $id ) {
  2005. return undef unless $id;
  2006. my @found = post_helper( { id => $id }, [], $query->{user_acls} );
  2007. return undef unless @found && ( $found[0]{conn_uri} // '' );
  2008. return $found[0];
  2009. }
  2010. =head2 guest_screenshot
  2011. Implements GET /guest/screenshot/$hypervisor/$guest. Admin only.
  2012. Served as its own route rather than inlined into the guest listing, so that a
  2013. page of guests renders immediately and the browser fetches the console
  2014. captures in parallel instead of us taking them one after another.
  2015. =cut
  2016. sub guest_screenshot ($query) {
  2017. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  2018. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  2019. my $hypervisor = guest_hypervisor( $query, $query->{hypervisor} );
  2020. return $query->{tpsgi}->notfound($query) unless $hypervisor;
  2021. require Trog::DataSource::Virt;
  2022. my ( $path, $why ) = Trog::DataSource::Virt::screenshot( $hypervisor, $query->{guest} );
  2023. if ( !$path ) {
  2024. WARN("Could not screenshot '$query->{guest}': $why");
  2025. return $query->{tpsgi}->notfound($query);
  2026. }
  2027. return $query->{tpsgi}->serve(
  2028. $query->{route}, $path, $query->{start}, $query->{streaming},
  2029. $query->{ranges}, $query->{last_fetched}, $query->{deflate},
  2030. );
  2031. }
  2032. =head2 guest_act
  2033. Implements POST /guest/act. Admin only.
  2034. Powering a guest on or off, snapshotting it, or destroying it. Separate from
  2035. everything that merely reads a guest, and the only route which reaches
  2036. Trog::DataSource::Virt::act.
  2037. =cut
  2038. sub guest_act ($query) {
  2039. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  2040. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  2041. my $to = $query->{to} || '/';
  2042. my $hypervisor = guest_hypervisor( $query, $query->{hypervisor} );
  2043. return feedback_redirect( $query, $to, 1, 'No such hypervisor.' ) unless $hypervisor;
  2044. require Trog::DataSource::Virt;
  2045. # Same reason the screenshot route captures 'guest': a form field called
  2046. # 'domain' would be overwritten by the router with the request's host.
  2047. my ( $ok, $message ) = Trog::DataSource::Virt::act(
  2048. $query->{action}, $hypervisor->{conn_uri}, $query->{guest}, $query->{user},
  2049. );
  2050. return feedback_redirect( $query, $to, $ok ? 0 : 1, "$query->{guest}: $message" );
  2051. }
  2052. =head2 guest_reprovision
  2053. Implements POST /guest/reprovision. Admin only.
  2054. Rebuilding a guest from the recipe it was provisioned with: bin/provision in
  2055. trog-provisioner. The only route which reaches
  2056. Trog::DataSource::ProvisionedVirt::reprovision.
  2057. This is not a recoverable operation, so read that function before changing
  2058. anything here. It refuses for the guest tCMS is itself running on.
  2059. What the provisioner needs arrives with the request and never lands in this hash:
  2060. the passphrase to its secrets database, the sudo password on the hypervisor if
  2061. that login has no passwordless sudo, or a TOTP code which is spent and exchanged
  2062. for whichever of those they kept last time.
  2063. =cut
  2064. sub guest_reprovision ($query) {
  2065. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  2066. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  2067. my $to = $query->{to} || '/';
  2068. require Trog::DataSource::ProvisionedVirt;
  2069. # 'guest' rather than 'domain', for the reason the screenshot route captures
  2070. # it that way: the router overwrites $query->{domain} with the request's own
  2071. # host, so a form field by that name never arrives.
  2072. my ( $ok, $message ) = Trog::DataSource::ProvisionedVirt::reprovision(
  2073. domain => $query->{guest},
  2074. user => $query->{user},
  2075. passphrase => $query->{passphrase},
  2076. sudo => $query->{sudo},
  2077. totp => $query->{totp},
  2078. remember => $query->{remember},
  2079. );
  2080. # Deleted rather than merely unused: this hash is cloned, logged around and
  2081. # handed to renderers, and neither of these has any business in any of that.
  2082. # The code as much as the passphrase -- it is spent by now, but a spent code
  2083. # in a log is still a code somebody wrote down.
  2084. delete $query->{$_} foreach qw{passphrase sudo totp};
  2085. return feedback_redirect( $query, $to, $ok ? 0 : 1, ( $query->{guest} // 'guest' ) . ": $message" );
  2086. }
  2087. =head2 guest_reprovision_log
  2088. Implements GET /guest/reprovision/log/$guest. Admin only.
  2089. The whole log of a guest's last reprovision, which the listing shows only the
  2090. tail of. Nobody is waiting on the process which writes it, so this is the only
  2091. account of what happened there is.
  2092. Admin only and served rather than linked directly, because it lives in logs/
  2093. rather than under www/ -- and because the output of a provisioner is a
  2094. reasonable place for a hostname, an IP plan or a package list to turn up.
  2095. =cut
  2096. sub guest_reprovision_log ($query) {
  2097. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  2098. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  2099. require Trog::DataSource::ProvisionedVirt;
  2100. my $log = Trog::DataSource::ProvisionedVirt::log_for( $query->{guest} );
  2101. return $query->{tpsgi}->notfound($query) unless defined $log;
  2102. return Trog::Renderer->render(
  2103. template => 'reprovision_log.tx',
  2104. contenttype => 'text/plain',
  2105. code => 200,
  2106. data => { %$query, body => $log },
  2107. );
  2108. }
  2109. # Repeated params arrive as arrayrefs; anywhere we want one string, insist on one string.
  2110. my sub wizard_scalar ( $value = '' ) {
  2111. return '' if !defined $value || ref $value;
  2112. return $value;
  2113. }
  2114. =head2 post_wizard
  2115. Implements /admin/wyzzerdd. Admin only.
  2116. The post type wizard: lists the post types which currently exist and offers a
  2117. form for building a new one. See post_wizard_save() for what happens when that
  2118. form comes back.
  2119. Re-rendered by post_wizard_save() on both success and failure, so it keeps the
  2120. submitted values and checkbox states rather than making the admin retype
  2121. everything after a rejected submission.
  2122. =cut
  2123. sub post_wizard ($query) {
  2124. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  2125. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  2126. $query->{failure} //= -1;
  2127. # Get the existing post types
  2128. my $forms = Trog::Themes::themed_templates_in_dir( "forms", 'text/html', 1 );
  2129. # Sticky checkboxes. Nothing is submitted on a fresh GET, so fall back to
  2130. # the defaults rather than rendering everything unticked.
  2131. my %checked = map { $_ => ( $query->{wizard_submitted} ? $query->{$_} : $wizard_checked_by_default{$_} ) ? 'checked' : '' } @wizard_checkboxes;
  2132. return Trog::Routes::HTML::index(
  2133. {
  2134. # Sticky form values first, so a failed submission doesn't lose the
  2135. # admin's work -- but everything the template actually depends on is
  2136. # set *after* this, as the whole of %$query is attacker controlled.
  2137. %$query,
  2138. title => 'tCMS Post Wizard',
  2139. theme_dir => Trog::Themes::td(),
  2140. template => 'post_wizard.tx',
  2141. is_admin => 1,
  2142. forms => $forms,
  2143. forms_dir => Trog::Themes::forms_dir(),
  2144. types => wizard_types_json($forms),
  2145. type_names => [ map { ( $_ =~ s/\.tx$//r ) } @$forms ],
  2146. description => wizard_description( $query->{description} ),
  2147. datasources => get_datasources(),
  2148. datasource => wizard_scalar( $query->{datasource} ),
  2149. checked => \%checked,
  2150. name => wizard_scalar( $query->{name} ),
  2151. title_placeholder => wizard_scalar( $query->{title_placeholder} ),
  2152. body_form => wizard_scalar( $query->{body_form} ),
  2153. display => wizard_scalar( $query->{display} ),
  2154. failure => $query->{failure},
  2155. message => $query->{message} // '',
  2156. to => $query->{to} // '',
  2157. },
  2158. undef,
  2159. ['post.css'],
  2160. ['post_wizard.js'],
  2161. );
  2162. }
  2163. =head2 wizard_reindex($name, $fields)
  2164. Bring the data model's idea of which custom fields are queryable into line with
  2165. what the post types on disk declare.
  2166. Every type's indexed fields, not just the one that was saved: two types can
  2167. declare a field of the same name, so reconciling against one of them alone would
  2168. have saving that type drop the other's index.
  2169. The type being saved is taken from the field list in hand rather than by reading
  2170. back the sidecar just written. schema_for() caches on the mtime of the forms
  2171. directory, which has one second of resolution, so a read here can legitimately
  2172. land on the generation before this save.
  2173. Returns the error if there was one, and nothing if all was well. A failure to
  2174. index is not a failure to create the post type: the type is written by this
  2175. point, works, and is only missing an optimization.
  2176. =cut
  2177. my sub wizard_reindex ( $name, $fields ) { ## no critic (ProhibitSingleUseLexicalSubs) -- 22 lines, which would overcomplicate post_wizard_save()
  2178. my %indexed = map { $_->{name} => 1 } grep { $_->{indexed} } @$fields;
  2179. my $this_type = "$name.tx";
  2180. foreach my $form ( @{ Trog::Themes::themed_templates_in_dir( 'forms', 'text/html', 1 ) } ) {
  2181. next if $form eq $this_type;
  2182. $indexed{$_} = 1 foreach @{ Trog::DataModule::indexed_fields_for($form) };
  2183. }
  2184. local $@;
  2185. eval {
  2186. my $data = Trog::Data->new( Trog::Config::get() );
  2187. $data->index_fields( sort keys %indexed );
  2188. 1;
  2189. } or do {
  2190. my $error = $@;
  2191. WARN("Could not reconcile custom field indexes: $error");
  2192. return $error;
  2193. };
  2194. return;
  2195. }
  2196. my sub wizard_fail ( $query, $message ) {
  2197. WARN($message);
  2198. return post_wizard(
  2199. {
  2200. %$query,
  2201. wizard_submitted => 1,
  2202. failure => 1,
  2203. message => $message,
  2204. }
  2205. );
  2206. }
  2207. my sub wizard_field_html ($field) { ## no critic (ProhibitSingleUseLexicalSubs) -- 23 lines, which would overcomplicate wizard_template()
  2208. my ( $n, $t, $l, $p ) = @$field{qw{name type label placeholder}};
  2209. my $required = $field->{required} ? 'required ' : '';
  2210. if ( $t eq 'relation' ) {
  2211. # 'all' relations aren't stored, so there is nothing to edit.
  2212. return '' if $field->{relation_mode} eq 'all';
  2213. # Left empty on purpose: post_relations.js fills it from
  2214. # /api/posts_of_form, so the picker can't go stale against the
  2215. # generated template.
  2216. return qq| $l<br /><select ${required}class="cooltext relation-picker" name="$n" data-relation-form="$field->{relation_form}" data-selected="<: \$post.$n :>"></select>\n|;
  2217. }
  2218. return qq| $l<br /><textarea ${required}class="cooltext" name="$n" placeholder="$p"><: \$post.$n :></textarea>\n|
  2219. if $t eq 'textarea';
  2220. 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|
  2221. if $t eq 'checkbox';
  2222. return qq| $l<br /><input ${required}class="cooltext" type="$t" name="$n" placeholder="$p" value="<: \$post.$n :>" />\n|;
  2223. }
  2224. =head2 wizard_template
  2225. Assemble the actual .tx file, following the shape of the hand-written forms:
  2226. a display half guarded by !$post.addpost, and an edit half guarded by $can_edit.
  2227. =cut
  2228. my sub wizard_template ( $query, $fields, $includes, $body_form, $datasource = '' ) { ## no critic (ProhibitSingleUseLexicalSubs) -- 54 lines, which would overcomplicate post_wizard_save()
  2229. my $placeholder = kolon_safe( $query->{title_placeholder} ) || 'Iowa Man Destroys Moon';
  2230. # NOT escaped, on purpose. Letting an admin write template code is the
  2231. # entire point of the wizard, and it is no more privileged than the data
  2232. # field of any post, which already gets run through render_it(). Both
  2233. # sides of this route are behind the admin ACL.
  2234. my $display = wizard_scalar( $query->{display} );
  2235. my $out = "<!-- Generated by the tCMS Post Type Wizard. Regenerating this type will overwrite any hand edits. -->\n";
  2236. # A series can ask for its children to be tiled, which is a layout the
  2237. # wrapper has to carry -- see how file.tx and series.tx do it. Harmless
  2238. # when the series hasn't asked, and it means a generated type gets tiling
  2239. # for free rather than being the one kind of post that ignores the setting.
  2240. $out .= qq|<div class="post <: \$style :> <: \$tiled ? 'tile' : '' :>">\n| if $query->{wrapper};
  2241. $out .= qq| : if ( !\$post.addpost ) {\n|;
  2242. $out .= qq| : include "post_title.tx";\n| if $query->{inc_post_title};
  2243. $out .= qq| : include "post_tags.tx";\n| if $query->{inc_post_tags};
  2244. $out .= "$display\n" if $display;
  2245. $out .= qq| : }\n|;
  2246. # A datasource can say its posts are built rather than written, in which
  2247. # case an editor would be a form saving something nobody can edit -- and
  2248. # for Trog::DataSource::Virt, one that writes a real post to sit alongside
  2249. # the synthesized ones and collide with them.
  2250. if ( !datasource_editable($datasource) ) {
  2251. $out .= qq|</div>\n| if $query->{wrapper};
  2252. return $out;
  2253. }
  2254. $out .= qq|\n|;
  2255. $out .= qq| : if ( \$can_edit ) {\n|;
  2256. $out .= qq| <div class="postedit">\n|;
  2257. $out .= qq| : include "edit_head.tx";\n|;
  2258. $out .= qq| <form class="Submissions" action="/post/save" method="POST" enctype="multipart/form-data">\n|;
  2259. $out .= qq| Title *<br /><input required class="cooltext" type="text" name="title" placeholder="$placeholder" value="<: \$post.title :>" />\n|
  2260. if $query->{inc_title_input};
  2261. $out .= wizard_field_html($_) foreach @$fields;
  2262. foreach my $include (@$includes) {
  2263. $out .= qq| : include "$wizard_includes{$include}";\n|;
  2264. }
  2265. # Always last, and never optional: this is what carries the post body, the
  2266. # app/to/id/form hiddens and the submit button.
  2267. $out .= qq| : include "$body_form";\n|;
  2268. $out .= qq| </form>\n|;
  2269. $out .= qq| : include "edit_foot.tx";\n|;
  2270. $out .= qq| </div>\n|;
  2271. $out .= qq| : }\n|;
  2272. $out .= qq|</div>\n| if $query->{wrapper};
  2273. return $out;
  2274. }
  2275. =head2 post_wizard_save
  2276. Implements POST /admin/wyzzerdd/save.
  2277. Writes a new post type template into whichever forms directory is currently in
  2278. use, along with a JSON sidecar naming its custom fields so that
  2279. Trog::DataModule::schema_for will merge it over the base post schema, so the
  2280. type's own fields survive validation at save time.
  2281. =cut
  2282. sub post_wizard_save ($query) {
  2283. return $query->{tpsgi}->see_also('/login') unless $query->{user};
  2284. return $query->{tpsgi}->forbidden($query) unless List::Util::any { $_ eq 'admin' } @{ $query->{user_acls} };
  2285. # Anchored capture rather than a substitution, so anything containing a '/'
  2286. # or a '..' simply fails to match instead of being silently scrubbed into
  2287. # something that still escapes the directory.
  2288. my ($name) = wizard_scalar( $query->{name} ) =~ m/^([\w-]+)$/;
  2289. return wizard_fail( $query, "Post type names may only contain letters, numbers, '-' and '_'." ) unless $name;
  2290. # Whichever forms dir is in use: the theme's if it has one, the stock one
  2291. # otherwise. Never mkdir it -- silently conjuring a forms/ dir inside a
  2292. # theme is not something an admin asked for by pressing this button.
  2293. my $dir = Trog::Themes::forms_dir();
  2294. # -d only. A -w here would check mode bits against our uid, which says
  2295. # nothing about read-only mounts, ACLs or immutable flags -- and it is the
  2296. # files, not the directory, that get written. The eval around the two
  2297. # spew_utf8 calls below reports the real errno when a write actually fails.
  2298. return wizard_fail( $query, "Forms directory '$dir' does not exist." ) unless -d $dir;
  2299. my $tx_file = "$dir/$name.tx";
  2300. my $json_file = "$dir/$name.json";
  2301. my $overwriting = -e $tx_file;
  2302. return wizard_fail( $query, "Post type '$name.tx' already exists. Tick 'Overwrite' if you meant to replace it." )
  2303. if $overwriting && !$query->{overwrite};
  2304. # Whitelisted against what is actually on disk: this name goes into a
  2305. # sidecar and is require()d later, so a regex is not enough.
  2306. my $datasource = wizard_scalar( $query->{datasource} );
  2307. if ( $datasource && List::Util::none { $_ eq $datasource } @{ get_datasources() } ) {
  2308. return wizard_fail( $query, "'$datasource' is not a datasource I can find." );
  2309. }
  2310. my $fields = wizard_fields($query);
  2311. # Not up for discussion. A post with no visibility gets an undef pushed
  2312. # into its tags by process, which is a tag nothing matches -- so the post
  2313. # is invisible to everyone but an admin, for no reason anybody chose. A
  2314. # title and a set of acls are equally non-negotiable: every other form has
  2315. # them, and a type whose editor cannot set them produces posts nobody can
  2316. # title or restrict.
  2317. $query->{$_} = 1 foreach @wizard_mandatory;
  2318. my @includes = grep { $query->{$_} } @wizard_include_order;
  2319. my $body_form = wizard_scalar( $query->{body_form} ) eq 'form_multi.tx' ? 'form_multi.tx' : 'form_common.tx';
  2320. my $spec = wizard_sidecar(
  2321. $name, $fields, \@includes, $body_form, $datasource,
  2322. {
  2323. description => wizard_description( $query->{description} ),
  2324. display => wizard_scalar( $query->{display} ),
  2325. title_placeholder => wizard_scalar( $query->{title_placeholder} ),
  2326. map { $_ => $query->{$_} ? 1 : 0 } qw{wrapper inc_post_title inc_post_tags},
  2327. }
  2328. );
  2329. local $@;
  2330. eval {
  2331. Path::Tiny::path($tx_file)->spew_utf8( wizard_template( $query, $fields, \@includes, $body_form, $datasource ) );
  2332. Path::Tiny::path($json_file)->spew_utf8( JSON::MaybeXS->new( pretty => 1, canonical => 1 )->encode($spec) );
  2333. 1;
  2334. } or return wizard_fail( $query, "Failed to write post type '$name': $@" );
  2335. INFO("Post type '$name' written to $tx_file by $query->{user}");
  2336. # Whatever the data model makes of an indexed field, it wants the whole
  2337. # picture rather than this type's share of it -- see wizard_reindex.
  2338. my $index_error = wizard_reindex( $name, $fields );
  2339. return wizard_fail( $query, "Post type '$name' was written, but indexing its fields failed: $index_error" ) if $index_error;
  2340. # Nothing else is needed to publish a new type: themed_templates_in_dir()
  2341. # re-reads
  2342. # the directory every call, and Xslate resolves includes lazily, so both the
  2343. # wizard's own list and the series child_form dropdown pick it up on the
  2344. # next request without a restart. Overwriting an *existing* type is another
  2345. # matter -- that changes how already-rendered anonymous pages should look.
  2346. if ($overwriting) {
  2347. $query->{tpsgi}->add_post_close_callback(
  2348. sub {
  2349. $query->{tpsgi}->invalidate_renders('html');
  2350. }
  2351. );
  2352. }
  2353. return post_wizard(
  2354. {
  2355. %$query,
  2356. wizard_submitted => 1,
  2357. failure => 0,
  2358. message => "Created post type '$name.tx'.",
  2359. to => '/admin/wyzzerdd',
  2360. }
  2361. );
  2362. }
  2363. =head2 short_error($error) = STRING
  2364. An error as a person should see it: the first line, without the file and line
  2365. number Perl glued onto the end.
  2366. add() dies with an arrayref of validation errors precisely so that they arrive
  2367. clean, but a failure further down -- a write that could not land, say -- is an
  2368. ordinary string die, and Carp::Always decorates those with the entire call
  2369. stack. That whole thing used to go to the user.
  2370. The undecorated original is logged; this is only what reaches the banner.
  2371. =cut
  2372. sub short_error ( $error = '' ) {
  2373. $error = "$error";
  2374. $error =~ s/\n.*//s;
  2375. $error =~ s/\s+at\s+\S+\s+line\s+\d+\.?\s*$//;
  2376. return $error;
  2377. }
  2378. # What a type's template says about the parts of it the wizard emits itself
  2379. # rather than through %wizard_includes: the wrapper div, and the two canned
  2380. # blocks which go in the display half rather than in the editor.
  2381. #
  2382. # Undef when the template cannot be read at all, which is what leaves the
  2383. # sidecar as the fallback rather than making it a second opinion. The template
  2384. # is what actually renders, so where the two disagree it is the template which
  2385. # is telling the truth.
  2386. my sub wizard_display_of ($form) { ## no critic (ProhibitSingleUseLexicalSubs) -- 26 lines, which would overcomplicate wizard_types()
  2387. my $path = Trog::Themes::themed_file_in_dir( 'forms', $form, 'text/html', 1 );
  2388. return undef unless $path;
  2389. my $template = eval { File::Slurper::read_text($path) };
  2390. return undef unless defined $template;
  2391. my %shown = (
  2392. inc_post_title => $template =~ m/^\s*:\s*include\s+"post_title\.tx"/m ? 1 : 0,
  2393. inc_post_tags => $template =~ m/^\s*:\s*include\s+"post_tags\.tx"/m ? 1 : 0,
  2394. wrapper => 0,
  2395. );
  2396. # The wrapper is the first thing a type that has one emits, ahead of any
  2397. # Kolon at all -- see wizard_template. So only the first line with
  2398. # anything on it is asked, and a type which opens with its own markup or its
  2399. # own directive is one that ticked the box off.
  2400. foreach my $line ( split( /\n/, $template ) ) {
  2401. next if $line =~ m/^\s*$/;
  2402. next if $line =~ m/^\s*<!--/;
  2403. $shown{wrapper} = 1 if $line =~ m/^\s*<div\s+class="post\b/;
  2404. last;
  2405. }
  2406. return \%shown;
  2407. }
  2408. # The custom fields of a type, as rows the wizard would have submitted.
  2409. my sub wizard_fields_of ( $schema, $meta, $includes = {} ) { ## no critic (ProhibitSingleUseLexicalSubs) -- 72 lines, which would overcomplicate wizard_types()
  2410. my $properties = $schema->{properties} // {};
  2411. my %required = map { $_ => 1 } @{ $schema->{required} // [] };
  2412. my $relations = $meta->{'x-tcms-relations'};
  2413. $relations = {} unless Ref::Util::is_hashref($relations);
  2414. # Whatever the canned blocks this type includes already collect. These are
  2415. # real fields of the type and really are in its schema, but nobody typed
  2416. # them into the wizard, and offering them back as custom fields is how
  2417. # ticking 'Preview image upload' and listing 'preview' as a text field came
  2418. # to be the same thing said twice.
  2419. my %canned;
  2420. foreach my $include ( keys(%$includes) ) {
  2421. my $collects = Trog::DataModule::include_schema_for($include)->{properties};
  2422. next unless Ref::Util::is_hashref($collects);
  2423. $canned{$_} = 1 foreach keys(%$collects);
  2424. }
  2425. my @fields;
  2426. foreach my $name ( sort keys(%$properties) ) {
  2427. # Only what this type added. Everything in the base post schema belongs
  2428. # to every post and was never a wizard field, and everything a canned
  2429. # block collects belongs to the block rather than to the type.
  2430. next if exists $Trog::DataModule::post_schema{properties}{$name};
  2431. next if $canned{$name};
  2432. my $property = $properties->{$name};
  2433. next unless Ref::Util::is_hashref($property);
  2434. push(
  2435. @fields,
  2436. {
  2437. name => $name,
  2438. type => $property->{'x-tcms-input'} // 'text',
  2439. label => $property->{'x-tcms-label'} // '',
  2440. placeholder => $property->{'x-tcms-placeholder'} // '',
  2441. required => $required{$name} ? 1 : 0,
  2442. private => $property->{'x-tcms-private'} ? 1 : 0,
  2443. indexed => $property->{'x-tcms-indexed'} ? 1 : 0,
  2444. relation_form => $property->{'x-tcms-relation-form'} // '',
  2445. relation_mode => 'one',
  2446. }
  2447. );
  2448. }
  2449. # A relation pulling in every post of its target type stores nothing, so it
  2450. # has no property to have been found above -- it exists only as a relations
  2451. # entry with no 'from'.
  2452. foreach my $name ( sort keys(%$relations) ) {
  2453. my $relation = $relations->{$name};
  2454. next unless Ref::Util::is_hashref($relation);
  2455. next if $relation->{from};
  2456. push(
  2457. @fields,
  2458. {
  2459. name => $name,
  2460. type => 'relation',
  2461. label => '',
  2462. placeholder => '',
  2463. required => 0,
  2464. private => 0,
  2465. indexed => 0,
  2466. relation_form => $relation->{form} // '',
  2467. relation_mode => 'all',
  2468. }
  2469. );
  2470. }
  2471. return \@fields;
  2472. }
  2473. =head2 wizard_display_from_template($form)
  2474. Recover a generated type's display template from the template itself.
  2475. For types written before the wizard started recording it in the sidecar. Only
  2476. attempted for a file carrying the generated marker, and only between the two
  2477. lines wizard_template puts around it, so this either finds exactly what was
  2478. submitted or finds nothing. A hand-written type finds nothing, which is correct:
  2479. there is no wizard form that produces one.
  2480. =cut
  2481. my sub wizard_display_from_template ($form) { ## no critic (ProhibitSingleUseLexicalSubs) -- 33 lines, which would overcomplicate wizard_types()
  2482. my $path = Trog::Themes::themed_file_in_dir( 'forms', $form, 'text/html', 1 );
  2483. return '' unless $path;
  2484. my $template = eval { File::Slurper::read_text($path) };
  2485. return '' unless defined $template;
  2486. my @lines = split( /\n/, $template );
  2487. # CORE::index because this package has an index() of its own -- the route
  2488. # that renders every page.
  2489. return '' if !@lines || CORE::index( $lines[0], 'Generated by the tCMS Post Type Wizard' ) == -1;
  2490. my ( @display, $inside );
  2491. foreach my $line (@lines) {
  2492. if ( !$inside ) {
  2493. $inside = 1 if $line =~ m/^\s*:\s*if\s*\(\s*!\$post\.addpost\s*\)\s*\{\s*$/;
  2494. next;
  2495. }
  2496. last if $line =~ m/^\s*:\s*\}\s*$/;
  2497. # The includes the wizard emitted, which are checkboxes rather than
  2498. # anything the admin typed into the display box.
  2499. next if $line =~ m/^\s*:\s*include\s+"/;
  2500. push( @display, $line );
  2501. }
  2502. my $display = join( "\n", @display );
  2503. $display =~ s/^\s+|\s+$//g;
  2504. return $display;
  2505. }
  2506. =head2 wizard_types($forms) = HASHREF
  2507. Every post type on disk, in the shape the wizard's form is in.
  2508. This is the other direction from wizard_sidecar: it reads a type back out and
  2509. says what the wizard would have had to be told to produce it, so that picking one
  2510. from the dropdown can put the form into that state.
  2511. Everything but the display template and the canned includes comes out of the
  2512. sidecar. The display comes out of the sidecar too for anything written since it
  2513. started being recorded there, and is read back out of the template itself
  2514. otherwise -- see wizard_display_from_template, and note that a hand-written type
  2515. will often yield nothing, which is honest: there is no wizard form that produces
  2516. it.
  2517. The includes always come out of the template, via
  2518. Trog::DataModule::includes_for(), since only a generated sidecar ever recorded
  2519. them. That is also what tells the field list apart from the checkboxes: a
  2520. preview image is a field of every type which includes preview.tx, so it is that
  2521. box being ticked rather than a custom field somebody added.
  2522. =cut
  2523. sub wizard_types ($forms) {
  2524. my %types;
  2525. foreach my $form (@$forms) {
  2526. my $schema = Trog::DataModule::schema_for($form);
  2527. my $meta = Trog::DataModule::type_meta_for($form);
  2528. my $type = $meta->{'x-tcms-post-type'};
  2529. $type = {} unless Ref::Util::is_hashref($type);
  2530. # What the editor actually splices in, which for a hand-written type is
  2531. # the only account there is -- nothing but a generated sidecar records
  2532. # the list. Keyed on the template name, which is what %wizard_includes
  2533. # maps a checkbox to.
  2534. my %includes = map { $_ => 1 } @{ Trog::DataModule::includes_for($form) };
  2535. my $display = $type->{display};
  2536. $display = wizard_display_from_template($form) unless $display;
  2537. # The wrapper div and the two blocks which belong to a type's display
  2538. # half rather than to its editor. Same reading as the includes, and for
  2539. # the same reason: a hand-written type recorded none of it, and the
  2540. # generated ones written before these were recorded did not either.
  2541. my $shown = wizard_display_of($form) // { map { $_ => $type->{$_} ? 1 : 0 } @wizard_display_checkboxes };
  2542. $types{$form} = {
  2543. name => ( $form =~ s/\.tx$//r ),
  2544. description => $type->{description} // '',
  2545. display => $display // '',
  2546. # An include like any other -- see the bottom of wizard_template. The
  2547. # sidecar is the fallback, for a datasource type with no editor at all.
  2548. body_form => ( List::Util::first { $includes{$_} } qw{form_multi.tx form_common.tx} ) // $type->{body_form} // 'form_common.tx',
  2549. datasource => $meta->{'x-tcms-datasource'} // '',
  2550. title_placeholder => $type->{title_placeholder} // '',
  2551. generated => $type->{generated} ? 1 : 0,
  2552. # The wizard's own checkboxes, every one of them an answer about
  2553. # what the template does rather than about what the sidecar says.
  2554. %$shown,
  2555. ( map { $_ => $includes{ $wizard_includes{$_} } ? 1 : 0 } @wizard_optional_includes ),
  2556. fields => wizard_fields_of( $schema, $meta, \%includes ),
  2557. };
  2558. }
  2559. return \%types;
  2560. }
  2561. =head2 wizard_types_json($forms) = STRING
  2562. wizard_types() as JSON, safe to drop into a script element.
  2563. Every '<' is escaped, which is still valid JSON and means the string cannot
  2564. close the element it is sitting in -- a display template is full of markup, and
  2565. one containing the characters that end a script tag would otherwise end it.
  2566. =cut
  2567. sub wizard_types_json ($forms) {
  2568. my $json = eval { JSON::MaybeXS->new( canonical => 1 )->encode( wizard_types($forms) ) };
  2569. if ( !defined $json ) {
  2570. WARN("Could not describe the existing post types: $@");
  2571. return '{}';
  2572. }
  2573. $json =~ s/</\\u003c/g;
  2574. return $json;
  2575. }
  2576. =head2 wizard_description($description)
  2577. A post type's description, as it goes into the sidecar.
  2578. Free text rather than template source: it is shown to whoever picks the type in
  2579. the wizard, and rendered as text, so the only thing to do to it is keep it a
  2580. sane length and stop it being something other than a string.
  2581. =cut
  2582. our $wizard_description_max = 2048;
  2583. sub wizard_description ( $description = '' ) {
  2584. $description = wizard_scalar($description);
  2585. $description = substr( $description, 0, $wizard_description_max ) if length($description) > $wizard_description_max;
  2586. return $description;
  2587. }
  2588. =head2 kolon_safe
  2589. Make a submitted string safe to splice into a generated Kolon template.
  2590. Newlines have to go, as a ':' at the start of a line is a Kolon directive, and
  2591. the angle brackets have to go so that '<:' can never be reassembled.
  2592. =cut
  2593. sub kolon_safe ( $string = '' ) {
  2594. $string = wizard_scalar($string);
  2595. $string =~ s/[\r\n]+/ /g;
  2596. $string =~ s/&/&amp;/g;
  2597. $string =~ s/</&lt;/g;
  2598. $string =~ s/>/&gt;/g;
  2599. $string =~ s/"/&quot;/g;
  2600. return $string;
  2601. }
  2602. =head2 wizard_fields
  2603. Zip the parallel param_* arrays submitted by the wizard back into a list of
  2604. field definitions. Every row always submits exactly one of each param, so the
  2605. arrays stay aligned even when a row is left blank.
  2606. =cut
  2607. sub wizard_fields ($query) {
  2608. my $names = Trog::Utils::coerce_array( $query->{param_name} );
  2609. my $types = Trog::Utils::coerce_array( $query->{param_type} );
  2610. my $labels = Trog::Utils::coerce_array( $query->{param_label} );
  2611. my $phs = Trog::Utils::coerce_array( $query->{param_placeholder} );
  2612. my $reqs = Trog::Utils::coerce_array( $query->{param_required} );
  2613. my $rforms = Trog::Utils::coerce_array( $query->{param_relation_form} );
  2614. my $rmodes = Trog::Utils::coerce_array( $query->{param_relation_mode} );
  2615. my $private = Trog::Utils::coerce_array( $query->{param_private} );
  2616. my $indexed = Trog::Utils::coerce_array( $query->{param_indexed} );
  2617. my ( @fields, %seen );
  2618. foreach my $index ( 0 .. $#$names ) {
  2619. my ($fname) = lc( wizard_scalar( $names->[$index] ) ) =~ m/^([[:lower:]][[:lower:]\d_]{0,31})$/;
  2620. # Blank and bogus rows just get dropped.
  2621. next unless $fname;
  2622. next if $seen{$fname}++;
  2623. # Never let a custom field shadow a core post attribute.
  2624. next if exists $Trog::DataModule::post_schema{properties}{$fname};
  2625. next if List::Util::any { $fname eq $_ } @wizard_reserved;
  2626. my $type = wizard_scalar( $types->[$index] );
  2627. $type = 'text' unless $wizard_field_types{$type};
  2628. # A relation is only a relation if it names a target type that looks
  2629. # like one; anything else falls back to being a plain text field.
  2630. my ($rform) = wizard_scalar( $rforms->[$index] ) =~ m/^([\w-]+\.tx)$/;
  2631. my $rmode = wizard_scalar( $rmodes->[$index] ) eq 'all' ? 'all' : 'one';
  2632. $type = 'text' if $type eq 'relation' && !$rform;
  2633. push(
  2634. @fields,
  2635. {
  2636. name => $fname,
  2637. type => $type,
  2638. label => kolon_safe( $labels->[$index] ) || ucfirst($fname),
  2639. placeholder => kolon_safe( $phs->[$index] ),
  2640. required => wizard_scalar( $reqs->[$index] ) ? 1 : 0,
  2641. relation_form => $rform,
  2642. relation_mode => $rmode,
  2643. private => wizard_scalar( $private->[$index] ) ? 1 : 0,
  2644. indexed => wizard_scalar( $indexed->[$index] ) ? 1 : 0,
  2645. }
  2646. );
  2647. }
  2648. return \@fields;
  2649. }
  2650. =head2 wizard_sidecar
  2651. Turn the wizard's field list into the post type's JSON sidecar: an OpenAPIv3
  2652. object schema describing what this type ingests, with the wizard's own UI
  2653. metadata hung off x- extension keys so there's only one file to keep in sync.
  2654. Trog::DataModule::schema_for() merges this over the base post schema.
  2655. =cut
  2656. sub wizard_sidecar ( $name, $fields, $includes, $body_form, $datasource = '', $extra = {} ) {
  2657. my %properties;
  2658. my @required;
  2659. my %relations;
  2660. foreach my $field (@$fields) {
  2661. # A relation pulling in every post of its target type isn't a field the
  2662. # post stores at all -- it is purely something injected at render, so
  2663. # it gets a relations entry and no property.
  2664. if ( $field->{type} eq 'relation' && $field->{relation_mode} eq 'all' ) {
  2665. $relations{ $field->{name} } = { form => $field->{relation_form} };
  2666. next;
  2667. }
  2668. my $property = { %{ $wizard_field_types{ $field->{type} } } };
  2669. $property->{'x-tcms-input'} = $field->{type};
  2670. $property->{'x-tcms-label'} = $field->{label};
  2671. $property->{'x-tcms-placeholder'} = $field->{placeholder} if ( $field->{placeholder} // q{} ) ne q{};
  2672. # Only written when it is true: a field is public unless it says so,
  2673. # and a sidecar full of x-tcms-private:false reads like the opposite.
  2674. $property->{'x-tcms-private'} = JSON::MaybeXS::true() if $field->{private};
  2675. # Likewise unindexed unless asked for. The sidecar is the declaration;
  2676. # post_wizard_save() reconciles the data model against it.
  2677. $property->{'x-tcms-indexed'} = JSON::MaybeXS::true() if $field->{indexed};
  2678. if ( $field->{type} eq 'relation' ) {
  2679. $property->{'x-tcms-relation-form'} = $field->{relation_form};
  2680. # The stored field holds a UUID; the resolved post lands beside it.
  2681. $relations{"$field->{name}_post"} = { form => $field->{relation_form}, from => $field->{name} };
  2682. }
  2683. $properties{ $field->{name} } = $property;
  2684. push( @required, $field->{name} ) if $field->{required};
  2685. }
  2686. # Everything the wizard was told, so that picking this type again puts the
  2687. # form back the way it was. It all lives under x-tcms-post-type, which
  2688. # schema_for() strips before validation -- the validator sees properties and
  2689. # required and nothing else, so none of this can affect whether a post saves.
  2690. my %spec = (
  2691. 'x-tcms-post-type' => {
  2692. name => $name,
  2693. generated => JSON::MaybeXS::true(),
  2694. generator => 'Trog::Routes::HTML::post_wizard_save',
  2695. body_form => $body_form,
  2696. includes => [ map { $wizard_includes{$_} } @$includes ],
  2697. description => $extra->{description} // '',
  2698. display => $extra->{display} // '',
  2699. # The checkboxes which are not includes, and so are not recoverable
  2700. # from the list above.
  2701. wrapper => $extra->{wrapper} ? JSON::MaybeXS::true() : JSON::MaybeXS::false(),
  2702. inc_post_title => $extra->{inc_post_title} ? JSON::MaybeXS::true() : JSON::MaybeXS::false(),
  2703. inc_post_tags => $extra->{inc_post_tags} ? JSON::MaybeXS::true() : JSON::MaybeXS::false(),
  2704. title_placeholder => $extra->{title_placeholder} // '',
  2705. },
  2706. type => 'object',
  2707. properties => \%properties,
  2708. );
  2709. $spec{required} = \@required if @required;
  2710. $spec{'x-tcms-relations'} = \%relations if %relations;
  2711. $spec{'x-tcms-datasource'} = $datasource if $datasource;
  2712. return \%spec;
  2713. }
  2714. # basically a file rewrite rule for themes
  2715. =head2 icon
  2716. Implements the /img/icon/* routes.
  2717. Serves a themed icon, falling back to the stock one. A rewrite rule with extra
  2718. steps, essentially, so that themes can replace individual icons.
  2719. =cut
  2720. sub icon ($query) {
  2721. my $path = $query->{route};
  2722. my $tpath = Trog::Themes::themed("img/icon/$path");
  2723. return $query->{tpsgi}->serve( $path, $tpath, $query->{start}, $query->{streaming}, $query->{ranges}, $query->{last_fetched}, $query->{deflate} );
  2724. }
  2725. =head2 bundle
  2726. Implements /bundle/{version}/{names}.js, the scripts of a page as one response.
  2727. See Trog::Bundle.
  2728. The body of a bundle is the same at a given href, so the browser keeps it. An
  2729. href with an old version is redirected to the current one, so a page that was
  2730. cached before a script changed still gets its scripts.
  2731. =cut
  2732. sub bundle ($query) {
  2733. my $bundle = Trog::Bundle::scripts( map { "$_.js" } split( /[+]/, $query->{names} ) );
  2734. return $query->{tpsgi}->notfound($query) unless $bundle;
  2735. return $query->{tpsgi}->redirect( $bundle->{href} ) if $query->{route} ne $bundle->{href};
  2736. return [
  2737. 200,
  2738. [
  2739. 'Content-type' => 'text/javascript',
  2740. 'Cache-Control' => $Trog::Vars::cache_control{static},
  2741. ],
  2742. [ $bundle->{body} ],
  2743. ];
  2744. }
  2745. =head2 totp_qr
  2746. Implements the /totp/* routes.
  2747. Serves the QR code generated when a user enables TOTP. These live outside
  2748. www/, so they go out through serve() rather than the static file handler --
  2749. handing someone else's enrollment QR out to the world would be handing them the
  2750. shared secret.
  2751. =cut
  2752. sub totp_qr ($query) {
  2753. my $fname = basename( $query->{route} );
  2754. # For authenticated content, we have to now do a serve().
  2755. return $query->{tpsgi}->serve(
  2756. "totp/$fname",
  2757. "totp/$fname",
  2758. $query->{start},
  2759. $query->{streaming},
  2760. $query->{ranges},
  2761. $query->{last_fetched},
  2762. $query->{deflate},
  2763. );
  2764. }
  2765. =head2 rss_style
  2766. Implements /styles/rss-style.xsl.
  2767. The XSL stylesheet which makes the RSS feed legible in a browser.
  2768. rss-style.tx pulls the header and footer in with component(), which works here
  2769. where an include directive would not: the output is XSL rather than HTML, so
  2770. the two are rendered separately and composed, and the header is asked for
  2771. without a doctype.
  2772. =cut
  2773. sub rss_style ($query) {
  2774. $query->{port} = ":$query->{port}" if $query->{port};
  2775. $query->{title} = qq{<xsl:value-of select="rss/channel/title"/>};
  2776. $query->{no_doctype} = 1;
  2777. return Trog::Renderer->render(
  2778. template => 'rss-style.tx',
  2779. contenttype => 'text/xsl',
  2780. data => $query,
  2781. code => 200,
  2782. );
  2783. }
  2784. =head2 finish_render($template, $vars, %headers)
  2785. Render a full page, as opposed to a component.
  2786. Fills in the defaults every page needs (lang, title, status code, content type,
  2787. cache control), resolves stylesheet and script names through the theme, makes
  2788. their paths absolute, and hands the lot to Trog::Renderer.
  2789. The page's own template asks for the header and footer with component(), so the
  2790. resolved stylesheet and script lists are passed on to Trog::Component::Header
  2791. rather than being rendered into a string here.
  2792. Just about everything in this module ends up here; index() is the usual way in.
  2793. =cut
  2794. sub finish_render ( $template, $vars, %headers ) {
  2795. #XXX default vars that need to be pulled from config
  2796. $vars->{lang} //= 'en-US';
  2797. $vars->{title} //= 'tCMS';
  2798. $vars->{stylesheets} //= [];
  2799. $vars->{print_styles} //= [qw{structure.css print.css}];
  2800. $vars->{scripts} //= [];
  2801. # Theme-ize the paths
  2802. $vars->{stylesheets} = [ @{ build_themed_styles( $vars->{stylesheets} ) } ];
  2803. $vars->{print_styles} = [ @{ build_themed_styles( $vars->{print_styles} ) } ];
  2804. my $bundle = Trog::Bundle::scripts( @{ Trog::Utils::coerce_array( $vars->{scripts} ) } );
  2805. $vars->{scripts} = $bundle ? [ $bundle->{href} ] : [];
  2806. Trog::Bundle::save( $vars->{tpsgi}, $bundle ) if $bundle;
  2807. # Add in avatars.css, it's special
  2808. push( @{ $vars->{stylesheets} }, "/styles/avatars.css" );
  2809. # Absolute-ize the paths for stylesheets
  2810. @{ $vars->{stylesheets} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{stylesheets} };
  2811. @{ $vars->{print_styles} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{print_styles} };
  2812. # TODO Smash together the stylesheets and minify
  2813. $vars->{contenttype} //= $Trog::Vars::content_types{html};
  2814. $vars->{cachecontrol} //= $Trog::Vars::cache_control{revalidate};
  2815. $vars->{code} ||= 200;
  2816. $vars->{theme_dir} =~ s/^\/www\/// if $vars->{theme_dir};
  2817. # %headers was accepted and then ignored, which nothing noticed because
  2818. # nothing passed any. index() passes one now, to expire the feedback cookie
  2819. # once its message has been rendered.
  2820. return Trog::Renderer->render(
  2821. template => $template,
  2822. data => $vars,
  2823. contenttype => 'text/html',
  2824. code => $vars->{code},
  2825. ( %headers ? ( headers => \%headers ) : () ),
  2826. );
  2827. }
  2828. 1;