HTML.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. package Trog::Routes::HTML;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures};
  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. );
  83. # Build aliases for /post with extra data
  84. my @post_aliases = qw{news blog image video audio about files};
  85. @routes{map { "/$_" } @post_aliases} = map { my %copy = %{$routes{'/posts'}}; $copy{data}{tag} = [$_]; \%copy } @post_aliases;
  86. # Build aliases for /post/(.*) with extra data
  87. @routes{map { "/$_/(.*)" } @post_aliases} = map { my %copy = %{$routes{'/posts/(.*)'}}; \%copy } @post_aliases;
  88. # Grab theme routes
  89. my $themed = 0;
  90. if ($theme_dir) {
  91. my $theme_mod = "$theme_dir/routes.pm";
  92. if (-f "www/$theme_mod" ) {
  93. require $theme_mod;
  94. @routes{keys(%Theme::routes)} = values(%Theme::routes);
  95. $themed = 1;
  96. }
  97. }
  98. # TODO build a sitemap.xml based on the above routing table, and robots.txt
  99. sub index ($query, $input, $render_cb, $content = '', $i_styles = []) {
  100. $query->{theme_dir} = $theme_dir || '';
  101. my $processor = Text::Xslate->new(
  102. path => $template_dir,
  103. );
  104. my $t_processor;
  105. $t_processor = Text::Xslate->new(
  106. path => "www/$theme_dir/templates",
  107. ) if $theme_dir;
  108. $content ||= _pick_processor($rightbar,$processor,$t_processor)->render($landing_page,$query);
  109. my @styles = ('/styles/avatars.css'); #TODO generate file for users
  110. if ($theme_dir) {
  111. unshift(@styles, _themed_style("screen.css")) if -f 'www/'._themed_style("screen.css");
  112. unshift(@styles, _themed_style("structure.css")) if -f 'www/'._themed_style("structure.css");
  113. }
  114. push( @styles, @$i_styles);
  115. #TODO allow theming of print css
  116. my $search_info = Trog::Data->new($conf);
  117. return $render_cb->('index.tx',{
  118. code => $query->{code},
  119. user => $query->{user},
  120. search_lang => $search_info->{lang},
  121. search_help => $search_info->{help},
  122. route => $query->{route},
  123. theme_dir => $theme_dir,
  124. content => $content,
  125. title => $conf->param('general.title'), #TODO control in theme instead
  126. htmltitle => _pick_processor("templates/$htmltitle" ,$processor,$t_processor)->render($htmltitle,$query),
  127. midtitle => _pick_processor("templates/$midtitle" ,$processor,$t_processor)->render($midtitle,$query),
  128. rightbar => _pick_processor("templates/$rightbar" ,$processor,$t_processor)->render($rightbar,$query),
  129. leftbar => _pick_processor("templates/$leftbar" ,$processor,$t_processor)->render($leftbar,$query),
  130. footbar => _pick_processor("templates/$footbar" ,$processor,$t_processor)->render($footbar,$query),
  131. stylesheets => \@styles,
  132. });
  133. }
  134. =head1 ADMIN ROUTES
  135. These are things that issue returns other than 200, and are not directly accessible by users via any defined route.
  136. =head2 notfound, forbidden, badrequest
  137. Implements the 4XX status codes. Override templates named the same for theming this.
  138. =cut
  139. sub _generic_route ($rname, $code, $title, $query,$input,$render_cb) {
  140. $query->{code} = $code;
  141. my $processor = Text::Xslate->new(
  142. path => _dir_for_resource("$rname.tx"),
  143. );
  144. my $styles = _build_themed_styles("$rname.css");
  145. my $content = $processor->render("$rname.tx", {
  146. title => $title,
  147. route => $query->{route},
  148. styles => $styles,
  149. });
  150. return Trog::Routes::HTML::index($query, $input, $render_cb, $content, $styles);
  151. }
  152. sub notfound (@args) {
  153. return _generic_route('notfound',404,"Return to sender, Address unknown", @args);
  154. }
  155. sub forbidden (@args) {
  156. return _generic_route('forbidden', 403, "STAY OUT YOU RED MENACE", @args);
  157. }
  158. sub badrequest (@args) {
  159. return _generic_route('badrequest', 400, "Bad Request", @args);
  160. }
  161. # TODO Rate limiting route
  162. =head1 NORMAL ROUTES
  163. These are expected to either return a 200, or redirect to something which does.
  164. =head2 setup
  165. One time setup page; should only display to the first user to visit the site which we presume to be the administrator.
  166. =cut
  167. sub setup ($query, $input, $render_cb) {
  168. File::Touch::touch("$ENV{HOME}/.tcms/setup");
  169. return $render_cb->('notconfigured.tx', {
  170. title => 'tCMS Requires Setup to Continue...',
  171. stylesheets => _build_themed_styles('notconfigured.css'),
  172. });
  173. }
  174. =head2 login
  175. 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.
  176. =cut
  177. sub login ($query, $input, $render_cb) {
  178. # Redirect if we actually have a logged in user.
  179. # Note to future me -- this user value is overwritten explicitly in server.psgi.
  180. # If that ever changes, you will die
  181. $query->{to} //= '/config';
  182. if ($query->{user}) {
  183. return $routes{$query->{to}}{callback}->($query,$input,$render_cb);
  184. }
  185. #Set the cookiez and issue a 302 back to ourselves if we have good creds
  186. my $postdata = _input2postdata($input);
  187. #Check and see if we have no users. If so we will just accept whatever creds are passed.
  188. my $hasusers = -f "$ENV{HOME}/.tcms/has_users";
  189. my $btnmsg = $hasusers ? "Log In" : "Register";
  190. my @headers;
  191. if ($postdata->{username} && $postdata->{password}) {
  192. if (!$hasusers) {
  193. # Make the first user
  194. Trog::Auth::useradd($postdata->{username}, $postdata->{password});
  195. File::Touch::touch("$ENV{HOME}/.tcms/has_users");
  196. }
  197. $query->{failed} = 1;
  198. my $cookie = Trog::Auth::mksession($postdata->{username}, $postdata->{password});
  199. if ($cookie) {
  200. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  201. @headers = (
  202. "Set-Cookie: tcmslogin=$cookie; HttpOnly",
  203. );
  204. $query->{failed} = 0;
  205. }
  206. }
  207. $query->{failed} //= -1;
  208. return $render_cb->('login.tx', {
  209. title => 'tCMS 2 ~ Login',
  210. to => $query->{to},
  211. failure => int( $query->{failed} ),
  212. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  213. btnmsg => $btnmsg,
  214. stylesheets => _build_themed_styles('login.css'),
  215. }, @headers);
  216. }
  217. =head2 config
  218. Renders the configuration page, or redirects you back to the login page.
  219. =cut
  220. sub config ($query, $input, $render_cb) {
  221. if (!$query->{user}) {
  222. $query->{to} = '/config';
  223. return login($query,$input,$render_cb);
  224. }
  225. my $tags = ['profile'];
  226. my $posts = _post_helper($query, $tags);
  227. my $css = _build_themed_styles('config.css');
  228. my $js = _build_themed_scripts('post.js');
  229. push(@$css, '/styles/avatars.css');
  230. $query->{failure} //= -1;
  231. return $render_cb->('config.tx', {
  232. title => 'Configure tCMS',
  233. stylesheets => $css,
  234. scripts => $js,
  235. themes => _get_themes(),
  236. data_models => _get_data_models(),
  237. current_theme => $conf->param('general.theme') // '',
  238. current_data_model => $conf->param('general.data_model') // 'DUMMY',
  239. route => '/about',
  240. category => '/about',
  241. types => ['profile'],
  242. can_edit => 1,
  243. posts => $posts,
  244. edittype => 'profile',
  245. message => $query->{message},
  246. failure => $query->{failure},
  247. to => '/config',
  248. });
  249. }
  250. sub _get_themes {
  251. my $dir = 'www/themes';
  252. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  253. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  254. closedir $dh;
  255. return \@tdirs;
  256. }
  257. sub _get_data_models {
  258. my $dir = 'lib/Trog/Data';
  259. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  260. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  261. closedir $dh;
  262. return \@dmods
  263. }
  264. =head2 config_save
  265. Implements /config/save route. Saves what little configuration we actually use to ~/.tcms/tcms.conf
  266. =cut
  267. sub config_save ($query, $input, $render_cb) {
  268. my $postdata = _input2postdata($input);
  269. $conf->param( 'general.theme', $postdata->{theme} ) if defined $postdata->{theme};
  270. $conf->param( 'general.data_model', $postdata->{data_model} ) if $postdata->{data_model};
  271. $query->{failure} = 1;
  272. $query->{message} = "Failed to save configuration!";
  273. if ($conf->save($Trog::Config::home_config)) {
  274. $query->{failure} = 0;
  275. $query->{message} = "Configuration updated succesfully.";
  276. }
  277. # 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.
  278. return config($query, $input, $render_cb);
  279. }
  280. # TODO actually do stuff
  281. sub profile ($query, $input, $render_cb) {
  282. return config($query, $input, $render_cb);
  283. }
  284. =head2 themeclone
  285. Clone a theme by copying a directory.
  286. =cut
  287. sub themeclone ($query, $input, $render_cb) {
  288. my $postdata = _input2postdata($input);
  289. my ($theme, $newtheme) = ($postdata->{theme},$postdata->{newtheme});
  290. my $themedir = 'www/themes';
  291. $query->{failure} = 1;
  292. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  293. require File::Copy::Recursive;
  294. if ($theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" )) {
  295. $query->{failure} = 0;
  296. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  297. }
  298. return config($query, $input, $render_cb);
  299. }
  300. =head2 post
  301. Display the route for making new posts.
  302. =cut
  303. sub post ($query, $input, $render_cb) {
  304. if (!$query->{user}) {
  305. $query->{to} = '/config';
  306. return login($query,$input,$render_cb);
  307. }
  308. my $tags = _coerce_array($query->{tag});
  309. my $posts = _post_helper($query, $tags);
  310. my $css = _build_themed_styles('post.css');
  311. my $js = _build_themed_scripts('post.js');
  312. push(@$css, '/styles/avatars.css');
  313. return $render_cb->('post.tx', {
  314. title => 'New Post',
  315. post_visibilities => ['public', 'private', 'unlisted'],
  316. stylesheets => $css,
  317. scripts => $js,
  318. posts => $posts,
  319. can_edit => 1,
  320. types => [qw{microblog blog file}],
  321. route => '/posts',
  322. category => '/posts',
  323. page => int($query->{page} || 1),
  324. limit => int($query->{limit} || 1),
  325. sizes => [25,50,100],
  326. edittype => $query->{type} || 'microblog',
  327. });
  328. }
  329. #TODO actually do stuff
  330. sub post_save ($query, $input, $render_cb) {
  331. return post($query, $input, $render_cb);
  332. }
  333. =head2 posts
  334. Display multi or single posts, supports RSS and pagination.
  335. =cut
  336. sub posts ($query, $input, $render_cb) {
  337. my $tags = _coerce_array($query->{tag});
  338. my $posts = _post_helper($query, $tags);
  339. return notfound($query,$input,$render_cb) unless @$posts;
  340. my $fmt = $query->{format} || '';
  341. return _rss($posts) if $fmt eq 'rss';
  342. my $processor = Text::Xslate->new(
  343. path => _dir_for_resource('posts.tx'),
  344. );
  345. my $styles = _build_themed_styles('posts.css');
  346. my $content = $processor->render('posts.tx', {
  347. title => "Posts tagged @$tags",
  348. posts => $posts,
  349. route => $query->{route},
  350. page => int($query->{page} || 1),
  351. limit => int($query->{limit} || 1),
  352. sizes => [25,50,100],
  353. rss => !$query->{id},
  354. category => $themed ? Theme::path_to_tile($query->{route}) : $query->{route},
  355. });
  356. return Trog::Routes::HTML::index($query, $input, $render_cb, $content, $styles);
  357. }
  358. sub _post_helper ($query, $tags) {
  359. my $data = Trog::Data->new($conf);
  360. return $data->get(
  361. page => int($query->{page} || 1),
  362. limit => int($query->{limit} || 25),
  363. tags => $tags,
  364. like => $query->{like},
  365. id => $query->{id},
  366. );
  367. }
  368. sub _rss ($posts) {
  369. return [200, ["Content-type: text/plain\n"], ["TODO"]];
  370. }
  371. sub _input2postdata ($input) {
  372. #Set the cookiez and issue a 302 back to ourselves if we have good creds
  373. my ($slurpee,$postdata) = ('',{});
  374. while (<$input>) { $slurpee .= $_ }
  375. $postdata = URL::Encode::url_params_mixed($slurpee) if $slurpee;
  376. return $postdata;
  377. }
  378. # Deal with Params which may or may not be arrays
  379. sub _coerce_array ($param) {
  380. my $p = $param || [];
  381. $p = [$param] if $param && (ref $param ne 'ARRAY');
  382. return $p;
  383. }
  384. sub _build_themed_styles ($style) {
  385. my @styles = ("/styles/$style");
  386. my $ts = _themed_style($style);
  387. push(@styles, $ts) if $theme_dir && -f "www/$ts";
  388. return \@styles;
  389. }
  390. sub _build_themed_scripts ($script) {
  391. my @scripts = ("/scripts/$script");
  392. my $ts = _themed_style($script);
  393. push(@scripts, $ts) if $theme_dir && -f "www/$ts";
  394. return \@scripts;
  395. }
  396. sub _pick_processor($file, $normal, $themed) {
  397. return _dir_for_resource($file) eq $template_dir ? $normal : $themed;
  398. }
  399. # Pick appropriate dir based on whether theme override exists
  400. sub _dir_for_resource ($resource) {
  401. return $theme_dir && -f "www/$theme_dir/$resource" ? $theme_dir : $template_dir;
  402. }
  403. sub _themed_style ($resource) {
  404. return _dir_for_resource("styles/$resource")."/styles/$resource";
  405. }
  406. sub _themed_script ($resource) {
  407. return _dir_for_resource("scripts/$resource")."/scripts/$resource";
  408. }
  409. 1;