HTML.pm 48 KB

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