HTML.pm 126 KB

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