HTML.pm 31 KB

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