HTML.pm 29 KB

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