HTML.pm 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  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 Errno qw{ENOENT};
  7. use File::Touch();
  8. use List::Util();
  9. use List::MoreUtils();
  10. use Capture::Tiny qw{capture};
  11. use HTML::SocialMeta;
  12. use Encode qw{encode_utf8};
  13. use IO::Compress::Gzip;
  14. use Path::Tiny();
  15. use File::Basename qw{dirname};
  16. use URI();
  17. use FindBin::libs;
  18. use Trog::Log qw{:all};
  19. use Trog::Utils;
  20. use Trog::Config;
  21. use Trog::Auth;
  22. use Trog::Data;
  23. use Trog::FileHandler;
  24. use Trog::Themes;
  25. use Trog::Renderer;
  26. use Trog::Component::EmojiPicker;
  27. my $conf = Trog::Config::get();
  28. our $landing_page = 'default.tx';
  29. our $htmltitle = 'title.tx';
  30. our $midtitle = 'midtitle.tx';
  31. our $rightbar = 'rightbar.tx';
  32. our $leftbar = 'leftbar.tx';
  33. our $topbar = 'topbar.tx';
  34. our $footbar = 'footbar.tx';
  35. # Note to maintainers: never ever remove backends from this list.
  36. # the auth => 1 is a crucial protection.
  37. our %routes = (
  38. default => {
  39. callback => \&Trog::Routes::HTML::setup,
  40. },
  41. '/index' => {
  42. method => 'GET',
  43. callback => \&Trog::Routes::HTML::index,
  44. },
  45. #Deal with most indexDocument directives interfering with proxied requests to /
  46. #TODO replace with alias routes
  47. '/index.html' => {
  48. method => 'GET',
  49. callback => \&Trog::Routes::HTML::index,
  50. },
  51. '/index.php' => {
  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. },
  64. '/logout' => {
  65. method => 'GET',
  66. callback => \&Trog::Routes::HTML::logout,
  67. },
  68. '/auth' => {
  69. method => 'POST',
  70. callback => \&Trog::Routes::HTML::login,
  71. },
  72. '/totp' => {
  73. method => 'GET',
  74. auth => 1,
  75. callback => \&Trog::Routes::HTML::totp,
  76. },
  77. '/post/save' => {
  78. method => 'POST',
  79. auth => 1,
  80. callback => \&Trog::Routes::HTML::post_save,
  81. },
  82. '/post/delete' => {
  83. method => 'POST',
  84. auth => 1,
  85. callback => \&Trog::Routes::HTML::post_delete,
  86. },
  87. '/config/save' => {
  88. method => 'POST',
  89. auth => 1,
  90. callback => \&Trog::Routes::HTML::config_save,
  91. },
  92. '/themeclone' => {
  93. method => 'POST',
  94. auth => 1,
  95. callback => \&Trog::Routes::HTML::themeclone,
  96. },
  97. '/profile' => {
  98. method => 'POST',
  99. auth => 1,
  100. callback => \&Trog::Routes::HTML::profile,
  101. },
  102. '/manual' => {
  103. method => 'GET',
  104. auth => 1,
  105. callback => \&Trog::Routes::HTML::manual,
  106. },
  107. '/lib/(.*)' => {
  108. method => 'GET',
  109. auth => 1,
  110. captures => ['module'],
  111. callback => \&Trog::Routes::HTML::manual,
  112. },
  113. #TODO transform into posts?
  114. '/sitemap',
  115. => {
  116. method => 'GET',
  117. callback => \&Trog::Routes::HTML::sitemap,
  118. },
  119. '/sitemap_index.xml',
  120. => {
  121. method => 'GET',
  122. callback => \&Trog::Routes::HTML::sitemap,
  123. data => { xml => 1 },
  124. },
  125. '/sitemap_index.xml.gz',
  126. => {
  127. method => 'GET',
  128. callback => \&Trog::Routes::HTML::sitemap,
  129. data => { xml => 1, compressed => 1 },
  130. },
  131. '/sitemap/static.xml' => {
  132. method => 'GET',
  133. callback => \&Trog::Routes::HTML::sitemap,
  134. data => { xml => 1, map => 'static' },
  135. },
  136. '/sitemap/static.xml.gz' => {
  137. method => 'GET',
  138. callback => \&Trog::Routes::HTML::sitemap,
  139. data => { xml => 1, compressed => 1, map => 'static' },
  140. },
  141. '/sitemap/(.*).xml' => {
  142. method => 'GET',
  143. callback => \&Trog::Routes::HTML::sitemap,
  144. data => { xml => 1 },
  145. captures => ['map'],
  146. },
  147. '/sitemap/(.*).xml.gz' => {
  148. method => 'GET',
  149. callback => \&Trog::Routes::HTML::sitemap,
  150. data => { xml => 1, compressed => 1 },
  151. captures => ['map'],
  152. },
  153. '/robots.txt' => {
  154. method => 'GET',
  155. callback => \&Trog::Routes::HTML::robots,
  156. },
  157. '/humans.txt' => {
  158. method => 'GET',
  159. callback => \&Trog::Routes::HTML::posts,
  160. data => { tag => ['about'] },
  161. },
  162. '/styles/avatars.css' => {
  163. method => 'GET',
  164. callback => \&Trog::Routes::HTML::avatars,
  165. data => { tag => ['about'] },
  166. },
  167. '/favicon.ico' => {
  168. method => 'GET',
  169. callback => \&Trog::Routes::HTML::icon,
  170. },
  171. '/styles/rss-style.xsl' => {
  172. method => 'GET',
  173. callback => \&Trog::Routes::HTML::rss_style,
  174. },
  175. '/rss.xml' => {
  176. method => 'GET',
  177. callback => \&Trog::Routes::HTML::posts,
  178. data => { format => 'rss' },
  179. },
  180. );
  181. # Grab theme routes
  182. my $themed = 0;
  183. if ($Trog::Themes::theme_dir) {
  184. my $theme_mod = "$Trog::Themes::theme_dir/routes.pm";
  185. if ( -f $theme_mod ) {
  186. use lib '.';
  187. require $theme_mod;
  188. @routes{ keys(%Theme::routes) } = values(%Theme::routes);
  189. $themed = 1;
  190. } else {
  191. # Use the special "default" theme
  192. require Theme;
  193. }
  194. }
  195. my $data = Trog::Data->new($conf);
  196. =head1 PRIMARY ROUTE
  197. =head2 index
  198. Implements the primary route used by all pages not behind auth.
  199. Most subsequent functions simply pass content to this function.
  200. =cut
  201. sub index ( $query, $content = '', $i_styles = [] ) {
  202. $query->{theme_dir} = $Trog::Themes::td;
  203. my $to_render = $query->{template} // $landing_page;
  204. $content ||= Trog::Renderer->render( template => $to_render, data => $query, component => 1, contenttype => 'text/html' );
  205. my @styles;
  206. unshift( @styles, qw{embed.css}) if $query->{embed};
  207. unshift( @styles, qw{screen.css structure.css});
  208. push( @styles, @$i_styles );
  209. my @p_styles = qw{print.css};
  210. #TODO allow theming of print css
  211. my @series = _get_series(0);
  212. my $title = $query->{primary_post}{title} // $query->{title} // $Theme::default_title // 'tCMS';
  213. # Handle link "unfurling" correctly
  214. my ( $default_tags, $meta_desc, $meta_tags ) = _build_social_meta( $query, $title );
  215. #Do embed content
  216. my $tmpl = $query->{embed} ? 'embed.tx' : 'index.tx';
  217. $query->{theme_dir} =~ s/^\/www\///;
  218. # TO support theming we have to do things like this rather than with an include directive in the templates.
  219. my $htmltitle = Trog::Renderer->render( template => $htmltitle, data => $query, component => 1, contenttype => 'text/html' );
  220. return $htmltitle if ref $htmltitle eq 'ARRAY';
  221. my $midtitle = Trog::Renderer->render( template => $midtitle, data => $query, component => 1, contenttype => 'text/html' );
  222. return $midtitle if ref $htmltitle eq 'ARRAY';
  223. my $rightbar = Trog::Renderer->render( template => $rightbar, data => $query, component => 1, contenttype => 'text/html' );
  224. return $rightbar if ref $htmltitle eq 'ARRAY';
  225. my $leftbar = Trog::Renderer->render( template => $leftbar, data => $query, component => 1, contenttype => 'text/html' );
  226. return $leftbar if ref $htmltitle eq 'ARRAY';
  227. my $topbar = Trog::Renderer->render( template => $topbar, data => $query, component => 1, contenttype => 'text/html' );
  228. return $topbar if ref $htmltitle eq 'ARRAY';
  229. my $footbar = Trog::Renderer->render( template => $footbar, data => $query, component => 1, contenttype => 'text/html' );
  230. return $footbar if ref $htmltitle eq 'ARRAY';
  231. return finish_render(
  232. $tmpl,
  233. {
  234. %$query,
  235. search_lang => $data->lang(),
  236. search_help => $data->help(),
  237. theme_dir => $Trog::Themes::td,
  238. content => $content,
  239. title => $title,
  240. htmltitle => $htmltitle,
  241. midtitle => $midtitle,
  242. rightbar => $rightbar,
  243. leftbar => $leftbar,
  244. topbar => $topbar,
  245. footbar => $footbar,
  246. categories => \@series,
  247. stylesheets => \@styles,
  248. print_styles => \@p_styles,
  249. show_madeby => $Theme::show_madeby ? 1 : 0,
  250. embed => $query->{embed} ? 1 : 0,
  251. embed_video => $query->{primary_post}{is_video},
  252. default_tags => $default_tags,
  253. meta_desc => $meta_desc,
  254. meta_tags => $meta_tags,
  255. }
  256. );
  257. }
  258. sub _build_social_meta ( $query, $title ) {
  259. return ( undef, undef, undef ) unless $query->{social_meta} && $query->{route} && $query->{domain};
  260. my $default_tags = $Theme::default_tags;
  261. $default_tags .= ',' . join( ',', @{ $query->{primary_post}->{tags} } ) if $default_tags && $query->{primary_post}->{tags};
  262. my $meta_desc = $query->{primary_post}{data} // $Theme::description // "tCMS Site";
  263. $meta_desc = Trog::Utils::strip_and_trunc($meta_desc) || '';
  264. my $meta_tags = '';
  265. my $card_type = 'summary';
  266. $card_type = 'featured_image' if $query->{primary_post} && $query->{primary_post}{is_image};
  267. $card_type = 'player' if $query->{primary_post} && $query->{primary_post}{is_video};
  268. my $image = $Theme::default_image ? "https://$query->{domain}/$Trog::Themes::td/$Theme::default_image" : '';
  269. $image = "https://$query->{domain}/$query->{primary_post}{preview}" if $query->{primary_post} && $query->{primary_post}{preview};
  270. $image = "https://$query->{domain}/$query->{primary_post}{href}" if $query->{primary_post} && $query->{primary_post}{is_image};
  271. my $primary_route = "https://$query->{domain}/$query->{route}";
  272. $primary_route =~ s/[\/]+/\//g;
  273. my $display_name = $Theme::display_name // 'Another tCMS Site';
  274. my $extra_tags = '';
  275. my %sopts = (
  276. site_name => $display_name,
  277. app_name => $display_name,
  278. title => $title,
  279. description => $meta_desc,
  280. url => $primary_route,
  281. );
  282. $sopts{site} = $Theme::twitter_account if $Theme::twitter_account;
  283. $sopts{image} = $image if $image;
  284. $sopts{fb_app_id} = $Theme::fb_app_id if $Theme::fb_app_id;
  285. if ( $query->{primary_post} && $query->{primary_post}{is_video} ) {
  286. #$sopts{player} = "$primary_route?embed=1";
  287. $sopts{player} = "https://$query->{domain}/$query->{primary_post}{href}";
  288. #XXX don't hardcode this
  289. $sopts{player_width} = 1280;
  290. $sopts{player_height} = 720;
  291. $extra_tags .= "<meta property='og:video:type' content='$query->{primary_post}{content_type}' />\n";
  292. }
  293. my $social = HTML::SocialMeta->new(%sopts);
  294. $meta_tags = eval { $social->create($card_type) };
  295. $meta_tags =~ s/content="video"/content="video:other"/mg if $meta_tags;
  296. $meta_tags .= $extra_tags if $extra_tags;
  297. print STDERR "WARNING: Theme misconfigured, social media tags will not be included\n$@\n" if $Trog::Themes::theme_dir && !$meta_tags;
  298. return ( $default_tags, $meta_desc, $meta_tags );
  299. }
  300. =head1 ADMIN ROUTES
  301. These are things that issue returns other than 200, and are not directly accessible by users via any defined route.
  302. =head2 notfound, forbidden, badrequest
  303. Implements the 4XX status codes. Override templates named the same for theming this.
  304. =cut
  305. sub _generic_route ( $rname, $code, $title, $query ) {
  306. $query->{code} = $code;
  307. $query->{route} //= $rname;
  308. $query->{title} = $title;
  309. $query->{template} = "$rname.tx";
  310. INFO("$query->{method} $code $query->{route}");
  311. return Trog::Routes::HTML::index( $query );
  312. }
  313. sub notfound (@args) {
  314. return _generic_route( 'notfound', 404, "Return to sender, Address unknown", @args );
  315. }
  316. sub forbidden (@args) {
  317. return _generic_route( 'forbidden', 403, "STAY OUT YOU RED MENACE", @args );
  318. }
  319. sub badrequest (@args) {
  320. return _generic_route( 'badrequest', 400, "Bad Request", @args );
  321. }
  322. sub toolong (@args) {
  323. return _generic_route( 'toolong', 419, "URI too long", @args );
  324. }
  325. =head2 redirect, redirect_permanent, see_also
  326. Redirects to the provided page.
  327. =cut
  328. sub redirect ($to) {
  329. INFO("redirect: $to");
  330. return [ 302, [ "Location" => $to ], [''] ];
  331. }
  332. sub redirect_permanent ($to) {
  333. INFO("permanent redirect: $to");
  334. return [ 301, [ "Location" => $to ], [''] ];
  335. }
  336. sub see_also ($to) {
  337. INFO("see also: $to");
  338. return [ 303, [ "Location" => $to ], [''] ];
  339. }
  340. =head1 NORMAL ROUTES
  341. These are expected to either return a 200, or redirect to something which does.
  342. =head2 robots
  343. Return an appropriate robots.txt
  344. =cut
  345. sub robots ($query) {
  346. state $etag = "robots-" . time();
  347. return Trog::Renderer->render(
  348. contenttype => 'text/plain',
  349. template => 'robots.tx',
  350. data => {
  351. etag => $etag,
  352. %$query,
  353. },
  354. code => 200,
  355. );
  356. }
  357. =head2 setup
  358. One time setup page; should only display to the first user to visit the site which we presume to be the administrator.
  359. =cut
  360. sub setup ($query) {
  361. File::Touch::touch("config/setup");
  362. Trog::Renderer->render(
  363. template => 'notconfigured.tx',
  364. data => {
  365. title => 'tCMS Requires Setup to Continue...',
  366. stylesheets => _build_themed_styles(['notconfigured.css']),
  367. %$query,
  368. },
  369. contenttype => 'text/html',
  370. code => 200,
  371. );
  372. }
  373. =head2 totp
  374. Enable 2 factor auth via TOTP for the currently authenticated user.
  375. Returns a page with a QR code & TOTP uri for pasting into your authenticator app of choice.
  376. =cut
  377. sub totp ($query) {
  378. my $active_user = $query->{user};
  379. my $domain = $query->{domain};
  380. $query->{failure} //= -1;
  381. my ( $uri, $qr, $failure, $message ) = Trog::Auth::totp( $active_user, $domain );
  382. return Trog::Routes::HTML::index(
  383. {
  384. title => 'Enable TOTP 2-Factor Auth',
  385. theme_dir => $Trog::Themes::td,
  386. uri => $uri,
  387. qr => $qr,
  388. failure => $failure,
  389. message => $message,
  390. template => 'totp.tx',
  391. is_admin => 1,
  392. %$query,
  393. },
  394. undef,
  395. [qw{post.css}],
  396. );
  397. }
  398. =head2 login
  399. 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.
  400. =cut
  401. sub login ($query) {
  402. # Redirect if we actually have a logged in user.
  403. # Note to future me -- this user value is overwritten explicitly in server.psgi.
  404. # If that ever changes, you will die
  405. $query->{to} //= $query->{route};
  406. $query->{to} = '/config' if List::Util::any { $query->{to} eq $_ } qw{/login /logout};
  407. if ( $query->{user} ) {
  408. DEBUG("Login by $query->{user}, redirecting to $query->{to}");
  409. return see_also( $query->{to} );
  410. }
  411. #Check and see if we have no users. If so we will just accept whatever creds are passed.
  412. my $hasusers = -f "config/has_users";
  413. my $btnmsg = $hasusers ? "Log In" : "Register";
  414. my $headers;
  415. my $has_totp = 0;
  416. if ( $query->{username} && $query->{password} ) {
  417. if ( !$hasusers ) {
  418. # Make the first user
  419. Trog::Auth::useradd( $query->{username}, $query->{password}, ['admin'] );
  420. # Add a stub user page and the initial series.
  421. my $dat = Trog::Data->new($conf);
  422. _setup_initial_db( $dat, $query->{username} );
  423. # Ensure we stop registering new users
  424. File::Touch::touch("config/has_users");
  425. }
  426. $query->{failed} = 1;
  427. my $cookie = Trog::Auth::mksession( $query->{username}, $query->{password}, $query->{token} );
  428. if ($cookie) {
  429. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  430. my $secure = '';
  431. $secure = '; Secure' if $query->{scheme} eq 'https';
  432. $headers = {
  433. "Set-Cookie" => "tcmslogin=$cookie; HttpOnly; SameSite=Strict$secure",
  434. };
  435. $query->{failed} = 0;
  436. }
  437. }
  438. $query->{failed} //= -1;
  439. return Trog::Renderer->render(
  440. template => 'login.tx',
  441. data => {
  442. title => 'tCMS 2 ~ Login',
  443. to => $query->{to},
  444. failure => int( $query->{failed} ),
  445. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  446. btnmsg => $btnmsg,
  447. stylesheets => _build_themed_styles([qw{login.css}]),
  448. theme_dir => $Trog::Themes::td,
  449. has_users => $hasusers,
  450. %$query,
  451. },
  452. headers => $headers,
  453. contenttype => 'text/html',
  454. code => 200,
  455. );
  456. }
  457. sub _setup_initial_db ( $dat, $user ) {
  458. $dat->add(
  459. {
  460. "aclname" => "series",
  461. "acls" => [],
  462. "callback" => "Trog::Routes::HTML::series",
  463. method => 'GET',
  464. "data" => "Series",
  465. "href" => "/series",
  466. "local_href" => "/series",
  467. "preview" => "/img/sys/testpattern.jpg",
  468. "tags" => [qw{series topbar}],
  469. visibility => 'public',
  470. "title" => "Series",
  471. user => $user,
  472. form => 'series.tx',
  473. child_form => 'series.tx',
  474. aliases => [],
  475. },
  476. {
  477. "aclname" => "about",
  478. "acls" => [],
  479. "callback" => "Trog::Routes::HTML::series",
  480. method => 'GET',
  481. "data" => "About",
  482. "href" => "/about",
  483. "local_href" => "/about",
  484. "preview" => "/img/sys/testpattern.jpg",
  485. "tags" => [qw{series topbar public}],
  486. visibility => 'public',
  487. "title" => "About",
  488. user => $user,
  489. form => 'series.tx',
  490. child_form => 'profile.tx',
  491. aliases => [],
  492. },
  493. {
  494. "aclname" => "config",
  495. acls => [],
  496. "callback" => "Trog::Routes::HTML::config",
  497. 'method' => 'GET',
  498. "content_type" => "text/html",
  499. "data" => "Config",
  500. "href" => "/config",
  501. "local_href" => "/config",
  502. "preview" => "/img/sys/testpattern.jpg",
  503. "tags" => [qw{admin}],
  504. visibility => 'private',
  505. "title" => "Configure tCMS",
  506. user => $user,
  507. aliases => [],
  508. },
  509. {
  510. title => $user,
  511. data => 'Default user',
  512. preview => '/img/avatar/humm.gif',
  513. wallpaper => '/img/sys/testpattern.jpg',
  514. tags => ['about'],
  515. visibility => 'public',
  516. acls => ['admin'],
  517. local_href => "/users/$user",
  518. callback => "Trog::Routes::HTML::users",
  519. method => 'GET',
  520. user => $user,
  521. form => 'profile.tx',
  522. aliases => [],
  523. },
  524. );
  525. }
  526. =head2 logout
  527. Deletes your users' session and opens the index.
  528. =cut
  529. sub logout ($query) {
  530. Trog::Auth::killsession( $query->{user} ) if $query->{user};
  531. delete $query->{user};
  532. return Trog::Routes::HTML::index($query);
  533. }
  534. =head2 config
  535. Renders the configuration page, or redirects you back to the login page.
  536. =cut
  537. sub config ($query) {
  538. return see_also('/login') unless $query->{user};
  539. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  540. $query->{failure} //= -1;
  541. return Trog::Routes::HTML::index(
  542. {
  543. title => 'Configure tCMS',
  544. theme_dir => $Trog::Themes::td,
  545. stylesheets => [qw{config.css}],
  546. scripts => [qw{post.js}],
  547. themes => _get_themes() || [],
  548. data_models => _get_data_models(),
  549. current_theme => $conf->param('general.theme') // '',
  550. current_data_model => $conf->param('general.data_model') // 'DUMMY',
  551. totp_secret => $conf->param('totp.secret'),
  552. message => $query->{message},
  553. failure => $query->{failure},
  554. to => '/config',
  555. scheme => $query->{scheme},
  556. embeds => $conf->param('security.allow_embeds_from') // '',
  557. is_admin => 1,
  558. template => 'config.tx',
  559. %$query,
  560. },
  561. undef,
  562. [qw{config.css}],
  563. );
  564. }
  565. sub _get_series ( $edit = 0 ) {
  566. my @series = $data->get(
  567. acls => [qw{public}],
  568. tags => [qw{topbar}],
  569. limit => 10,
  570. page => 1,
  571. );
  572. @series = map { $_->{local_href} = "/post$_->{local_href}"; $_ } @series if $edit;
  573. return @series;
  574. }
  575. sub _get_themes {
  576. my $dir = 'www/themes';
  577. opendir( my $dh, $dir ) || do { die "Can't opendir $dir: $!" unless $!{ENOENT} };
  578. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  579. closedir $dh;
  580. return \@tdirs;
  581. }
  582. sub _get_data_models {
  583. my $dir = 'lib/Trog/Data';
  584. opendir( my $dh, $dir ) || die "Can't opendir $dir: $!";
  585. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  586. closedir $dh;
  587. return \@dmods;
  588. }
  589. =head2 config_save
  590. Implements /config/save route. Saves what little configuration we actually use to ~/.tcms/tcms.conf
  591. =cut
  592. sub config_save ($query) {
  593. return see_also('/login') unless $query->{user};
  594. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  595. $conf->param( 'general.theme', $query->{theme} ) if defined $query->{theme};
  596. $conf->param( 'general.data_model', $query->{data_model} ) if $query->{data_model};
  597. # Erase all TOTP secrets in the event we change the global secret
  598. if ( $query->{totp_secret} ) {
  599. $conf->param( 'totp.secret', $query->{totp_secret} );
  600. Trog::Auth::clear_totp();
  601. }
  602. $query->{failure} = 1;
  603. $query->{message} = "Failed to save configuration!";
  604. if ( $conf->write($Trog::Config::home_cfg) ) {
  605. $query->{failure} = 0;
  606. $query->{message} = "Configuration updated succesfully.";
  607. }
  608. #Get the PID of the parent port using lsof, send HUP
  609. my $parent = getppid;
  610. kill 'HUP', $parent;
  611. return config($query);
  612. }
  613. =head2 themeclone
  614. Clone a theme by copying a directory.
  615. =cut
  616. sub themeclone ($query) {
  617. return see_also('/login') unless $query->{user};
  618. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  619. my ( $theme, $newtheme ) = ( $query->{theme}, $query->{newtheme} );
  620. my $themedir = 'www/themes';
  621. $query->{failure} = 1;
  622. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  623. require File::Copy::Recursive;
  624. if ( $theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" ) ) {
  625. $query->{failure} = 0;
  626. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  627. }
  628. return see_also('/config');
  629. }
  630. =head2 post_save
  631. Saves posts submitted via the /post pages
  632. =cut
  633. sub post_save ($query) {
  634. return see_also('/login') unless $query->{user};
  635. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  636. my $to = delete $query->{to};
  637. #Copy this down since it will be deleted later
  638. my $acls = $query->{acls};
  639. $query->{tags} = Trog::Utils::coerce_array( $query->{tags} );
  640. # Filter bits and bobs
  641. delete $query->{primary_post};
  642. delete $query->{social_meta};
  643. delete $query->{deflate};
  644. delete $query->{acls};
  645. # Ensure there are no null tags
  646. @{ $query->{tags} } = grep { defined $_ } @{ $query->{tags} };
  647. # Posts will always be GET
  648. $query->{method} = 'GET';
  649. $data->add($query) and die "Could not add post";
  650. return see_also($to);
  651. }
  652. =head2 profile
  653. Saves / updates new users.
  654. =cut
  655. sub profile ($query) {
  656. return see_also('/login') unless $query->{user};
  657. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  658. #TODO allow users to do something OTHER than be admins
  659. if ( $query->{password} ) {
  660. Trog::Auth::useradd( $query->{username}, $query->{password}, ['admin'] );
  661. }
  662. #Make sure it is "self-authored", redact pw
  663. $query->{user} = delete $query->{username};
  664. delete $query->{password};
  665. return post_save($query);
  666. }
  667. =head2 post_delete
  668. deletes posts.
  669. =cut
  670. sub post_delete ($query) {
  671. return see_also('/login') unless $query->{user};
  672. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  673. $data->delete($query) and die "Could not delete post";
  674. return see_also( $query->{to} );
  675. }
  676. =head2 series
  677. Series specific view, much like the users/ route
  678. Displays identified series, not all series.
  679. =cut
  680. sub series ($query) {
  681. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  682. #we are either viewed one of two ways, /post/$id or /$aclname
  683. my ( undef, $aclname, $id ) = split( /\//, $query->{route} );
  684. $query->{aclname} = $aclname if !$id;
  685. $query->{id} = $id if $id;
  686. # Don't show topbar series on the series page. That said, don't exclude it from direct series view.
  687. $query->{exclude_tags} = ['topbar'] if !$is_admin && $aclname && $aclname eq 'series';
  688. #XXX I'd prefer to overload id to actually *be* the aclname...
  689. # but this way, accomodates things like the flat file time-indexing hack.
  690. # TODO I should probably have it for all posts, and make *everything* a series.
  691. # WE can then do threaded comments/posts.
  692. # That will essentially necessitate it *becoming* the ID for real.
  693. #Grab the relevant tag (aclname), then pass that to posts
  694. my @posts = _post_helper( $query, ['series'], $query->{user_acls} );
  695. delete $query->{id};
  696. delete $query->{aclname};
  697. $query->{subhead} = $posts[0]->{data};
  698. $query->{title} = $posts[0]->{title};
  699. $query->{tag} = $posts[0]->{aclname};
  700. $query->{primary_post} = $posts[0];
  701. $query->{in_series} = 1;
  702. return posts($query);
  703. }
  704. =head2 avatars
  705. Returns the avatars.css.
  706. =cut
  707. sub avatars ($query) {
  708. push( @{ $query->{user_acls} }, 'public' );
  709. my $tags = Trog::Utils::coerce_array( $query->{tag} );
  710. my @posts = _post_helper( $query, $tags, $query->{user_acls} );
  711. if (@posts) {
  712. # Set the eTag so that we don't get a re-fetch
  713. $query->{etag} = "$posts[0]{id}-$posts[0]{version}";
  714. }
  715. return Trog::Renderer->render(
  716. template => 'avatars.tx',
  717. data => {
  718. users => \@posts,
  719. %$query,
  720. },
  721. code => 200,
  722. contenttype => 'text/css',
  723. );
  724. }
  725. =head2 users
  726. Implements direct user profile view.
  727. =cut
  728. sub users ($query) {
  729. # Capture the username
  730. my ( undef, undef, $username ) = split( /\//, $query->{route} );
  731. $query->{username} //= $username;
  732. push( @{ $query->{user_acls} }, 'public' );
  733. $query->{exclude_tags} = ['about'];
  734. # Don't show topbar series on the series page. That said, don't exclude it from direct series view.
  735. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  736. push( @{ $query->{exclude_tags} }, 'topbar' ) if !$is_admin;
  737. my @posts = _post_helper( { author => $query->{username} }, ['about'], $query->{user_acls} );
  738. $query->{id} = $posts[0]->{id};
  739. $query->{title} = $posts[0]->{title};
  740. $query->{user_obj} = $posts[0];
  741. $query->{primary_post} = $posts[0];
  742. $query->{in_series} = 1;
  743. return posts($query);
  744. }
  745. =head2 posts
  746. Display multi or single posts, supports RSS and pagination.
  747. =cut
  748. sub posts ( $query, $direct = 0 ) {
  749. # Allow rss.xml to tell what posts to loop over
  750. my $fmt = $query->{format} || '';
  751. my $for = URI->new($query->{for} || '')->path() || $query->{route};
  752. $query->{route} = $for if $fmt eq 'rss';
  753. #Process the input URI to capture tag/id
  754. $query->{route} //= $query->{to};
  755. my ( undef, undef, $id ) = split( /\//, $query->{route} );
  756. my $tags = Trog::Utils::coerce_array( $query->{tag} );
  757. $query->{id} = $id if $id && !$query->{in_series};
  758. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  759. push( @{ $query->{user_acls} }, 'public' );
  760. push( @{ $query->{user_acls} }, 'unlisted' ) if $query->{id};
  761. push( @{ $query->{user_acls} }, 'private' ) if $is_admin;
  762. my @posts;
  763. # Discover this user's visibility, so we can make them post in this category by default
  764. my $user_visibility = 'public';
  765. if ( $query->{user_obj} ) {
  766. #Optimize the /users/* route
  767. @posts = ( $query->{user_obj} );
  768. $user_visibility = $query->{user_obj}->{visibility};
  769. }
  770. else {
  771. if ( $query->{user} ) {
  772. my @me = _post_helper( { author => $query->{user} }, ['about'], $query->{user_acls} );
  773. $user_visibility = $me[0]->{visibility};
  774. }
  775. @posts = _post_helper( $query, $tags, $query->{user_acls} );
  776. }
  777. if ( $query->{id} ) {
  778. $query->{primary_post} = $posts[0] if @posts;
  779. }
  780. #OK, so if we have a user as the ID we found, go grab the rest of their posts
  781. if ( $query->{id} && @posts && List::Util::any { $_ eq 'about' } @{ $posts[0]->{tags} } ) {
  782. my $user = shift(@posts);
  783. my $id = delete $query->{id};
  784. $query->{author} = $user->{user};
  785. @posts = _post_helper( $query, $tags, $query->{user_acls} );
  786. @posts = grep { $_->{id} ne $id } @posts;
  787. unshift @posts, $user;
  788. }
  789. if ( !$is_admin ) {
  790. return notfound($query) unless @posts;
  791. }
  792. # Set the eTag so that we don't get a re-fetch
  793. $query->{etag} = "$posts[0]{id}-$posts[0]{version}" if @posts;
  794. #Correct page headers
  795. my $ph = $themed ? _themed_title( $query->{route} ) : $query->{route};
  796. return _rss( $query, $ph, \@posts ) if $fmt eq 'rss';
  797. #XXX Is used by the sitemap, maybe just fix there?
  798. my @post_aliases = map { $_->{local_href} } _get_series();
  799. # Allow themes to put in custom headers/footers on posts
  800. my ( $header, $footer );
  801. $header = Trog::Renderer->render(
  802. template => 'headers/' . $query->{primary_post}{header},
  803. data => { theme_dir => $Trog::Themes::td, %$query },
  804. component => 1,
  805. contenttype => 'text/html',
  806. ) if $query->{primary_post}{header};
  807. return $header if ref $header eq 'ARRAY';
  808. $footer = Trog::Renderer->render(
  809. template => 'footers/' . $query->{primary_post}{footer},
  810. data => { theme_dir => $Trog::Themes::td, %$query },
  811. component => 1,
  812. contenttype => 'text/html',
  813. ) if $query->{primary_post}{footer};
  814. return $header if ref $footer eq 'ARRAY';
  815. # List the available headers/footers
  816. my $headers = Trog::Themes::templates_in_dir( "headers", 'text/html', 1 );
  817. my $footers = Trog::Themes::templates_in_dir( "footers", 'text/html', 1 );
  818. #XXX used to be post.css, but probably not good anymore?
  819. my $styles = [];
  820. # Build page title if it wasn't set by a wrapping sub
  821. $query->{title} = "$query->{domain} : $query->{title}" if $query->{title} && $query->{domain};
  822. $query->{title} ||= @$tags && $query->{domain} ? "$query->{domain} : @$tags" : undef;
  823. #Handle paginator vars
  824. my $limit = int( $query->{limit} || 25 );
  825. my $now_year = ( localtime(time) )[5] + 1900;
  826. my $oldest_year = $now_year - 20; #XXX actually find oldest post year
  827. # Handle post style.
  828. if ( $query->{style} ) {
  829. undef $header;
  830. undef $footer;
  831. }
  832. my $older = !@posts ? 0 : $posts[-1]->{created};
  833. $query->{failure} //= -1;
  834. $query->{id} //= '';
  835. my $newer = !@posts ? 0 : $posts[0]->{created};
  836. #XXX messed up data has to be fixed unfortunately
  837. @$tags = List::Util::uniq @$tags;
  838. #Filter displaying visibility tags
  839. my @visibuddies = qw{public unlisted private};
  840. foreach my $post (@posts) {
  841. @{ $post->{tags} } = grep {
  842. my $tag = $_;
  843. !grep { $tag eq $_ } @visibuddies
  844. } @{ $post->{tags} };
  845. }
  846. #XXX note that we are explicitly relying on the first tag to be the ACL
  847. my $aclselected = $tags->[0] || '';
  848. my @acls = map {
  849. $_->{selected} = $_->{aclname} eq $aclselected ? 'selected' : '';
  850. $_
  851. } _post_helper( {}, ['series'], $query->{user_acls} );
  852. my $forms = Trog::Themes::templates_in_dir("forms", 'text/html', 1);
  853. my $edittype = $query->{primary_post} ? $query->{primary_post}->{child_form} : $query->{form};
  854. my $tiled = $query->{primary_post} ? !$is_admin && $query->{primary_post}->{tiled} : 0;
  855. # Grab the rest of the tags to dump into the edit form
  856. my @tags_all = $data->tags();
  857. #Filter out the visibilities and special series tags
  858. @tags_all = grep {
  859. my $subj = $_;
  860. scalar( grep { $_ eq $subj } qw{public private unlisted admin series about topbar} ) == 0
  861. } @tags_all;
  862. @posts = map {
  863. my $subject = $_;
  864. my @et = grep {
  865. my $subj = $_;
  866. grep { $subj eq $_ } @tags_all
  867. } @{ $subject->{tags} };
  868. @et = grep { $_ ne $aclselected } @et;
  869. $_->{extra_tags} = \@et;
  870. $_
  871. } @posts;
  872. my @et = List::MoreUtils::singleton( @$tags, @tags_all );
  873. $query->{author} = $query->{primary_post}{user} // $posts[0]{user};
  874. my $picker = Trog::Component::EmojiPicker::render();
  875. return $picker if ref $picker eq 'ARRAY';
  876. #XXX the only reason this is needed is due to direct=1
  877. #XXX is this even used?
  878. my $content = Trog::Renderer->render(
  879. template => 'posts.tx',
  880. data => {
  881. acls => \@acls,
  882. can_edit => $is_admin,
  883. forms => $forms,
  884. post => { tags => $tags, extra_tags => \@et, form => $edittype, visibility => $user_visibility, addpost => 1 },
  885. post_visibilities => \@visibuddies,
  886. failure => $query->{failure},
  887. to => $query->{to},
  888. message => $query->{failure} ? "Failed to add post!" : "Successfully added Post as $query->{id}",
  889. direct => $direct,
  890. title => $query->{title},
  891. author => $query->{primary_post}{user} // $posts[0]{user},
  892. style => $query->{style},
  893. posts => \@posts,
  894. like => $query->{like},
  895. in_series => exists $query->{in_series} || !!( $query->{route} =~ m/^\/series\// ),
  896. route => $query->{route},
  897. limit => $limit,
  898. pages => scalar(@posts) == $limit,
  899. older => $older,
  900. newer => $newer,
  901. sizes => [ 25, 50, 100 ],
  902. rss => !$query->{id} && !$query->{older},
  903. tiled => $tiled,
  904. category => $ph,
  905. subhead => $query->{subhead},
  906. header => $header,
  907. footer => $footer,
  908. headers => $headers,
  909. footers => $footers,
  910. years => [ reverse( $oldest_year .. $now_year ) ],
  911. months => [ 0 .. 11 ],
  912. emoji_picker => $picker,
  913. },
  914. contenttype => 'text/html',
  915. component => 1,
  916. );
  917. # Something exploded
  918. return $content if ref $content eq "ARRAY";
  919. return $content if $direct;
  920. return Trog::Routes::HTML::index( $query, $content, $styles );
  921. }
  922. sub _themed_title ($path) {
  923. return $path unless %Theme::paths;
  924. return $Theme::paths{$path} ? $Theme::paths{$path} : $path;
  925. }
  926. sub _post_helper ( $query, $tags, $acls ) {
  927. return $data->get(
  928. older => $query->{older},
  929. newer => $query->{newer},
  930. page => int( $query->{page} || 1 ),
  931. limit => int( $query->{limit} || 25 ),
  932. tags => $tags,
  933. exclude_tags => $query->{exclude_tags},
  934. acls => $acls,
  935. aclname => $query->{aclname},
  936. like => $query->{like},
  937. author => $query->{author},
  938. id => $query->{id},
  939. version => $query->{version},
  940. );
  941. }
  942. =head2 sitemap
  943. Return the sitemap index unless the static or a set of dynamic routes is requested.
  944. We have a maximum of 99,990,000 posts we can make under this model
  945. As we have 10,000 * 10,000 posts which are indexable via the sitemap format.
  946. 1 top level index slot (10k posts) is taken by our static routes, the rest will be /posts.
  947. Passing ?xml=1 will result in an appropriate sitemap.xml instead.
  948. This is used to generate the static sitemaps as expected by search engines.
  949. Passing compressed=1 will gzip the output.
  950. =cut
  951. sub sitemap ($query) {
  952. state $etag = "sitemap-" . time();
  953. my ( @to_map, $is_index, $route_type );
  954. my $warning = '';
  955. $query->{map} //= '';
  956. if ( $query->{map} eq 'static' ) {
  957. # Return the map of static routes
  958. $route_type = 'Static Routes';
  959. @to_map = grep { !defined $routes{$_}->{captures} && $_ !~ m/^default|login|auth$/ && !$routes{$_}->{auth} } keys(%routes);
  960. }
  961. elsif ( !$query->{map} ) {
  962. # Return the index instead
  963. @to_map = ('static');
  964. my $tot = $data->count();
  965. my $size = 50000;
  966. my $pages = int( $tot / $size ) + ( ( $tot % $size ) ? 1 : 0 );
  967. # Truncate pages at 10k due to standard
  968. my $clamped = $pages > 49999 ? 49999 : $pages;
  969. $warning = "More posts than possible to represent in sitemaps & index! Old posts have been truncated." if $pages > 49999;
  970. foreach my $page ( $clamped .. 1 ) {
  971. push( @to_map, "$page" );
  972. }
  973. $is_index = 1;
  974. }
  975. else {
  976. $route_type = "Posts: Page $query->{map}";
  977. # Return the map of the particular range of dynamic posts
  978. $query->{limit} = 50000;
  979. $query->{page} = $query->{map};
  980. @to_map = _post_helper( $query, [], ['public'] );
  981. }
  982. if ( $query->{xml} ) {
  983. DEBUG("RENDER SITEMAP XML");
  984. my $sm;
  985. my $xml_date = time();
  986. my $fmt = "xml";
  987. $fmt .= ".gz" if $query->{compressed};
  988. if ( !$query->{map} ) {
  989. require WWW::SitemapIndex::XML;
  990. $sm = WWW::SitemapIndex::XML->new();
  991. foreach my $url (@to_map) {
  992. $sm->add(
  993. loc => "http://$query->{domain}/sitemap/$url.$fmt",
  994. lastmod => $xml_date,
  995. );
  996. }
  997. }
  998. else {
  999. require WWW::Sitemap::XML;
  1000. $sm = WWW::Sitemap::XML->new();
  1001. my $changefreq = $query->{map} eq 'static' ? 'monthly' : 'daily';
  1002. foreach my $url (@to_map) {
  1003. my $true_uri = "http://$query->{domain}$url";
  1004. if ( ref $url eq 'HASH' ) {
  1005. my $is_user_page = grep { $_ eq 'about' } @{ $url->{tags} };
  1006. $true_uri = "http://$query->{domain}/posts/$url->{id}";
  1007. $true_uri = "http://$query->{domain}/users/$url->{title}" if $is_user_page;
  1008. }
  1009. my %out = (
  1010. loc => $true_uri,
  1011. lastmod => $xml_date,
  1012. mobile => 1,
  1013. changefreq => $changefreq,
  1014. priority => 1.0,
  1015. );
  1016. if ( ref $url eq 'HASH' ) {
  1017. #add video & preview image if applicable
  1018. $out{images} = [
  1019. {
  1020. loc => "http://$query->{domain}$url->{href}",
  1021. caption => $url->{data},
  1022. title => substr( $url->{title}, 0, 100 ),
  1023. }
  1024. ]
  1025. if $url->{is_image};
  1026. # Truncate descriptions
  1027. my $desc = substr( $url->{data}, 0, 2048 ) || '';
  1028. my $href = $url->{href} || '';
  1029. my $preview = $url->{preview} || '';
  1030. my $domain = $query->{domain} || '';
  1031. $out{videos} = [
  1032. {
  1033. content_loc => "http://$domain$href",
  1034. thumbnail_loc => "http://$domain$preview",
  1035. title => substr( $url->{title}, 0, 100 ) || '',
  1036. description => $desc,
  1037. }
  1038. ]
  1039. if $url->{is_video};
  1040. }
  1041. $sm->add(%out);
  1042. }
  1043. }
  1044. my $xml = $sm->as_xml();
  1045. require IO::String;
  1046. my $buf = IO::String->new();
  1047. my $ct = 'application/xml';
  1048. $xml->toFH( $buf, 0 );
  1049. seek $buf, 0, 0;
  1050. if ( $query->{compressed} ) {
  1051. require IO::Compress::Gzip;
  1052. my $compressed = IO::String->new();
  1053. IO::Compress::Gzip::gzip( $buf => $compressed );
  1054. $ct = 'application/gzip';
  1055. $buf = $compressed;
  1056. seek $compressed, 0, 0;
  1057. }
  1058. #XXX This is one of the few exceptions where we don't use finish_render, as it *requires* gzip.
  1059. return [ 200, [ "Content-type" => $ct, 'ETag' => $etag ], $buf ];
  1060. }
  1061. @to_map = sort @to_map unless $is_index;
  1062. my $styles = ['sitemap.css'];
  1063. $query->{title} = "$query->{domain} : Sitemap";
  1064. $query->{template} = 'sitemap.tx',
  1065. $query->{to_map} = \@to_map,
  1066. $query->{is_index} = $is_index,
  1067. $query->{route_type} = $route_type,
  1068. $query->{etag} = $etag;
  1069. return Trog::Routes::HTML::index( $query, undef, $styles );
  1070. }
  1071. sub _rss ( $query, $subtitle, $posts ) {
  1072. require XML::RSS;
  1073. my $rss = XML::RSS->new( version => '2.0', stylesheet => '/styles/rss-style.xsl' );
  1074. my $now = DateTime->from_epoch( epoch => time() );
  1075. $rss->channel(
  1076. title => "$query->{domain}",
  1077. subtitle => $subtitle,
  1078. link => "http://$query->{domain}/$query->{route}.rss.xml",
  1079. language => 'en', #TODO localization
  1080. description => "$query->{domain} : $query->{route}",
  1081. pubDate => $now,
  1082. lastBuildDate => $now,
  1083. );
  1084. $rss->image(
  1085. title => $query->{domain},
  1086. url => "/favicon.ico",
  1087. link => "http://$query->{domain}",
  1088. width => 32,
  1089. height => 32,
  1090. description => "$query->{domain} favicon",
  1091. );
  1092. foreach my $post (@$posts) {
  1093. my $url = "http://$query->{domain}$post->{local_href}";
  1094. _post2rss( $rss, $url, $post );
  1095. next unless ref $post->{aliases} eq 'ARRAY';
  1096. foreach my $alias ( @{ $post->{aliases} } ) {
  1097. $url = "http://$query->{domain}$alias";
  1098. _post2rss( $rss, $url, $post );
  1099. }
  1100. }
  1101. return Trog::Renderer->render(
  1102. template => 'raw.tx',
  1103. data => {
  1104. etag => $query->{etag},
  1105. body => encode_utf8( $rss->as_string ),
  1106. scheme => $query->{scheme},
  1107. },
  1108. headers => { 'Content-Disposition' => 'inline; filename="rss.xml"' },
  1109. #XXX if you do the "proper" content-type of application/rss+xml, browsers download rather than display.
  1110. contenttype => "text/xml",
  1111. code => 200,
  1112. );
  1113. }
  1114. sub _post2rss ( $rss, $url, $post ) {
  1115. $rss->add_item(
  1116. title => $post->{title},
  1117. permaLink => $url,
  1118. link => $url,
  1119. enclosure => { url => $url, type => "text/html" },
  1120. description => "<![CDATA[$post->{data}]]>",
  1121. pubDate => DateTime->from_epoch( epoch => $post->{created} ), #TODO format like Thu, 23 Aug 1999 07:00:00 GMT
  1122. author => $post->{user}, #TODO translate to "email (user)" format
  1123. );
  1124. }
  1125. =head2 manual
  1126. Implements the /manual and /lib/* routes.
  1127. Basically a thin wrapper around Pod::Html.
  1128. =cut
  1129. sub manual ($query) {
  1130. return see_also('/login') unless $query->{user};
  1131. return Trog::Routes::HTML::forbidden($query) unless grep { $_ eq 'admin' } @{ $query->{user_acls} };
  1132. require Pod::Html;
  1133. require Capture::Tiny;
  1134. #Fix links from Pod::HTML
  1135. $query->{module} =~ s/\.html$//g if $query->{module};
  1136. $query->{failure} //= -1;
  1137. my $infile = $query->{module} ? "$query->{module}.pm" : 'tCMS/Manual.pod';
  1138. return notfound($query) unless -f "lib/$infile";
  1139. my $content = capture { Pod::Html::pod2html( qw{--podpath=lib --podroot=.}, "--infile=lib/$infile" ) };
  1140. return Trog::Routes::HTML::index(
  1141. {
  1142. title => 'tCMS Manual',
  1143. theme_dir => $Trog::Themes::td,
  1144. content => $content,
  1145. template => 'manual.tx',
  1146. is_admin => 1,
  1147. %$query,
  1148. },
  1149. undef,
  1150. ['post.css'],
  1151. );
  1152. }
  1153. # basically a file rewrite rule for themes
  1154. sub icon ($query) {
  1155. my $path = $query->{route};
  1156. return Trog::FileHandler::serve(Trog::Themes::themed("img/icon/$path"));
  1157. }
  1158. # TODO make statics, abstract gzipped outputting & header handling
  1159. sub rss_style ($query) {
  1160. $query->{port} = ":$query->{port}" if $query->{port};
  1161. $query->{title} = qq{<xsl:value-of select="rss/channel/title"/>};
  1162. $query->{no_doctype} = 1;
  1163. # Due to this being html rather than XML, we can't use an include directive.
  1164. $query->{header} = Trog::Renderer->render( template => 'header.tx', data => $query, contenttype => 'text/html', component => 1 );
  1165. $query->{footer} = Trog::Renderer->render( template => 'footer.tx', data => $query, contenttype => 'text/html', component => 1 );
  1166. return Trog::Renderer->render(
  1167. template => 'rss-style.tx',
  1168. contenttype => 'text/xsl',
  1169. data => $query,
  1170. code => 200,
  1171. );
  1172. }
  1173. sub _build_themed_styles ($styles) {
  1174. my @styles = map { Trog::Themes::themed_style("$_") } @{Trog::Utils::coerce_array($styles)};
  1175. return \@styles;
  1176. }
  1177. sub _build_themed_scripts ($scripts) {
  1178. my @scripts = map { Trog::Themes::themed_script("$_") } @{Trog::Utils::coerce_array($scripts)};
  1179. return \@scripts;
  1180. }
  1181. sub finish_render ( $template, $vars, %headers ) {
  1182. #XXX default vars that need to be pulled from config
  1183. $vars->{lang} //= 'en-US';
  1184. $vars->{title} //= 'tCMS';
  1185. $vars->{stylesheets} //= [];
  1186. $vars->{scripts} //= [];
  1187. # Theme-ize the paths
  1188. $vars->{stylesheets} = [map { s/^www\///; $_ } grep { -f $_ } @{_build_themed_styles($vars->{stylesheets})}];
  1189. $vars->{print_styles} = [map { s/^www\///; $_ } grep { -f $_ } @{_build_themed_styles($vars->{p_styles})}];
  1190. $vars->{scripts} = [map { s/^www\///; $_ } grep { -f $_ } @{_build_themed_scripts($vars->{scripts})}];
  1191. # Add in avatars.css, it's special
  1192. push(@{$vars->{stylesheets}},"/styles/avatars.css");
  1193. # Absolute-ize the paths for scripts & stylesheets
  1194. @{ $vars->{stylesheets} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{stylesheets} };
  1195. @{ $vars->{print_styles} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{print_styles} };
  1196. @{ $vars->{scripts} } = map { CORE::index( $_, '/' ) == 0 ? $_ : "/$_" } @{ $vars->{scripts} };
  1197. # TODO Smash together the stylesheets and minify
  1198. $vars->{contenttype} //= $Trog::Vars::content_types{html};
  1199. $vars->{cachecontrol} //= $Trog::Vars::cache_control{revalidate};
  1200. $vars->{code} ||= 200;
  1201. $vars->{theme_dir} =~ s/^\/www\/// if $vars->{theme_dir};
  1202. $vars->{header} = Trog::Renderer->render( template => 'header.tx', data => $vars, contenttype => 'text/html', component => 1 );
  1203. $vars->{footer} = Trog::Renderer->render( template => 'footer.tx', data => $vars, contenttype => 'text/html', component => 1 );
  1204. return Trog::Renderer->render( template => $template, data => $vars, contenttype => 'text/html', code => $vars->{code} );
  1205. }
  1206. 1;