HTML.pm 25 KB

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