HTML.pm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. package Trog::Routes::HTML;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures state};
  6. use File::Touch();
  7. use Trog::Config;
  8. use Trog::Data;
  9. my $conf = Trog::Config::get();
  10. my $template_dir = 'www/templates';
  11. my $theme_dir;
  12. $theme_dir = "themes/".$conf->param('general.theme') if $conf->param('general.theme') && -d "www/themes/".$conf->param('general.theme');
  13. use lib 'www';
  14. our $landing_page = 'default.tx';
  15. our $htmltitle = 'title.tx';
  16. our $midtitle = 'midtitle.tx';
  17. our $rightbar = 'rightbar.tx';
  18. our $leftbar = 'leftbar.tx';
  19. our $footbar = 'footbar.tx';
  20. our %routes = (
  21. default => {
  22. callback => \&Trog::Routes::HTML::setup,
  23. },
  24. '/' => {
  25. method => 'GET',
  26. callback => \&Trog::Routes::HTML::index,
  27. },
  28. # This should only be enabled to debug
  29. # '/setup' => {
  30. # method => 'GET',
  31. # callback => \&Trog::Routes::HTML::setup,
  32. # },
  33. '/login' => {
  34. method => 'GET',
  35. callback => \&Trog::Routes::HTML::login,
  36. },
  37. '/auth' => {
  38. method => 'POST',
  39. nostatic => 1,
  40. callback => \&Trog::Routes::HTML::login,
  41. },
  42. '/config' => {
  43. method => 'GET',
  44. auth => 1,
  45. callback => \&Trog::Routes::HTML::config,
  46. },
  47. '/config/save' => {
  48. method => 'POST',
  49. auth => 1,
  50. callback => \&Trog::Routes::HTML::config_save,
  51. },
  52. '/post' => {
  53. method => 'GET',
  54. auth => 1,
  55. callback => \&Trog::Routes::HTML::post,
  56. },
  57. '/post/save' => {
  58. method => 'POST',
  59. auth => 1,
  60. callback => \&Trog::Routes::HTML::post,
  61. },
  62. '/post/(.*)' => {
  63. method => 'GET',
  64. auth => 1,
  65. callback => \&Trog::Routes::HTML::post,
  66. captures => ['id'],
  67. },
  68. '/posts/(.*)' => {
  69. method => 'GET',
  70. callback => \&Trog::Routes::HTML::posts,
  71. captures => ['id'],
  72. },
  73. '/posts' => {
  74. method => 'GET',
  75. callback => \&Trog::Routes::HTML::posts,
  76. },
  77. '/profile' => {
  78. method => 'POST',
  79. auth => 1,
  80. callback => \&Trog::Routes::HTML::profile,
  81. },
  82. '/themeclone' => {
  83. method => 'POST',
  84. auth => 1,
  85. callback => \&Trog::Routes::HTML::themeclone,
  86. },
  87. '/sitemap', => {
  88. method => 'GET',
  89. callback => \&Trog::Routes::HTML::sitemap,
  90. },
  91. '/sitemap_index.xml', => {
  92. method => 'GET',
  93. callback => \&Trog::Routes::HTML::sitemap,
  94. data => { xml => 1 },
  95. },
  96. '/sitemap_index.xml.gz', => {
  97. method => 'GET',
  98. callback => \&Trog::Routes::HTML::sitemap,
  99. data => { xml => 1, compressed => 1 },
  100. },
  101. '/sitemap/static.xml' => {
  102. method => 'GET',
  103. callback => \&Trog::Routes::HTML::sitemap,
  104. data => { xml => 1, map => 'static' },
  105. },
  106. '/sitemap/static.xml.gz' => {
  107. method => 'GET',
  108. callback => \&Trog::Routes::HTML::sitemap,
  109. data => { xml => 1, compressed => 1, map => 'static' },
  110. },
  111. '/sitemap/(.*).xml' => {
  112. method => 'GET',
  113. callback => \&Trog::Routes::HTML::sitemap,
  114. data => { xml => 1 },
  115. captures => ['map'],
  116. },
  117. '/sitemap/(.*).xml.gz' => {
  118. method => 'GET',
  119. callback => \&Trog::Routes::HTML::sitemap,
  120. data => { xml => 1, compressed => 1},
  121. captures => ['map'],
  122. },
  123. '/robots.txt' => {
  124. method => 'GET',
  125. callback => \&Trog::Routes::HTML::robots,
  126. },
  127. '/humans.txt' => {
  128. method => 'GET',
  129. callback => \&Trog::Routes::HTML::posts,
  130. data => { tag => ['about'] },
  131. },
  132. );
  133. # Build aliases for /posts and /post with extra data
  134. my @post_aliases = qw{news blog image video audio about files series};
  135. @routes{map { "/$_" } @post_aliases} = map { my %copy = %{$routes{'/posts'}}; $copy{data}{tag} = [$_]; \%copy } @post_aliases;
  136. #TODO clean this up so we don't need _build_post_type
  137. @routes{map { "/post/$_" } qw{image video audio files}} = map { my %copy = %{$routes{'/post'}}; $copy{data}{tag} = [$_]; $copy{data}{type} = 'file'; \%copy } qw{image video audio files};
  138. $routes{'/post/news'} = { method => 'GET', auth => 1, callback => \&Trog::Routes::HTML::post, data => { tag => ['news'], type => 'microblog' } };
  139. $routes{'/post/blog'} = { method => 'GET', auth => 1, callback => \&Trog::Routes::HTML::post, data => { tag => ['blog'], type => 'blog' } };
  140. $routes{'/post/about'} = { method => 'GET', auth => 1, callback => \&Trog::Routes::HTML::post, data => { tag => ['about'], type => 'profile' } };
  141. $routes{'/post/series'} = { method => 'GET', auth => 1, callback => \&Trog::Routes::HTML::post, data => { tag => ['series'], type => 'series' } };
  142. # Build aliases for /posts/(.*) and /post/(.*) with extra data
  143. @routes{map { "/$_/(.*)" } @post_aliases} = map { my %copy = %{$routes{'/posts/(.*)'}}; \%copy } @post_aliases;
  144. @routes{map { "/$_/(.*)" } @post_aliases} = map { my %copy = %{$routes{'/post/(.*)'}}; \%copy } @post_aliases;
  145. # Grab theme routes
  146. my $themed = 0;
  147. if ($theme_dir) {
  148. my $theme_mod = "$theme_dir/routes.pm";
  149. if (-f "www/$theme_mod" ) {
  150. require $theme_mod;
  151. @routes{keys(%Theme::routes)} = values(%Theme::routes);
  152. $themed = 1;
  153. }
  154. }
  155. sub robots ($query, $input, $render_cb) {
  156. my $processor = Text::Xslate->new(
  157. path => $template_dir,
  158. );
  159. return [200, ["Content-type:text/plain\n"],[$processor->render('robots.tx', { domain => $query->{domain} })]];
  160. }
  161. sub index ($query, $input, $render_cb, $content = '', $i_styles = []) {
  162. $query->{theme_dir} = $theme_dir || '';
  163. my $processor = Text::Xslate->new(
  164. path => $template_dir,
  165. );
  166. my $t_processor;
  167. $t_processor = Text::Xslate->new(
  168. path => "www/$theme_dir/templates",
  169. ) if $theme_dir;
  170. $content ||= _pick_processor($rightbar,$processor,$t_processor)->render($landing_page,$query);
  171. my @styles = ('/styles/avatars.css'); #TODO generate file for users
  172. if ($theme_dir) {
  173. unshift(@styles, _themed_style("screen.css")) if -f 'www/'._themed_style("screen.css");
  174. unshift(@styles, _themed_style("structure.css")) if -f 'www/'._themed_style("structure.css");
  175. }
  176. push( @styles, @$i_styles);
  177. #TODO allow theming of print css
  178. my $search_info = Trog::Data->new($conf);
  179. return $render_cb->('index.tx',{
  180. code => $query->{code},
  181. user => $query->{user},
  182. search_lang => $search_info->{lang},
  183. search_help => $search_info->{help},
  184. route => $query->{route},
  185. theme_dir => $theme_dir,
  186. content => $content,
  187. title => $conf->param('general.title'), #TODO control in theme instead
  188. htmltitle => _pick_processor("templates/$htmltitle" ,$processor,$t_processor)->render($htmltitle,$query),
  189. midtitle => _pick_processor("templates/$midtitle" ,$processor,$t_processor)->render($midtitle,$query),
  190. rightbar => _pick_processor("templates/$rightbar" ,$processor,$t_processor)->render($rightbar,$query),
  191. leftbar => _pick_processor("templates/$leftbar" ,$processor,$t_processor)->render($leftbar,$query),
  192. footbar => _pick_processor("templates/$footbar" ,$processor,$t_processor)->render($footbar,$query),
  193. stylesheets => \@styles,
  194. });
  195. }
  196. =head1 ADMIN ROUTES
  197. These are things that issue returns other than 200, and are not directly accessible by users via any defined route.
  198. =head2 notfound, forbidden, badrequest
  199. Implements the 4XX status codes. Override templates named the same for theming this.
  200. =cut
  201. sub _generic_route ($rname, $code, $title, $query,$input,$render_cb) {
  202. $query->{code} = $code;
  203. my $processor = Text::Xslate->new(
  204. path => _dir_for_resource("$rname.tx"),
  205. );
  206. my $styles = _build_themed_styles("$rname.css");
  207. my $content = $processor->render("$rname.tx", {
  208. title => $title,
  209. route => $query->{route},
  210. user => $query->{user},
  211. styles => $styles,
  212. });
  213. return Trog::Routes::HTML::index($query, $input, $render_cb, $content, $styles);
  214. }
  215. sub notfound (@args) {
  216. return _generic_route('notfound',404,"Return to sender, Address unknown", @args);
  217. }
  218. sub forbidden (@args) {
  219. return _generic_route('forbidden', 403, "STAY OUT YOU RED MENACE", @args);
  220. }
  221. sub badrequest (@args) {
  222. return _generic_route('badrequest', 400, "Bad Request", @args);
  223. }
  224. # TODO Rate limiting route
  225. =head1 NORMAL ROUTES
  226. These are expected to either return a 200, or redirect to something which does.
  227. =head2 setup
  228. One time setup page; should only display to the first user to visit the site which we presume to be the administrator.
  229. =cut
  230. sub setup ($query, $input, $render_cb) {
  231. File::Touch::touch("$ENV{HOME}/.tcms/setup");
  232. return $render_cb->('notconfigured.tx', {
  233. title => 'tCMS Requires Setup to Continue...',
  234. stylesheets => _build_themed_styles('notconfigured.css'),
  235. });
  236. }
  237. =head2 login
  238. 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.
  239. =cut
  240. sub login ($query, $input, $render_cb) {
  241. # Redirect if we actually have a logged in user.
  242. # Note to future me -- this user value is overwritten explicitly in server.psgi.
  243. # If that ever changes, you will die
  244. $query->{to} //= '/config';
  245. if ($query->{user}) {
  246. return $routes{$query->{to}}{callback}->($query,$input,$render_cb);
  247. }
  248. #Set the cookiez and issue a 302 back to ourselves if we have good creds
  249. my $postdata = _input2postdata($input);
  250. #Check and see if we have no users. If so we will just accept whatever creds are passed.
  251. my $hasusers = -f "$ENV{HOME}/.tcms/has_users";
  252. my $btnmsg = $hasusers ? "Log In" : "Register";
  253. my @headers;
  254. if ($postdata->{username} && $postdata->{password}) {
  255. if (!$hasusers) {
  256. # Make the first user
  257. Trog::Auth::useradd($postdata->{username}, $postdata->{password}, ['admin'] );
  258. File::Touch::touch("$ENV{HOME}/.tcms/has_users");
  259. }
  260. $query->{failed} = 1;
  261. my $cookie = Trog::Auth::mksession($postdata->{username}, $postdata->{password});
  262. if ($cookie) {
  263. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  264. @headers = (
  265. "Set-Cookie: tcmslogin=$cookie; HttpOnly",
  266. );
  267. $query->{failed} = 0;
  268. }
  269. }
  270. $query->{failed} //= -1;
  271. return $render_cb->('login.tx', {
  272. title => 'tCMS 2 ~ Login',
  273. to => $query->{to},
  274. failure => int( $query->{failed} ),
  275. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  276. btnmsg => $btnmsg,
  277. stylesheets => _build_themed_styles('login.css'),
  278. }, @headers);
  279. }
  280. =head2 config
  281. Renders the configuration page, or redirects you back to the login page.
  282. =cut
  283. sub config ($query, $input, $render_cb) {
  284. if (!$query->{user}) {
  285. $query->{to} = '/config';
  286. return login($query,$input,$render_cb);
  287. }
  288. #NOTE: we are relying on this to skip the ACL check with 'admin', this may not be viable in future?
  289. return forbidden($query, $input, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  290. my $css = _build_themed_styles('config.css');
  291. my $js = _build_themed_scripts('post.js');
  292. $query->{failure} //= -1;
  293. return $render_cb->('config.tx', {
  294. title => 'Configure tCMS',
  295. stylesheets => $css,
  296. scripts => $js,
  297. themes => _get_themes(),
  298. data_models => _get_data_models(),
  299. current_theme => $conf->param('general.theme') // '',
  300. current_data_model => $conf->param('general.data_model') // 'DUMMY',
  301. message => $query->{message},
  302. failure => $query->{failure},
  303. to => '/config',
  304. });
  305. }
  306. sub _get_themes {
  307. my $dir = 'www/themes';
  308. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  309. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  310. closedir $dh;
  311. return \@tdirs;
  312. }
  313. sub _get_data_models {
  314. my $dir = 'lib/Trog/Data';
  315. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  316. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  317. closedir $dh;
  318. return \@dmods
  319. }
  320. =head2 config_save
  321. Implements /config/save route. Saves what little configuration we actually use to ~/.tcms/tcms.conf
  322. =cut
  323. sub config_save ($query, $input, $render_cb) {
  324. my $postdata = _input2postdata($input);
  325. $conf->param( 'general.theme', $postdata->{theme} ) if defined $postdata->{theme};
  326. $conf->param( 'general.data_model', $postdata->{data_model} ) if $postdata->{data_model};
  327. $query->{failure} = 1;
  328. $query->{message} = "Failed to save configuration!";
  329. if ($conf->save($Trog::Config::home_config)) {
  330. $query->{failure} = 0;
  331. $query->{message} = "Configuration updated succesfully.";
  332. }
  333. # TODO we need to soft-restart the server at this point. Maybe we can just hot-load config on each page when we get to have static renders? Probably not worth the perf hit for paywall users.
  334. return config($query, $input, $render_cb);
  335. }
  336. # TODO actually do stuff
  337. sub profile ($query, $input, $render_cb) {
  338. return config($query, $input, $render_cb);
  339. }
  340. =head2 themeclone
  341. Clone a theme by copying a directory.
  342. =cut
  343. sub themeclone ($query, $input, $render_cb) {
  344. my $postdata = _input2postdata($input);
  345. my ($theme, $newtheme) = ($postdata->{theme},$postdata->{newtheme});
  346. my $themedir = 'www/themes';
  347. $query->{failure} = 1;
  348. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  349. require File::Copy::Recursive;
  350. if ($theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" )) {
  351. $query->{failure} = 0;
  352. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  353. }
  354. return config($query, $input, $render_cb);
  355. }
  356. =head2 post
  357. Display the route for making new posts.
  358. =cut
  359. sub post ($query, $input, $render_cb) {
  360. if (!$query->{user}) {
  361. $query->{to} = '/post';
  362. return login($query,$input,$render_cb);
  363. }
  364. return forbidden($query, $input, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  365. my $tags = _coerce_array($query->{tag});
  366. my $posts = _post_helper($query, $tags, $query->{acls});
  367. my $css = _build_themed_styles('post.css');
  368. my $js = _build_themed_scripts('post.js');
  369. push(@$css, '/styles/avatars.css');
  370. return $render_cb->('post.tx', {
  371. title => 'New Post',
  372. post_visibilities => ['public', 'private', 'unlisted'],
  373. stylesheets => $css,
  374. scripts => $js,
  375. posts => $posts,
  376. can_edit => 1,
  377. types => [qw{microblog blog file series profile}],
  378. route => '/posts',
  379. category => '/posts',
  380. page => int($query->{page} || 1),
  381. limit => int($query->{limit} || 1),
  382. sizes => [25,50,100],
  383. id => $query->{id},
  384. acls => _post_helper({}, ['series'], $query->{acls}),
  385. edittype => $query->{type} || 'microblog',
  386. });
  387. }
  388. #TODO actually do stuff
  389. sub post_save ($query, $input, $render_cb) {
  390. return post($query, $input, $render_cb);
  391. }
  392. =head2 posts
  393. Display multi or single posts, supports RSS and pagination.
  394. =cut
  395. sub posts ($query, $input, $render_cb) {
  396. my $tags = _coerce_array($query->{tag});
  397. #TODO If we have a direct ID query, we should show unlisted videos as well as public ones IFF they have a valid campaign ID attached to query
  398. push(@{$query->{acls}}, 'public');
  399. my $posts = _post_helper($query, $tags, $query->{acls});
  400. return notfound($query,$input,$render_cb) unless @$posts;
  401. my $fmt = $query->{format} || '';
  402. return _rss($query,$posts) if $fmt eq 'rss';
  403. my $processor = Text::Xslate->new(
  404. path => _dir_for_resource('posts.tx'),
  405. );
  406. my $styles = _build_themed_styles('posts.css');
  407. my $content = $processor->render('posts.tx', {
  408. title => "Posts tagged @$tags",
  409. posts => $posts,
  410. route => $query->{route},
  411. page => int($query->{page} || 1),
  412. limit => int($query->{limit} || 1),
  413. sizes => [25,50,100],
  414. rss => !$query->{id},
  415. tiled => scalar(grep { $_ eq $query->{route} } qw{/files /audio /video /image /series}),
  416. category => $themed ? Theme::path_to_tile($query->{route}) : $query->{route},
  417. });
  418. return Trog::Routes::HTML::index($query, $input, $render_cb, $content, $styles);
  419. }
  420. sub _post_helper ($query, $tags, $acls) {
  421. state $data = Trog::Data->new($conf);
  422. return $data->get(
  423. page => int($query->{page} || 1),
  424. limit => int($query->{limit} || 25),
  425. tags => $tags,
  426. acls => $acls,
  427. like => $query->{like},
  428. id => $query->{id},
  429. );
  430. }
  431. =head2 sitemap
  432. Return the sitemap index unless the static or a set of dynamic routes is requested.
  433. We have a maximum of 99,990,000 posts we can make under this model
  434. As we have 10,000 * 10,000 posts which are indexable via the sitemap format.
  435. 1 top level index slot (10k posts) is taken by our static routes, the rest will be /posts.
  436. Passing ?xml=1 will result in an appropriate sitemap.xml instead.
  437. This is used to generate the static sitemaps as expected by search engines.
  438. Passing compressed=1 will gzip the output.
  439. =cut
  440. sub sitemap ($query, $input, $render_cb) {
  441. my (@to_map, $is_index, $route_type);
  442. my $warning = '';
  443. $query->{map} //= '';
  444. if ($query->{map} eq 'static') {
  445. # Return the map of static routes
  446. $route_type = 'Static Routes';
  447. @to_map = grep { !defined $routes{$_}->{captures} && $_ !~ m/^default|login|auth$/ && !$routes{$_}->{auth} } keys(%routes);
  448. } elsif ( !$query->{map} ) {
  449. # Return the index instead
  450. @to_map = ('static');
  451. my $data = Trog::Data->new($conf);
  452. my $tot = $data->total_posts();
  453. my $size = 50000;
  454. my $pages = int($tot / $size) + (($tot % $size) ? 1 : 0);
  455. # Truncate pages at 10k due to standard
  456. my $clamped = $pages > 49999 ? 49999 : $pages;
  457. $warning = "More posts than possible to represent in sitemaps & index! Old posts have been truncated." if $pages > 49999;
  458. foreach my $page ($clamped..1) {
  459. push(@to_map, "$page");
  460. }
  461. $is_index = 1;
  462. } else {
  463. $route_type = "Posts: Page $query->{map}";
  464. # Return the map of the particular range of dynamic posts
  465. $query->{limit} = 50000;
  466. $query->{page} = $query->{map};
  467. @to_map = @{_post_helper($query, [], ['public'])};
  468. }
  469. if ( $query->{xml} ) {
  470. my $sm;
  471. my $xml_date = time();
  472. my $fmt = "xml";
  473. $fmt .= ".gz" if $query->{compressed};
  474. if ( !$query->{map}) {
  475. require WWW::SitemapIndex::XML;
  476. $sm = WWW::SitemapIndex::XML->new();
  477. foreach my $url (@to_map) {
  478. $sm->add(
  479. loc => "http://$query->{domain}/sitemap/$url.$fmt",
  480. lastmod => $xml_date,
  481. );
  482. }
  483. } else {
  484. require WWW::Sitemap::XML;
  485. $sm = WWW::Sitemap::XML->new();
  486. my $changefreq = $query->{map} eq 'static' ? 'monthly' : 'daily';
  487. foreach my $url (@to_map) {
  488. my $true_uri = "http://$query->{domain}$url";
  489. $true_uri = "http://$query->{domain}/posts/$url->{id}" if ref $url eq 'HASH';
  490. my %data = (
  491. loc => $true_uri,
  492. lastmod => $xml_date,
  493. mobile => 1,
  494. changefreq => $changefreq,
  495. priority => 1.0,
  496. );
  497. #TODO add video & preview image if applicable
  498. $sm->add(%data);
  499. }
  500. }
  501. my $xml = $sm->as_xml();
  502. require IO::String;
  503. my $buf = IO::String->new();
  504. my $ct = 'application/xml';
  505. $xml->toFH($buf, 0);
  506. seek $buf, 0, 0;
  507. if ($query->{compressed}) {
  508. require IO::Compress::Gzip;
  509. my $compressed = IO::String->new();
  510. IO::Compress::Gzip::gzip($buf => $compressed);
  511. $ct = 'application/gzip';
  512. $buf = $compressed;
  513. seek $compressed, 0, 0;
  514. }
  515. return [200,["Content-type:$ct\n"], $buf];
  516. }
  517. @to_map = sort @to_map unless $is_index;
  518. my $processor = Text::Xslate->new(
  519. path => _dir_for_resource('sitemap.tx'),
  520. );
  521. my $styles = _build_themed_styles('sitemap.css');
  522. my $content = $processor->render('sitemap.tx', {
  523. title => "Site Map",
  524. to_map => \@to_map,
  525. is_index => $is_index,
  526. route_type => $route_type,
  527. route => $query->{route},
  528. });
  529. return Trog::Routes::HTML::index($query,$input,$render_cb,$content,$styles);
  530. }
  531. sub _rss ($query,$posts) {
  532. require XML::RSS;
  533. my $rss = XML::RSS->new (version => '2.0');
  534. my $now = DateTime->from_epoch(epoch => time());
  535. $rss->channel(
  536. title => "$query->{domain}",
  537. link => "http://$query->{domain}/$query->{route}?format=rss",
  538. language => 'en', #TODO localization
  539. description => 'tCMS website', #TODO make configurable
  540. pubDate => $now, #TODO format
  541. lastBuildDate => $now, #TODO format
  542. );
  543. #TODO configurability
  544. $rss->image(
  545. title => $query->{domain},
  546. url => "http://$query->{domain}/img/icon/tcms.svg",
  547. link => "http://$query->{domain}",
  548. width => 88,
  549. height => 31,
  550. description => 'tCMS image'
  551. );
  552. foreach my $post (@$posts) {
  553. my $url = "http://$query->{domain}/posts/$post->{id}";
  554. $rss->add_item(
  555. title => $post->{title},
  556. permaLink => $url,
  557. link => $url,
  558. enclosure => { url => $url, type=>"text/html" },
  559. description => "<![CDATA[$post->{data}]]>",
  560. pubDate => DateTime->from_epoch(epoch => $post->{created} ), #TODO format like Thu, 23 Aug 1999 07:00:00 GMT
  561. author => $post->{user}, #TODO translate to "email (user)" format
  562. );
  563. }
  564. return [200, ["Content-type: application/rss+xml\n"], [$rss->as_string]];
  565. }
  566. sub _input2postdata ($input) {
  567. #Set the cookiez and issue a 302 back to ourselves if we have good creds
  568. my ($slurpee,$postdata) = ('',{});
  569. while (<$input>) { $slurpee .= $_ }
  570. $postdata = URL::Encode::url_params_mixed($slurpee) if $slurpee;
  571. return $postdata;
  572. }
  573. # Deal with Params which may or may not be arrays
  574. sub _coerce_array ($param) {
  575. my $p = $param || [];
  576. $p = [$param] if $param && (ref $param ne 'ARRAY');
  577. return $p;
  578. }
  579. sub _build_themed_styles ($style) {
  580. my @styles = ("/styles/$style");
  581. my $ts = _themed_style($style);
  582. push(@styles, $ts) if $theme_dir && -f "www/$ts";
  583. return \@styles;
  584. }
  585. sub _build_themed_scripts ($script) {
  586. my @scripts = ("/scripts/$script");
  587. my $ts = _themed_style($script);
  588. push(@scripts, $ts) if $theme_dir && -f "www/$ts";
  589. return \@scripts;
  590. }
  591. sub _pick_processor($file, $normal, $themed) {
  592. return _dir_for_resource($file) eq $template_dir ? $normal : $themed;
  593. }
  594. # Pick appropriate dir based on whether theme override exists
  595. sub _dir_for_resource ($resource) {
  596. return $theme_dir && -f "www/$theme_dir/$resource" ? $theme_dir : $template_dir;
  597. }
  598. sub _themed_style ($resource) {
  599. return _dir_for_resource("styles/$resource")."/styles/$resource";
  600. }
  601. sub _themed_script ($resource) {
  602. return _dir_for_resource("scripts/$resource")."/scripts/$resource";
  603. }
  604. 1;