HTML.pm 33 KB

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