HTML.pm 126 KB

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