HTML.pm 95 KB

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