HTML.pm 28 KB

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