HTML.pm 89 KB

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