HTML.pm 128 KB

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