HTML.pm 34 KB

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