HTML.pm 122 KB

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