HTML.pm 33 KB

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