HTML.pm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. # TODO Things which should be themable
  15. our $landing_page = 'default.tx';
  16. our $htmltitle = 'title.tx';
  17. our $midtitle = 'midtitle.tx';
  18. our $rightbar = 'rightbar.tx';
  19. our $leftbar = 'leftbar.tx';
  20. our $footbar = 'footbar.tx';
  21. our %routes = (
  22. default => {
  23. callback => \&Trog::Routes::HTML::setup,
  24. },
  25. '/' => {
  26. method => 'GET',
  27. callback => \&Trog::Routes::HTML::index,
  28. },
  29. # This should only be enabled to debug
  30. # '/setup' => {
  31. # method => 'GET',
  32. # callback => \&Trog::Routes::HTML::setup,
  33. # },
  34. '/login' => {
  35. method => 'GET',
  36. callback => \&Trog::Routes::HTML::login,
  37. },
  38. '/auth' => {
  39. method => 'POST',
  40. nostatic => 1,
  41. callback => \&Trog::Routes::HTML::login,
  42. },
  43. '/config' => {
  44. method => 'GET',
  45. auth => 1,
  46. callback => \&Trog::Routes::HTML::config,
  47. },
  48. '/config/save' => {
  49. method => 'POST',
  50. auth => 1,
  51. callback => \&Trog::Routes::HTML::config_save,
  52. },
  53. '/post' => {
  54. method => 'GET',
  55. auth => 1,
  56. callback => \&Trog::Routes::HTML::post,
  57. },
  58. '/post/save' => {
  59. method => 'POST',
  60. auth => 1,
  61. callback => \&Trog::Routes::HTML::post,
  62. },
  63. '/posts/(.*)' => {
  64. method => 'GET',
  65. auth => 1,
  66. callback => \&Trog::Routes::HTML::posts,
  67. captures => ['id'],
  68. },
  69. '/posts' => {
  70. method => 'GET',
  71. callback => \&Trog::Routes::HTML::posts,
  72. },
  73. '/profile' => {
  74. method => 'POST',
  75. auth => 1,
  76. callback => \&Trog::Routes::HTML::profile,
  77. },
  78. '/themeclone' => {
  79. method => 'POST',
  80. auth => 1,
  81. callback => \&Trog::Routes::HTML::themeclone,
  82. },
  83. );
  84. # Build aliases for /post with extra data
  85. my @post_aliases = qw{news blog image video audio about files};
  86. @routes{map { "/$_" } @post_aliases} = map { my %copy = %{$routes{'/posts'}}; $copy{data}{tag} = [$_]; \%copy } @post_aliases;
  87. # Build aliases for /post/(.*) with extra data
  88. @routes{map { "/$_/(.*)" } @post_aliases} = map { my %copy = %{$routes{'/posts/(.*)'}}; \%copy } @post_aliases;
  89. # Grab theme routes
  90. my $themed = 0;
  91. if ($theme_dir) {
  92. my $theme_mod = "$theme_dir/routes.pm";
  93. if (-f "www/$theme_mod" ) {
  94. require $theme_mod;
  95. @routes{keys(%Theme::routes)} = values(%Theme::routes);
  96. $themed = 1;
  97. }
  98. }
  99. # TODO build a sitemap.xml based on the above routing table, and robots.txt
  100. sub index ($query, $input, $render_cb, $content = '', $i_styles = []) {
  101. $query->{theme_dir} = $theme_dir || '';
  102. my $processor = Text::Xslate->new(
  103. path => $template_dir,
  104. );
  105. my $t_processor;
  106. $t_processor = Text::Xslate->new(
  107. path => "www/$theme_dir/templates",
  108. ) if $theme_dir;
  109. $content ||= _pick_processor($rightbar,$processor,$t_processor)->render($landing_page,$query);
  110. my @styles = ('/styles/avatars.css'); #TODO generate file for users
  111. if ($theme_dir) {
  112. unshift(@styles, _themed_style("screen.css")) if -f 'www/'._themed_style("screen.css");
  113. unshift(@styles, _themed_style("structure.css")) if -f 'www/'._themed_style("structure.css");
  114. }
  115. push( @styles, @$i_styles);
  116. #TODO allow theming of print css
  117. my $search_info = Trog::Data->new($conf);
  118. return $render_cb->('index.tx',{
  119. code => $query->{code},
  120. user => $query->{user},
  121. search_lang => $search_info->{lang},
  122. search_help => $search_info->{help},
  123. route => $query->{route},
  124. theme_dir => $theme_dir,
  125. content => $content,
  126. title => $conf->param('general.title'), #TODO control in theme instead
  127. htmltitle => _pick_processor("templates/$htmltitle" ,$processor,$t_processor)->render($htmltitle,$query),
  128. midtitle => _pick_processor("templates/$midtitle" ,$processor,$t_processor)->render($midtitle,$query),
  129. rightbar => _pick_processor("templates/$rightbar" ,$processor,$t_processor)->render($rightbar,$query),
  130. leftbar => _pick_processor("templates/$leftbar" ,$processor,$t_processor)->render($leftbar,$query),
  131. footbar => _pick_processor("templates/$footbar" ,$processor,$t_processor)->render($footbar,$query),
  132. stylesheets => \@styles,
  133. });
  134. }
  135. =head1 ADMIN ROUTES
  136. These are things that issue returns other than 200, and are not directly accessible by users via any defined route.
  137. =cut
  138. sub notfound ($query,$input,$render_cb) {
  139. $query->{code} = 404;
  140. my $processor = Text::Xslate->new(
  141. path => _dir_for_resource('notfound.tx'),
  142. );
  143. my $styles = _build_themed_styles('notfound.css');
  144. my $content = $processor->render('notfound.tx', {
  145. title => "Return to Sender, Address unknown",
  146. route => $query->{route},
  147. });
  148. return Trog::Routes::HTML::index($query, $input, $render_cb, $content, $styles);
  149. }
  150. =head1 NORMAL ROUTES
  151. These are expected to either return a 200, or redirect to something which does.
  152. =cut
  153. sub setup ($query, $input, $render_cb) {
  154. File::Touch::touch("$ENV{HOME}/.tcms/setup");
  155. return $render_cb->('notconfigured.tx', {
  156. title => 'tCMS Requires Setup to Continue...',
  157. stylesheets => _build_themed_styles('notconfigured.css'),
  158. });
  159. }
  160. sub login ($query, $input, $render_cb) {
  161. # Redirect if we actually have a logged in user.
  162. # Note to future me -- this user value is overwritten explicitly in server.psgi.
  163. # If that ever changes, you will die
  164. $query->{to} //= '/config';
  165. if ($query->{user}) {
  166. return $routes{$query->{to}}{callback}->($query,$input,$render_cb);
  167. }
  168. #Set the cookiez and issue a 302 back to ourselves if we have good creds
  169. my $postdata = _input2postdata($input);
  170. #Check and see if we have no users. If so we will just accept whatever creds are passed.
  171. my $hasusers = -f "$ENV{HOME}/.tcms/has_users";
  172. my $btnmsg = $hasusers ? "Log In" : "Register";
  173. my @headers;
  174. if ($postdata->{username} && $postdata->{password}) {
  175. if (!$hasusers) {
  176. # Make the first user
  177. Trog::Auth::useradd($postdata->{username}, $postdata->{password});
  178. File::Touch::touch("$ENV{HOME}/.tcms/has_users");
  179. }
  180. $query->{failed} = 1;
  181. my $cookie = Trog::Auth::mksession($postdata->{username}, $postdata->{password});
  182. if ($cookie) {
  183. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  184. @headers = (
  185. "Set-Cookie: tcmslogin=$cookie; HttpOnly",
  186. );
  187. $query->{failed} = 0;
  188. }
  189. }
  190. $query->{failed} //= -1;
  191. return $render_cb->('login.tx', {
  192. title => 'tCMS 2 ~ Login',
  193. to => $query->{to},
  194. failure => int( $query->{failed} ),
  195. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  196. btnmsg => $btnmsg,
  197. stylesheets => _build_themed_styles('login.css'),
  198. }, @headers);
  199. }
  200. sub config ($query, $input, $render_cb) {
  201. if (!$query->{user}) {
  202. $query->{to} = '/config';
  203. return login($query,$input,$render_cb);
  204. }
  205. my $tags = ['profile'];
  206. my $posts = _post_helper($query, $tags);
  207. my $css = _build_themed_styles('config.css');
  208. my $js = _build_themed_scripts('post.js');
  209. push(@$css, '/styles/avatars.css');
  210. $query->{failure} //= -1;
  211. return $render_cb->('config.tx', {
  212. title => 'Configure tCMS',
  213. stylesheets => $css,
  214. scripts => $js,
  215. themes => _get_themes(),
  216. data_models => _get_data_models(),
  217. current_theme => $conf->param('general.theme'),
  218. current_data_model => $conf->param('general.data_model'),
  219. route => '/about',
  220. category => '/about',
  221. types => ['profile'],
  222. can_edit => 1,
  223. posts => $posts,
  224. edittype => 'profile',
  225. message => $query->{message},
  226. failure => $query->{failure},
  227. to => '/config',
  228. });
  229. }
  230. sub _get_themes {
  231. my $dir = 'www/themes';
  232. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  233. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  234. closedir $dh;
  235. return \@tdirs;
  236. }
  237. sub _get_data_models {
  238. my $dir = 'lib/Trog/Data';
  239. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  240. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  241. closedir $dh;
  242. return \@dmods
  243. }
  244. sub config_save ($query, $input, $render_cb) {
  245. my $postdata = _input2postdata($input);
  246. $conf->param( 'general.theme', $postdata->{theme} ) if defined $postdata->{theme};
  247. $conf->param( 'general.data_model', $postdata->{data_model} ) if $postdata->{data_model};
  248. $query->{failure} = 1;
  249. $query->{message} = "Failed to save configuration!";
  250. if ($conf->save()) {
  251. $query->{failure} = 0;
  252. $query->{message} = "Configuration updated succesfully.";
  253. }
  254. # 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.
  255. return config($query, $input, $render_cb);
  256. }
  257. # TODO actually do stuff
  258. sub profile ($query, $input, $render_cb) {
  259. return config($query, $input, $render_cb);
  260. }
  261. sub themeclone ($query, $input, $render_cb) {
  262. my $postdata = _input2postdata($input);
  263. my ($theme, $newtheme) = ($postdata->{theme},$postdata->{newtheme});
  264. my $themedir = 'www/themes';
  265. $query->{failure} = 1;
  266. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  267. require File::Copy::Recursive;
  268. if ($theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" )) {
  269. $query->{failure} = 0;
  270. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  271. }
  272. return config($query, $input, $render_cb);
  273. }
  274. sub post ($query, $input, $render_cb) {
  275. if (!$query->{user}) {
  276. $query->{to} = '/config';
  277. return login($query,$input,$render_cb);
  278. }
  279. my $tags = _coerce_array($query->{tag});
  280. my $posts = _post_helper($query, $tags);
  281. my $css = _build_themed_styles('post.css');
  282. my $js = _build_themed_scripts('post.js');
  283. push(@$css, '/styles/avatars.css');
  284. return $render_cb->('post.tx', {
  285. title => 'New Post',
  286. stylesheets => $css,
  287. scripts => $js,
  288. posts => $posts,
  289. can_edit => 1,
  290. types => [qw{microblog blog file}],
  291. route => '/posts',
  292. category => '/posts',
  293. page => int($query->{page} || 1),
  294. limit => int($query->{limit} || 1),
  295. sizes => [25,50,100],
  296. edittype => $query->{type} || 'microblog',
  297. });
  298. }
  299. sub post_save ($query, $input, $render_cb) {
  300. return post($query, $input, $render_cb);
  301. }
  302. sub posts ($query, $input, $render_cb) {
  303. my $tags = _coerce_array($query->{tag});
  304. my $posts = _post_helper($query, $tags);
  305. return notfound($query,$input,$render_cb) unless @$posts;
  306. my $fmt = $query->{format} || '';
  307. return _rss($posts) if $fmt eq 'rss';
  308. my $processor = Text::Xslate->new(
  309. path => _dir_for_resource('posts.tx'),
  310. );
  311. my $styles = _build_themed_styles('posts.css');
  312. my $content = $processor->render('posts.tx', {
  313. title => "Posts tagged @$tags",
  314. posts => $posts,
  315. route => $query->{route},
  316. page => int($query->{page} || 1),
  317. limit => int($query->{limit} || 1),
  318. sizes => [25,50,100],
  319. rss => !$query->{id},
  320. category => $themed ? Theme::path_to_tile($query->{route}) : $query->{route},
  321. });
  322. return Trog::Routes::HTML::index($query, $input, $render_cb, $content, $styles);
  323. }
  324. sub _post_helper ($query, $tags) {
  325. my $data = Trog::Data->new($conf);
  326. return $data->get(
  327. page => int($query->{page} || 1),
  328. limit => int($query->{limit} || 25),
  329. tags => $tags,
  330. like => $query->{like},
  331. id => $query->{id},
  332. );
  333. }
  334. sub _rss ($posts) {
  335. return [200, ["Content-type: text/plain\n"], ["TODO"]];
  336. }
  337. sub _input2postdata ($input) {
  338. #Set the cookiez and issue a 302 back to ourselves if we have good creds
  339. my ($slurpee,$postdata) = ('',{});
  340. while (<$input>) { $slurpee .= $_ }
  341. $postdata = URL::Encode::url_params_mixed($slurpee) if $slurpee;
  342. return $postdata;
  343. }
  344. # Deal with Params which may or may not be arrays
  345. sub _coerce_array ($param) {
  346. my $p = $param || [];
  347. $p = [$param] if $param && (ref $param ne 'ARRAY');
  348. return $p;
  349. }
  350. sub _build_themed_styles ($style) {
  351. my @styles = ("/styles/$style");
  352. my $ts = _themed_style($style);
  353. push(@styles, $ts) if $theme_dir && -f "www/$ts";
  354. return \@styles;
  355. }
  356. sub _build_themed_scripts ($script) {
  357. my @scripts = ("/scripts/$script");
  358. my $ts = _themed_style($script);
  359. push(@scripts, $ts) if $theme_dir && -f "www/$ts";
  360. return \@scripts;
  361. }
  362. sub _pick_processor($file, $normal, $themed) {
  363. return _dir_for_resource($file) eq $template_dir ? $normal : $themed;
  364. }
  365. # Pick appropriate dir based on whether theme override exists
  366. sub _dir_for_resource ($resource) {
  367. return $theme_dir && -f "www/$theme_dir/$resource" ? $theme_dir : $template_dir;
  368. }
  369. sub _themed_style ($resource) {
  370. return _dir_for_resource("styles/$resource")."/styles/$resource";
  371. }
  372. sub _themed_script ($resource) {
  373. return _dir_for_resource("scripts/$resource")."/scripts/$resource";
  374. }
  375. 1;