HTML.pm 32 KB

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