HTML.pm 126 KB

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