HTML.pm 34 KB

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