HTML.pm 26 KB

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