HTML.pm 131 KB

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