HTML.pm 105 KB

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