HTML.pm 48 KB

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