HTML.pm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 Trog::Config;
  8. use Trog::Data;
  9. my $conf = Trog::Config::get();
  10. my $template_dir = 'www/templates';
  11. my $theme_dir;
  12. $theme_dir = "themes/".$conf->param('general.theme') if $conf->param('general.theme') && -d "www/themes/".$conf->param('general.theme');
  13. use lib 'www';
  14. our $landing_page = 'default.tx';
  15. our $htmltitle = 'title.tx';
  16. our $midtitle = 'midtitle.tx';
  17. our $rightbar = 'rightbar.tx';
  18. our $leftbar = 'leftbar.tx';
  19. our $footbar = 'footbar.tx';
  20. our %routes = (
  21. default => {
  22. callback => \&Trog::Routes::HTML::setup,
  23. },
  24. '/' => {
  25. method => 'GET',
  26. callback => \&Trog::Routes::HTML::index,
  27. },
  28. # This should only be enabled to debug
  29. # '/setup' => {
  30. # method => 'GET',
  31. # callback => \&Trog::Routes::HTML::setup,
  32. # },
  33. '/login' => {
  34. method => 'GET',
  35. callback => \&Trog::Routes::HTML::login,
  36. },
  37. '/auth' => {
  38. method => 'POST',
  39. nostatic => 1,
  40. callback => \&Trog::Routes::HTML::login,
  41. },
  42. '/config' => {
  43. method => 'GET',
  44. auth => 1,
  45. callback => \&Trog::Routes::HTML::config,
  46. },
  47. '/config/save' => {
  48. method => 'POST',
  49. auth => 1,
  50. callback => \&Trog::Routes::HTML::config_save,
  51. },
  52. '/post' => {
  53. method => 'GET',
  54. auth => 1,
  55. callback => \&Trog::Routes::HTML::post,
  56. },
  57. '/post/save' => {
  58. method => 'POST',
  59. auth => 1,
  60. callback => \&Trog::Routes::HTML::post,
  61. },
  62. '/posts/(.*)' => {
  63. method => 'GET',
  64. auth => 1,
  65. callback => \&Trog::Routes::HTML::posts,
  66. captures => ['id'],
  67. },
  68. '/posts' => {
  69. method => 'GET',
  70. callback => \&Trog::Routes::HTML::posts,
  71. },
  72. '/profile' => {
  73. method => 'POST',
  74. auth => 1,
  75. callback => \&Trog::Routes::HTML::profile,
  76. },
  77. '/themeclone' => {
  78. method => 'POST',
  79. auth => 1,
  80. callback => \&Trog::Routes::HTML::themeclone,
  81. },
  82. '/sitemap', => {
  83. method => 'GET',
  84. callback => \&Trog::Routes::HTML::sitemap,
  85. },
  86. );
  87. # Build aliases for /post with extra data
  88. my @post_aliases = qw{news blog image video audio about files series};
  89. @routes{map { "/$_" } @post_aliases} = map { my %copy = %{$routes{'/posts'}}; $copy{data}{tag} = [$_]; \%copy } @post_aliases;
  90. # Build aliases for /post/(.*) with extra data
  91. @routes{map { "/$_/(.*)" } @post_aliases} = map { my %copy = %{$routes{'/posts/(.*)'}}; \%copy } @post_aliases;
  92. # Grab theme routes
  93. my $themed = 0;
  94. if ($theme_dir) {
  95. my $theme_mod = "$theme_dir/routes.pm";
  96. if (-f "www/$theme_mod" ) {
  97. require $theme_mod;
  98. @routes{keys(%Theme::routes)} = values(%Theme::routes);
  99. $themed = 1;
  100. }
  101. }
  102. # TODO build a sitemap.xml based on the above routing table, and robots.txt
  103. sub index ($query, $input, $render_cb, $content = '', $i_styles = []) {
  104. $query->{theme_dir} = $theme_dir || '';
  105. my $processor = Text::Xslate->new(
  106. path => $template_dir,
  107. );
  108. my $t_processor;
  109. $t_processor = Text::Xslate->new(
  110. path => "www/$theme_dir/templates",
  111. ) if $theme_dir;
  112. $content ||= _pick_processor($rightbar,$processor,$t_processor)->render($landing_page,$query);
  113. my @styles = ('/styles/avatars.css'); #TODO generate file for users
  114. if ($theme_dir) {
  115. unshift(@styles, _themed_style("screen.css")) if -f 'www/'._themed_style("screen.css");
  116. unshift(@styles, _themed_style("structure.css")) if -f 'www/'._themed_style("structure.css");
  117. }
  118. push( @styles, @$i_styles);
  119. #TODO allow theming of print css
  120. my $search_info = Trog::Data->new($conf);
  121. return $render_cb->('index.tx',{
  122. code => $query->{code},
  123. user => $query->{user},
  124. search_lang => $search_info->{lang},
  125. search_help => $search_info->{help},
  126. route => $query->{route},
  127. theme_dir => $theme_dir,
  128. content => $content,
  129. title => $conf->param('general.title'), #TODO control in theme instead
  130. htmltitle => _pick_processor("templates/$htmltitle" ,$processor,$t_processor)->render($htmltitle,$query),
  131. midtitle => _pick_processor("templates/$midtitle" ,$processor,$t_processor)->render($midtitle,$query),
  132. rightbar => _pick_processor("templates/$rightbar" ,$processor,$t_processor)->render($rightbar,$query),
  133. leftbar => _pick_processor("templates/$leftbar" ,$processor,$t_processor)->render($leftbar,$query),
  134. footbar => _pick_processor("templates/$footbar" ,$processor,$t_processor)->render($footbar,$query),
  135. stylesheets => \@styles,
  136. });
  137. }
  138. =head1 ADMIN ROUTES
  139. These are things that issue returns other than 200, and are not directly accessible by users via any defined route.
  140. =head2 notfound, forbidden, badrequest
  141. Implements the 4XX status codes. Override templates named the same for theming this.
  142. =cut
  143. sub _generic_route ($rname, $code, $title, $query,$input,$render_cb) {
  144. $query->{code} = $code;
  145. my $processor = Text::Xslate->new(
  146. path => _dir_for_resource("$rname.tx"),
  147. );
  148. my $styles = _build_themed_styles("$rname.css");
  149. my $content = $processor->render("$rname.tx", {
  150. title => $title,
  151. route => $query->{route},
  152. user => $query->{user},
  153. styles => $styles,
  154. });
  155. return Trog::Routes::HTML::index($query, $input, $render_cb, $content, $styles);
  156. }
  157. sub notfound (@args) {
  158. return _generic_route('notfound',404,"Return to sender, Address unknown", @args);
  159. }
  160. sub forbidden (@args) {
  161. return _generic_route('forbidden', 403, "STAY OUT YOU RED MENACE", @args);
  162. }
  163. sub badrequest (@args) {
  164. return _generic_route('badrequest', 400, "Bad Request", @args);
  165. }
  166. # TODO Rate limiting route
  167. =head1 NORMAL ROUTES
  168. These are expected to either return a 200, or redirect to something which does.
  169. =head2 setup
  170. One time setup page; should only display to the first user to visit the site which we presume to be the administrator.
  171. =cut
  172. sub setup ($query, $input, $render_cb) {
  173. File::Touch::touch("$ENV{HOME}/.tcms/setup");
  174. return $render_cb->('notconfigured.tx', {
  175. title => 'tCMS Requires Setup to Continue...',
  176. stylesheets => _build_themed_styles('notconfigured.css'),
  177. });
  178. }
  179. =head2 login
  180. 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.
  181. =cut
  182. sub login ($query, $input, $render_cb) {
  183. # Redirect if we actually have a logged in user.
  184. # Note to future me -- this user value is overwritten explicitly in server.psgi.
  185. # If that ever changes, you will die
  186. $query->{to} //= '/config';
  187. if ($query->{user}) {
  188. return $routes{$query->{to}}{callback}->($query,$input,$render_cb);
  189. }
  190. #Set the cookiez and issue a 302 back to ourselves if we have good creds
  191. my $postdata = _input2postdata($input);
  192. #Check and see if we have no users. If so we will just accept whatever creds are passed.
  193. my $hasusers = -f "$ENV{HOME}/.tcms/has_users";
  194. my $btnmsg = $hasusers ? "Log In" : "Register";
  195. my @headers;
  196. if ($postdata->{username} && $postdata->{password}) {
  197. if (!$hasusers) {
  198. # Make the first user
  199. Trog::Auth::useradd($postdata->{username}, $postdata->{password}, ['admin'] );
  200. File::Touch::touch("$ENV{HOME}/.tcms/has_users");
  201. }
  202. $query->{failed} = 1;
  203. my $cookie = Trog::Auth::mksession($postdata->{username}, $postdata->{password});
  204. if ($cookie) {
  205. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  206. @headers = (
  207. "Set-Cookie: tcmslogin=$cookie; HttpOnly",
  208. );
  209. $query->{failed} = 0;
  210. }
  211. }
  212. $query->{failed} //= -1;
  213. return $render_cb->('login.tx', {
  214. title => 'tCMS 2 ~ Login',
  215. to => $query->{to},
  216. failure => int( $query->{failed} ),
  217. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  218. btnmsg => $btnmsg,
  219. stylesheets => _build_themed_styles('login.css'),
  220. }, @headers);
  221. }
  222. =head2 config
  223. Renders the configuration page, or redirects you back to the login page.
  224. =cut
  225. sub config ($query, $input, $render_cb) {
  226. if (!$query->{user}) {
  227. $query->{to} = '/config';
  228. return login($query,$input,$render_cb);
  229. }
  230. #NOTE: we are relying on this to skip the ACL check with 'admin', this may not be viable in future?
  231. return forbidden($query, $input, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  232. my $tags = ['profile'];
  233. my $posts = _post_helper($query, $tags, $query->{acls});
  234. my $css = _build_themed_styles('config.css');
  235. my $js = _build_themed_scripts('post.js');
  236. push(@$css, '/styles/avatars.css');
  237. $query->{failure} //= -1;
  238. return $render_cb->('config.tx', {
  239. title => 'Configure tCMS',
  240. stylesheets => $css,
  241. scripts => $js,
  242. themes => _get_themes(),
  243. data_models => _get_data_models(),
  244. current_theme => $conf->param('general.theme') // '',
  245. current_data_model => $conf->param('general.data_model') // 'DUMMY',
  246. post_visibilities => [qw{public private unlisted}],
  247. route => '/about',
  248. category => '/about',
  249. types => ['profile'],
  250. acls => _post_helper({}, ['series'], $query->{acls}),
  251. can_edit => 1,
  252. posts => $posts,
  253. edittype => 'profile',
  254. message => $query->{message},
  255. failure => $query->{failure},
  256. to => '/config',
  257. });
  258. }
  259. sub _get_themes {
  260. my $dir = 'www/themes';
  261. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  262. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  263. closedir $dh;
  264. return \@tdirs;
  265. }
  266. sub _get_data_models {
  267. my $dir = 'lib/Trog/Data';
  268. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  269. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  270. closedir $dh;
  271. return \@dmods
  272. }
  273. =head2 config_save
  274. Implements /config/save route. Saves what little configuration we actually use to ~/.tcms/tcms.conf
  275. =cut
  276. sub config_save ($query, $input, $render_cb) {
  277. my $postdata = _input2postdata($input);
  278. $conf->param( 'general.theme', $postdata->{theme} ) if defined $postdata->{theme};
  279. $conf->param( 'general.data_model', $postdata->{data_model} ) if $postdata->{data_model};
  280. $query->{failure} = 1;
  281. $query->{message} = "Failed to save configuration!";
  282. if ($conf->save($Trog::Config::home_config)) {
  283. $query->{failure} = 0;
  284. $query->{message} = "Configuration updated succesfully.";
  285. }
  286. # TODO we need to soft-restart the server at this point. Maybe we can just hot-load config on each page when we get to have static renders? Probably not worth the perf hit for paywall users.
  287. return config($query, $input, $render_cb);
  288. }
  289. # TODO actually do stuff
  290. sub profile ($query, $input, $render_cb) {
  291. return config($query, $input, $render_cb);
  292. }
  293. =head2 themeclone
  294. Clone a theme by copying a directory.
  295. =cut
  296. sub themeclone ($query, $input, $render_cb) {
  297. my $postdata = _input2postdata($input);
  298. my ($theme, $newtheme) = ($postdata->{theme},$postdata->{newtheme});
  299. my $themedir = 'www/themes';
  300. $query->{failure} = 1;
  301. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  302. require File::Copy::Recursive;
  303. if ($theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" )) {
  304. $query->{failure} = 0;
  305. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  306. }
  307. return config($query, $input, $render_cb);
  308. }
  309. =head2 post
  310. Display the route for making new posts.
  311. =cut
  312. sub post ($query, $input, $render_cb) {
  313. if (!$query->{user}) {
  314. $query->{to} = '/post';
  315. return login($query,$input,$render_cb);
  316. }
  317. return forbidden($query, $input, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  318. my $tags = _coerce_array($query->{tag});
  319. my $posts = _post_helper($query, $tags, $query->{acls});
  320. my $css = _build_themed_styles('post.css');
  321. my $js = _build_themed_scripts('post.js');
  322. push(@$css, '/styles/avatars.css');
  323. return $render_cb->('post.tx', {
  324. title => 'New Post',
  325. post_visibilities => ['public', 'private', 'unlisted'],
  326. stylesheets => $css,
  327. scripts => $js,
  328. posts => $posts,
  329. can_edit => 1,
  330. types => [qw{microblog blog file series}],
  331. route => '/posts',
  332. category => '/posts',
  333. page => int($query->{page} || 1),
  334. limit => int($query->{limit} || 1),
  335. sizes => [25,50,100],
  336. edittype => $query->{type} || 'microblog',
  337. });
  338. }
  339. #TODO actually do stuff
  340. sub post_save ($query, $input, $render_cb) {
  341. return post($query, $input, $render_cb);
  342. }
  343. =head2 posts
  344. Display multi or single posts, supports RSS and pagination.
  345. =cut
  346. sub posts ($query, $input, $render_cb) {
  347. my $tags = _coerce_array($query->{tag});
  348. #TODO If we have a direct ID query, we should show unlisted videos as well as public ones IFF they have a valid campaign ID attached to query
  349. push(@{$query->{acls}}, 'public');
  350. my $posts = _post_helper($query, $tags, $query->{acls});
  351. return notfound($query,$input,$render_cb) unless @$posts;
  352. my $fmt = $query->{format} || '';
  353. return _rss($posts) if $fmt eq 'rss';
  354. my $processor = Text::Xslate->new(
  355. path => _dir_for_resource('posts.tx'),
  356. );
  357. my $styles = _build_themed_styles('posts.css');
  358. my $content = $processor->render('posts.tx', {
  359. title => "Posts tagged @$tags",
  360. posts => $posts,
  361. route => $query->{route},
  362. page => int($query->{page} || 1),
  363. limit => int($query->{limit} || 1),
  364. sizes => [25,50,100],
  365. rss => !$query->{id},
  366. tiled => scalar(grep { $_ eq $query->{route} } qw{/files /audio /video /image /series}),
  367. category => $themed ? Theme::path_to_tile($query->{route}) : $query->{route},
  368. });
  369. return Trog::Routes::HTML::index($query, $input, $render_cb, $content, $styles);
  370. }
  371. sub _post_helper ($query, $tags, $acls) {
  372. state $data = Trog::Data->new($conf);
  373. return $data->get(
  374. page => int($query->{page} || 1),
  375. limit => int($query->{limit} || 25),
  376. tags => $tags,
  377. acls => $acls,
  378. like => $query->{like},
  379. id => $query->{id},
  380. );
  381. }
  382. =head2 sitemap
  383. Return the sitemap index unless the static or a set of dynamic routes is requested.
  384. We have a maximum of 99,990,000 posts we can make under this model
  385. As we have 10,000 * 10,000 posts which are indexable via the sitemap format.
  386. 1 top level index slot (10k posts) is taken by our static routes, the rest will be /posts.
  387. =cut
  388. sub sitemap ($query, $input, $render_cb) {
  389. my (@to_map, $is_index, $route_type);
  390. my $warning = '';
  391. $query->{map} //= '';
  392. if ($query->{map} eq 'static') {
  393. # Return the map of static routes
  394. $route_type = 'Static Routes';
  395. @to_map = grep { !defined $routes{$_}->{captures} && $_ ne 'default' } keys(%routes);
  396. } elsif ( !$query->{map} ) {
  397. # Return the index instead
  398. @to_map = ('static');
  399. my $data = Trog::Data->new($conf);
  400. my $tot = $data->total_posts();
  401. my $size = 50000;
  402. my $pages = int($tot / $size) + (($tot % $size) ? 1 : 0);
  403. # Truncate pages at 10k due to standard
  404. my $clamped = $pages > 49999 ? 49999 : $pages;
  405. $warning = "More posts than possible to represent in sitemaps & index! Old posts have been truncated." if $pages > 49999;
  406. foreach my $page ($clamped..1) {
  407. push(@to_map, "$page");
  408. }
  409. $is_index = 1;
  410. } else {
  411. $route_type = "Posts: Page $query->{map}";
  412. # Return the map of the particular range of dynamic posts
  413. $query->{limit} = 50000;
  414. $query->{page} = $query->{map};
  415. @to_map = @{_post_helper($query, {}, ['public'])};
  416. }
  417. @to_map = sort @to_map unless $is_index;
  418. my $processor = Text::Xslate->new(
  419. path => _dir_for_resource('sitemap.tx'),
  420. );
  421. my $styles = _build_themed_styles('sitemap.css');
  422. my $content = $processor->render('sitemap.tx', {
  423. title => "Site Map",
  424. to_map => \@to_map,
  425. is_index => $is_index,
  426. route_type => $route_type,
  427. route => $query->{route},
  428. });
  429. return Trog::Routes::HTML::index($query,$input,$render_cb,$content,$styles);
  430. }
  431. sub _rss ($posts) {
  432. return [200, ["Content-type: text/plain\n"], ["TODO"]];
  433. }
  434. sub _input2postdata ($input) {
  435. #Set the cookiez and issue a 302 back to ourselves if we have good creds
  436. my ($slurpee,$postdata) = ('',{});
  437. while (<$input>) { $slurpee .= $_ }
  438. $postdata = URL::Encode::url_params_mixed($slurpee) if $slurpee;
  439. return $postdata;
  440. }
  441. # Deal with Params which may or may not be arrays
  442. sub _coerce_array ($param) {
  443. my $p = $param || [];
  444. $p = [$param] if $param && (ref $param ne 'ARRAY');
  445. return $p;
  446. }
  447. sub _build_themed_styles ($style) {
  448. my @styles = ("/styles/$style");
  449. my $ts = _themed_style($style);
  450. push(@styles, $ts) if $theme_dir && -f "www/$ts";
  451. return \@styles;
  452. }
  453. sub _build_themed_scripts ($script) {
  454. my @scripts = ("/scripts/$script");
  455. my $ts = _themed_style($script);
  456. push(@scripts, $ts) if $theme_dir && -f "www/$ts";
  457. return \@scripts;
  458. }
  459. sub _pick_processor($file, $normal, $themed) {
  460. return _dir_for_resource($file) eq $template_dir ? $normal : $themed;
  461. }
  462. # Pick appropriate dir based on whether theme override exists
  463. sub _dir_for_resource ($resource) {
  464. return $theme_dir && -f "www/$theme_dir/$resource" ? $theme_dir : $template_dir;
  465. }
  466. sub _themed_style ($resource) {
  467. return _dir_for_resource("styles/$resource")."/styles/$resource";
  468. }
  469. sub _themed_script ($resource) {
  470. return _dir_for_resource("scripts/$resource")."/scripts/$resource";
  471. }
  472. 1;