HTML.pm 122 KB

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