HTML.pm 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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 HTML::SocialMeta;
  11. use Trog::Utils;
  12. use Trog::Config;
  13. use Trog::Data;
  14. my $conf = Trog::Config::get();
  15. my $template_dir = 'www/templates';
  16. my $theme_dir = '';
  17. $theme_dir = "themes/".$conf->param('general.theme') if $conf->param('general.theme') && -d "www/themes/".$conf->param('general.theme');
  18. my $td = $theme_dir ? "/$theme_dir" : '';
  19. use lib 'www';
  20. our $landing_page = 'default.tx';
  21. our $htmltitle = 'title.tx';
  22. our $midtitle = 'midtitle.tx';
  23. our $rightbar = 'rightbar.tx';
  24. our $leftbar = 'leftbar.tx';
  25. our $footbar = 'footbar.tx';
  26. # Note to maintainers: never ever remove backends from this list.
  27. # the auth => 1 is a crucial protection, even with forbidden() guards in these routes.
  28. our %routes = (
  29. default => {
  30. callback => \&Trog::Routes::HTML::setup,
  31. },
  32. '/' => {
  33. method => 'GET',
  34. callback => \&Trog::Routes::HTML::index,
  35. },
  36. #Deal with most indexDocument directives interfering with proxied requests to /
  37. '/index.html' => {
  38. method => 'GET',
  39. callback => \&Trog::Routes::HTML::index,
  40. },
  41. '/index.php' => {
  42. method => 'GET',
  43. callback => \&Trog::Routes::HTML::index,
  44. },
  45. # This should only be enabled to debug
  46. # '/setup' => {
  47. # method => 'GET',
  48. # callback => \&Trog::Routes::HTML::setup,
  49. # },
  50. '/login' => {
  51. method => 'GET',
  52. callback => \&Trog::Routes::HTML::login,
  53. },
  54. '/logout' => {
  55. method => 'GET',
  56. callback => \&Trog::Routes::HTML::logout,
  57. },
  58. '/auth' => {
  59. method => 'POST',
  60. nostatic => 1,
  61. callback => \&Trog::Routes::HTML::login,
  62. },
  63. '/post/save' => {
  64. method => 'POST',
  65. auth => 1,
  66. callback => \&Trog::Routes::HTML::post_save,
  67. },
  68. '/post/delete' => {
  69. method => 'POST',
  70. auth => 1,
  71. callback => \&Trog::Routes::HTML::post_delete,
  72. },
  73. '/themeclone' => {
  74. method => 'POST',
  75. auth => 1,
  76. callback => \&Trog::Routes::HTML::themeclone,
  77. },
  78. '/profile' => {
  79. method => 'POST',
  80. auth => 1,
  81. callback => \&Trog::Routes::HTML::profile,
  82. },
  83. '/manual' => {
  84. method => 'GET',
  85. auth => 1,
  86. callback => \&Trog::Routes::HTML::manual,
  87. },
  88. '/lib/(.*)' => {
  89. method => 'GET',
  90. auth => 1,
  91. captures => ['module'],
  92. callback => \&Trog::Routes::HTML::manual,
  93. },
  94. #TODO transform into posts?
  95. '/sitemap', => {
  96. method => 'GET',
  97. callback => \&Trog::Routes::HTML::sitemap,
  98. },
  99. '/sitemap_index.xml', => {
  100. method => 'GET',
  101. callback => \&Trog::Routes::HTML::sitemap,
  102. data => { xml => 1 },
  103. },
  104. '/sitemap_index.xml.gz', => {
  105. method => 'GET',
  106. callback => \&Trog::Routes::HTML::sitemap,
  107. data => { xml => 1, compressed => 1 },
  108. },
  109. '/sitemap/static.xml' => {
  110. method => 'GET',
  111. callback => \&Trog::Routes::HTML::sitemap,
  112. data => { xml => 1, map => 'static' },
  113. },
  114. '/sitemap/static.xml.gz' => {
  115. method => 'GET',
  116. callback => \&Trog::Routes::HTML::sitemap,
  117. data => { xml => 1, compressed => 1, map => 'static' },
  118. },
  119. '/sitemap/(.*).xml' => {
  120. method => 'GET',
  121. callback => \&Trog::Routes::HTML::sitemap,
  122. data => { xml => 1 },
  123. captures => ['map'],
  124. },
  125. '/sitemap/(.*).xml.gz' => {
  126. method => 'GET',
  127. callback => \&Trog::Routes::HTML::sitemap,
  128. data => { xml => 1, compressed => 1},
  129. captures => ['map'],
  130. },
  131. '/robots.txt' => {
  132. method => 'GET',
  133. callback => \&Trog::Routes::HTML::robots,
  134. },
  135. '/humans.txt' => {
  136. method => 'GET',
  137. callback => \&Trog::Routes::HTML::posts,
  138. data => { tag => ['about'] },
  139. },
  140. '/styles/avatars.css' => {
  141. method => 'GET',
  142. callback => \&Trog::Routes::HTML::avatars,
  143. data => { tag => ['about'] },
  144. },
  145. );
  146. #XXX these need to be fetched dynamically from all the header categories?
  147. # Is used by the sitemap, maybe just fix there
  148. my @post_aliases = qw{news blog video images audio files series about};
  149. # Grab theme routes
  150. my $themed = 0;
  151. if ($theme_dir) {
  152. my $theme_mod = "$theme_dir/routes.pm";
  153. if (-f "www/$theme_mod" ) {
  154. require $theme_mod;
  155. @routes{keys(%Theme::routes)} = values(%Theme::routes);
  156. $themed = 1;
  157. }
  158. }
  159. =head1 PRIMARY ROUTE
  160. =head2 index
  161. Implements the primary route used by all pages not behind auth.
  162. Most subsequent functions simply pass content to this function.
  163. =cut
  164. sub index ($query,$render_cb, $content = '', $i_styles = []) {
  165. $query->{theme_dir} = $td;
  166. my $processor = Text::Xslate->new(
  167. path => $template_dir,
  168. );
  169. my $t_processor;
  170. $t_processor = Text::Xslate->new(
  171. path => "www/$theme_dir/templates",
  172. ) if $theme_dir;
  173. $content ||= _pick_processor("templates/$landing_page",$processor,$t_processor)->render($landing_page,$query);
  174. my @styles = ('/styles/avatars.css');
  175. if ($theme_dir) {
  176. if ($query->{embed}) {
  177. unshift(@styles, _themed_style("embed.css")) if -f 'www/'._themed_style("embed.css");
  178. }
  179. unshift(@styles, _themed_style("screen.css")) if -f 'www/'._themed_style("screen.css");
  180. unshift(@styles, _themed_style("structure.css")) if -f 'www/'._themed_style("structure.css");
  181. }
  182. push( @styles, @$i_styles );
  183. #TODO allow theming of print css
  184. my $search_info = Trog::Data->new($conf);
  185. my @series = _get_series(0, $search_info);
  186. my $title = $query->{primary_post}{title} // $query->{title} // $Theme::default_title // 'tCMS';
  187. # Handle link "unfurling" correctly
  188. my ($default_tags, $meta_desc, $meta_tags) = _build_social_meta($query,$title);
  189. #Do embed content
  190. my $tmpl = $query->{embed} ? 'embed.tx' : 'index.tx';
  191. return $render_cb->( $tmpl, {
  192. code => $query->{code},
  193. user => $query->{user},
  194. search_lang => $search_info->lang(),
  195. search_help => $search_info->help(),
  196. route => $query->{route},
  197. domain => $query->{domain},
  198. theme_dir => $td,
  199. content => $content,
  200. title => $title,
  201. htmltitle => _pick_processor("templates/$htmltitle" ,$processor,$t_processor)->render($htmltitle,$query),
  202. midtitle => _pick_processor("templates/$midtitle" ,$processor,$t_processor)->render($midtitle,$query),
  203. rightbar => _pick_processor("templates/$rightbar" ,$processor,$t_processor)->render($rightbar,$query),
  204. leftbar => _pick_processor("templates/$leftbar" ,$processor,$t_processor)->render($leftbar,$query),
  205. footbar => _pick_processor("templates/$footbar" ,$processor,$t_processor)->render($footbar,$query),
  206. categories => \@series,
  207. stylesheets => \@styles,
  208. show_madeby => $Theme::show_madeby ? 1 : 0,
  209. embed => $query->{embed} ? 1 : 0,
  210. embed_video => $query->{primary_post}{is_video},
  211. default_tags => $default_tags,
  212. meta_desc => $meta_desc,
  213. meta_tags => $meta_tags,
  214. deflate => $query->{deflate},
  215. });
  216. }
  217. sub _build_social_meta ($query,$title) {
  218. return (undef,undef,undef) unless $query->{social_meta};
  219. my $default_tags = $Theme::default_tags;
  220. $default_tags .= ','.join(',',@{$query->{primary_post}->{tags}}) if $default_tags && $query->{primary_post}->{tags};
  221. my $meta_desc = $query->{primary_post}{data} // $Theme::description // "tCMS Site";
  222. $meta_desc = Trog::Utils::strip_and_trunc($meta_desc);
  223. my $meta_tags = '';
  224. my $card_type = 'summary';
  225. $card_type = 'featured_image' if $query->{primary_post} && $query->{primary_post}{is_image};
  226. $card_type = 'player' if $query->{primary_post} && $query->{primary_post}{is_video};
  227. my $image = $Theme::default_image ? "https://$query->{domain}/$td/$Theme::default_image" : '';
  228. $image = "https://$query->{domain}/$query->{primary_post}{preview}" if $query->{primary_post} && $query->{primary_post}{preview};
  229. $image = "https://$query->{domain}/$query->{primary_post}{href}" if $query->{primary_post} && $query->{primary_post}{is_image};
  230. my $primary_route = "https://$query->{domain}/$query->{route}";
  231. $primary_route =~ s/[\/]+/\//g;
  232. my $display_name = $Theme::display_name // 'Another tCMS Site';
  233. my $extra_tags ='';
  234. my %sopts = (
  235. site_name => $display_name,
  236. app_name => $display_name,
  237. title => $title,
  238. description => $meta_desc,
  239. url => $primary_route,
  240. );
  241. $sopts{site} = $Theme::twitter_account if $Theme::twitter_account;
  242. $sopts{image} = $image if $image;
  243. $sopts{fb_app_id} = $Theme::fb_app_id if $Theme::fb_app_id;
  244. if ($query->{primary_post} && $query->{primary_post}{is_video}) {
  245. #$sopts{player} = "$primary_route?embed=1";
  246. $sopts{player} = "https://$query->{domain}/$query->{primary_post}{href}";
  247. #XXX don't hardcode this
  248. $sopts{player_width} = 1280;
  249. $sopts{player_height} = 720;
  250. $extra_tags .= "<meta property='og:video:type' content='$query->{primary_post}{content_type}' />\n";
  251. }
  252. my $social = HTML::SocialMeta->new(%sopts);
  253. $meta_tags = eval { $social->create($card_type) };
  254. $meta_tags =~ s/content="video"/content="video:other"/mg if $meta_tags;
  255. $meta_tags .= $extra_tags if $extra_tags;
  256. print STDERR "WARNING: Theme misconfigured, social media tags will not be included\n$@\n" if $theme_dir && !$meta_tags;
  257. return ($default_tags, $meta_desc, $meta_tags);
  258. }
  259. =head1 ADMIN ROUTES
  260. These are things that issue returns other than 200, and are not directly accessible by users via any defined route.
  261. =head2 notfound, forbidden, badrequest
  262. Implements the 4XX status codes. Override templates named the same for theming this.
  263. =cut
  264. sub _generic_route ($rname, $code, $title, $query, $render_cb) {
  265. $query->{code} = $code;
  266. my $processor = Text::Xslate->new(
  267. path => _dir_for_resource("$rname.tx"),
  268. );
  269. $query->{title} = $title;
  270. my $styles = _build_themed_styles("$rname.css");
  271. my $content = $processor->render("$rname.tx", {
  272. title => $title,
  273. route => $query->{route},
  274. user => $query->{user},
  275. styles => $styles,
  276. deflate => $query->{deflate},
  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. my @series = _get_series(1);
  384. return $render_cb->('config.tx', {
  385. title => 'Configure tCMS',
  386. theme_dir => $td,
  387. stylesheets => $css,
  388. scripts => $js,
  389. categories => \@series,
  390. themes => _get_themes() || [],
  391. data_models => _get_data_models(),
  392. current_theme => $conf->param('general.theme') // '',
  393. current_data_model => $conf->param('general.data_model') // 'DUMMY',
  394. message => $query->{message},
  395. failure => $query->{failure},
  396. to => '/config',
  397. });
  398. }
  399. sub _get_series($edit=0,$search_info=0) {
  400. $search_info ||= Trog::Data->new($conf);
  401. my @series = $search_info->get(
  402. acls => [qw{public}],
  403. tags => [qw{topbar}],
  404. limit => 10,
  405. page => 1,
  406. );
  407. @series = map { $_->{local_href} = "/post$_->{local_href}"; $_ } @series if $edit;
  408. return @series;
  409. }
  410. sub _get_themes {
  411. my $dir = 'www/themes';
  412. opendir(my $dh, $dir) || do { die "Can't opendir $dir: $!" unless $!{ENOENT} };
  413. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  414. closedir $dh;
  415. return \@tdirs;
  416. }
  417. sub _get_data_models {
  418. my $dir = 'lib/Trog/Data';
  419. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  420. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  421. closedir $dh;
  422. return \@dmods
  423. }
  424. =head2 config_save
  425. Implements /config/save route. Saves what little configuration we actually use to ~/.tcms/tcms.conf
  426. =cut
  427. sub config_save ($query, $render_cb) {
  428. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  429. $conf->param( 'general.theme', $query->{theme} ) if defined $query->{theme};
  430. $conf->param( 'general.data_model', $query->{data_model} ) if $query->{data_model};
  431. $query->{failure} = 1;
  432. $query->{message} = "Failed to save configuration!";
  433. if ($conf->write($Trog::Config::home_cfg)) {
  434. $query->{failure} = 0;
  435. $query->{message} = "Configuration updated succesfully.";
  436. }
  437. #Get the PID of the parent port using lsof, send HUP
  438. my $parent = getppid;
  439. kill 'HUP', $parent;
  440. return config($query, $render_cb);
  441. }
  442. =head2 themeclone
  443. Clone a theme by copying a directory.
  444. =cut
  445. sub themeclone ($query, $render_cb) {
  446. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  447. my ($theme, $newtheme) = ($query->{theme},$query->{newtheme});
  448. my $themedir = 'www/themes';
  449. $query->{failure} = 1;
  450. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  451. require File::Copy::Recursive;
  452. if ($theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" )) {
  453. $query->{failure} = 0;
  454. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  455. }
  456. return config($query, $render_cb);
  457. }
  458. =head2 post_save
  459. Saves posts submitted via the /post pages
  460. =cut
  461. sub post_save ($query, $render_cb) {
  462. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  463. my $to = delete $query->{to};
  464. #Copy this down since it will be deleted later
  465. my $acls = $query->{acls};
  466. state $data = Trog::Data->new($conf);
  467. $query->{tags} = _coerce_array($query->{tags});
  468. # Filter bits and bobs
  469. delete $query->{primary_post};
  470. delete $query->{social_meta};
  471. delete $query->{deflate};
  472. delete $query->{acls};
  473. # Ensure there are no null tags
  474. @{$query->{tags}} = grep { defined $_ } @{$query->{tags}};
  475. $query->{failure} = $data->add($query);
  476. $query->{to} = $to;
  477. $query->{acls} = $acls;
  478. $query->{message} = $query->{failure} ? "Failed to add post!" : "Successfully added Post";
  479. delete $query->{id};
  480. return posts($query, $render_cb);
  481. }
  482. =head2 profile
  483. Saves / updates new users.
  484. =cut
  485. sub profile ($query, $render_cb) {
  486. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  487. #TODO allow users to do something OTHER than be admins
  488. if ($query->{password}) {
  489. Trog::Auth::useradd($query->{username}, $query->{password}, ['admin'] );
  490. }
  491. #Make sure it is "self-authored", redact pw
  492. $query->{user} = delete $query->{username};
  493. delete $query->{password};
  494. return post_save($query, $render_cb);
  495. }
  496. =head2 post_delete
  497. deletes posts.
  498. =cut
  499. sub post_delete ($query, $render_cb) {
  500. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  501. state $data = Trog::Data->new($conf);
  502. $query->{failure} = $data->delete($query);
  503. $query->{to} = $query->{to};
  504. $query->{message} = $query->{failure} ? "Failed to delete post $query->{id}!" : "Successfully deleted Post $query->{id}";
  505. delete $query->{id};
  506. return post($query, $render_cb);
  507. }
  508. =head2 series
  509. Series specific view, much like the users/ route
  510. Displays identified series, not all series.
  511. =cut
  512. sub series ($query, $render_cb) {
  513. my $is_admin = grep { $_ eq 'admin' } @{$query->{acls}};
  514. $query->{exclude_tags} = ['topbar'] unless $is_admin;
  515. #we are either viewed one of two ways, /series/$id or /$aclname
  516. my (undef,$aclname) = split(/\//,$query->{route});
  517. $query->{aclname} = $aclname if $aclname;
  518. #XXX I'd prefer to overload id to actually *be* the aclname...
  519. # but this way, accomodates things like the flat file time-indexing hack.
  520. # TODO I should probably have it for all posts, and make *everything* a series.
  521. # WE can then do threaded comments/posts.
  522. # That will essentially necessitate it *becoming* the ID for real.
  523. #Grab the relevant tag (aclname), then pass that to posts
  524. my @posts = _post_helper($query, [], $query->{acls});
  525. delete $query->{id};
  526. delete $query->{aclname};
  527. $query->{subhead} = $posts[0]->{data};
  528. $query->{title} = $posts[0]->{title};
  529. $query->{tag} = $posts[0]->{aclname};
  530. $query->{primary_post} = $posts[0];
  531. return posts($query,$render_cb);
  532. }
  533. =head2 avatars
  534. Returns the avatars.css. Limited to 1000 users.
  535. =cut
  536. sub avatars ($query, $render_cb) {
  537. #XXX if you have more than 1000 editors you should stop
  538. push(@{$query->{acls}}, 'public');
  539. my $tags = _coerce_array($query->{tag});
  540. $query->{limit} = 1000;
  541. my $processor = Text::Xslate->new(
  542. path => $template_dir,
  543. );
  544. my @posts = _post_helper($query, $tags, $query->{acls});
  545. my $content = $processor->render('avatars.tx', {
  546. users => \@posts,
  547. });
  548. return [200, ["Content-type" => "text/css" ],[$content]];
  549. }
  550. =head2 users
  551. Implements direct user profile view.
  552. =cut
  553. sub users ($query, $render_cb) {
  554. # Capture the username
  555. my (undef, undef, $username) = split(/\//, $query->{route});
  556. $query->{username} //= $username;
  557. push(@{$query->{acls}}, 'public');
  558. $query->{exclude_tags} = ['about'];
  559. my @posts = _post_helper({ limit => 10000 }, ['about'], $query->{acls});
  560. my @user = grep { $_->{user} eq $query->{username} } @posts;
  561. $query->{id} = $user[0]->{id};
  562. $query->{title} = $user[0]->{title};
  563. $query->{user_obj} = $user[0];
  564. $query->{primary_post} = $posts[0];
  565. return posts($query,$render_cb);
  566. }
  567. =head2 posts
  568. Display multi or single posts, supports RSS and pagination.
  569. =cut
  570. sub posts ($query, $render_cb, $direct=0) {
  571. #Process the input URI to capture tag/id
  572. $query->{route} //= $query->{to};
  573. my (undef, $tag, $id) = split(/\//, $query->{route});
  574. my $tags = _coerce_array($query->{tag});
  575. push(@$tags, $tag) if $tag && $tag ne 'posts';
  576. $query->{id} = $id if $id;
  577. my $is_admin = grep { $_ eq 'admin' } @{$query->{acls}};
  578. push(@{$query->{acls}}, 'public');
  579. push(@{$query->{acls}}, 'unlisted') if $query->{id};
  580. push(@{$query->{acls}}, 'private') if $is_admin;
  581. my @posts;
  582. if ($query->{user_obj}) {
  583. #Optimize the /users/* route
  584. @posts = ($query->{user_obj});
  585. } else {
  586. @posts = _post_helper($query, $tags, $query->{acls});
  587. }
  588. if ($query->{id}) {
  589. $query->{primary_post} = $posts[0] if @posts;
  590. }
  591. #OK, so if we have a user as the ID we found, go grab the rest of their posts
  592. if ($query->{id} && @posts && grep { $_ eq 'about'} @{$posts[0]->{tags}} ) {
  593. my $user = shift(@posts);
  594. my $id = delete $query->{id};
  595. $query->{author} = $user->{user};
  596. @posts = _post_helper($query, [], $query->{acls});
  597. @posts = grep { $_->{id} ne $id } @posts;
  598. unshift @posts, $user;
  599. }
  600. if (!$is_admin) {
  601. return notfound($query, $render_cb) unless @posts;
  602. }
  603. my $fmt = $query->{format} || '';
  604. return _rss($query,\@posts) if $fmt eq 'rss';
  605. my $processor = Text::Xslate->new(
  606. path => $template_dir,
  607. function => {
  608. render_it => sub {
  609. my ($template_string, $options) = @_;
  610. return Text::Xslate->new(
  611. # Prevent a recursive descent. If the renderer is hit again, just do nothing
  612. # XXX unfortunately if the post tries to include itself, it will die.
  613. function => {
  614. embed => sub {
  615. my ($this_id, $style) = @_;
  616. $style //= 'embed';
  617. # If instead the style is 'content', then we will only show the content w/ no formatting, and no title.
  618. return Text::Xslate::mark_raw(Trog::Routes::HTML::posts(
  619. { route => "/post/$this_id", style => $style },
  620. sub {},
  621. 1));
  622. },
  623. },
  624. )->render_string($template_string,$options);
  625. },
  626. },
  627. );
  628. # Themed header/footer for about page -- TODO maybe make this generic so we can have MESSAGE FROM JIMBO WALES everywhere
  629. my ($header,$footer);
  630. my $should_header = grep { $_ eq $query->{route} } map { "/$_" } (@post_aliases,'humans.txt');
  631. if ($should_header) {
  632. my $route = $query->{route};
  633. my %alias = ( '/humans.txt' => '/about');
  634. $route = $alias{$route} if exists $alias{$route};
  635. my $t_processor;
  636. $t_processor = Text::Xslate->new(
  637. path => "www/$theme_dir/templates",
  638. ) if $theme_dir;
  639. my $no_leading_slash = $route;
  640. $no_leading_slash =~ tr/\///d;
  641. $header = _pick_processor("templates$route\_header.tx" ,$processor,$t_processor)->render("$no_leading_slash\_header.tx", { theme_dir => $td } );
  642. $footer = _pick_processor("templates$route\_header.tx" ,$processor,$t_processor)->render("$no_leading_slash\_footer.tx", { theme_dir => $td } );
  643. }
  644. my $styles = _build_themed_styles('posts.css');
  645. #Correct page headers
  646. my $ph = $themed ? _themed_title($query->{route}) : $query->{route};
  647. $ph = $query->{title} if $query->{title};
  648. # Build page title if it wasn't set by a wrapping sub
  649. $query->{title} = "$query->{domain} : $query->{title}" if $query->{title} && $query->{domain};
  650. $query->{title} ||= @$tags && $query->{domain} ? "$query->{domain} : @$tags" : undef;
  651. #Handle paginator vars
  652. my $limit = int($query->{limit} || 25);
  653. my $now_year = (localtime(time))[5] + 1900;
  654. my $oldest_year = $now_year - 20; #XXX actually find oldest post year
  655. # Handle post style.
  656. if ($query->{style}) {
  657. undef $header;
  658. undef $footer;
  659. }
  660. my %routemap;
  661. @routemap{qw{/news /about /series /image /video /audio /files}} = qw{microblog profile series file file file file};
  662. my $edittype = $routemap{$query->{route}} // 'blog';
  663. my $older = !@posts ? 0 : $posts[-1]->{created};
  664. $query->{failure} //= -1;
  665. $query->{id} //= '';
  666. #XXX messed up data has to be fixed unfortunately
  667. @$tags = List::Util::uniq @$tags;
  668. #XXX also unsure this is actually necessary
  669. my $app = 'file';
  670. if ($query->{route}) {
  671. $app = 'image' if $query->{route} =~ m/image$/;
  672. $app = 'video' if $query->{route} =~ m/video$/;
  673. $app = 'audio' if $query->{route} =~ m/audio$/;
  674. }
  675. #Filter displaying visibility tags
  676. my @visibuddies = qw{public unlisted private};
  677. foreach my $post (@posts) {
  678. @{$post->{tags}} = grep { my $tag = $_; !grep { $tag eq $_ } @visibuddies } @{$post->{tags}};
  679. }
  680. my $aclselected = $tags->[0] || '';
  681. my @acls = map {
  682. $_->{selected} = $_->{aclname} eq $aclselected ? 'selected' : '';
  683. $_
  684. } _post_helper({}, ['series'], $query->{acls});
  685. my $content = $processor->render('posts.tx', {
  686. app => $app,
  687. acls => \@acls,
  688. can_edit => $is_admin,
  689. edittype => $edittype,
  690. post => { tags => $tags },
  691. post_visibilities => \@visibuddies,
  692. failure => $query->{failure},
  693. to => $query->{to},
  694. message => $query->{failure} ? "Failed to add post!" : "Successfully added Post as $query->{id}",
  695. direct => $direct,
  696. title => $query->{title},
  697. style => $query->{style},
  698. posts => \@posts,
  699. like => $query->{like},
  700. in_series => exists $query->{in_series} || !!($query->{route} =~ m/\/series\/\d*$/),
  701. route => $query->{route},
  702. limit => $limit,
  703. pages => scalar(@posts) == $limit,
  704. older => $older,
  705. sizes => [25,50,100],
  706. rss => !$query->{id} && !$query->{older},
  707. tiled => !$is_admin && scalar(grep { $_ eq $query->{route} } qw{/files /audio /video /image /series /about}),
  708. category => $ph,
  709. subhead => $query->{subhead},
  710. header => $header,
  711. footer => $footer,
  712. years => [reverse($oldest_year..$now_year)],
  713. months => [0..11],
  714. });
  715. return $content if $direct;
  716. return Trog::Routes::HTML::index($query, $render_cb, $content, $styles);
  717. }
  718. sub _themed_title ($path) {
  719. return $path unless %Theme::paths;
  720. return $Theme::paths{$path} ? $Theme::paths{$path} : $path;
  721. }
  722. sub _post_helper ($query, $tags, $acls) {
  723. state $data = Trog::Data->new($conf);
  724. return $data->get(
  725. older => $query->{older},
  726. page => int($query->{page} || 1),
  727. limit => int($query->{limit} || 25),
  728. tags => $tags,
  729. exclude_tags => $query->{exclude_tags},
  730. acls => $acls,
  731. aclname => $query->{aclname},
  732. like => $query->{like},
  733. author => $query->{author},
  734. id => $query->{id},
  735. version => $query->{version},
  736. );
  737. }
  738. =head2 sitemap
  739. Return the sitemap index unless the static or a set of dynamic routes is requested.
  740. We have a maximum of 99,990,000 posts we can make under this model
  741. As we have 10,000 * 10,000 posts which are indexable via the sitemap format.
  742. 1 top level index slot (10k posts) is taken by our static routes, the rest will be /posts.
  743. Passing ?xml=1 will result in an appropriate sitemap.xml instead.
  744. This is used to generate the static sitemaps as expected by search engines.
  745. Passing compressed=1 will gzip the output.
  746. =cut
  747. sub sitemap ($query, $render_cb) {
  748. my (@to_map, $is_index, $route_type);
  749. my $warning = '';
  750. $query->{map} //= '';
  751. if ($query->{map} eq 'static') {
  752. # Return the map of static routes
  753. $route_type = 'Static Routes';
  754. @to_map = grep { !defined $routes{$_}->{captures} && $_ !~ m/^default|login|auth$/ && !$routes{$_}->{auth} } keys(%routes);
  755. } elsif ( !$query->{map} ) {
  756. # Return the index instead
  757. @to_map = ('static');
  758. my $data = Trog::Data->new($conf);
  759. my $tot = $data->count();
  760. my $size = 50000;
  761. my $pages = int($tot / $size) + (($tot % $size) ? 1 : 0);
  762. # Truncate pages at 10k due to standard
  763. my $clamped = $pages > 49999 ? 49999 : $pages;
  764. $warning = "More posts than possible to represent in sitemaps & index! Old posts have been truncated." if $pages > 49999;
  765. foreach my $page ($clamped..1) {
  766. push(@to_map, "$page");
  767. }
  768. $is_index = 1;
  769. } else {
  770. $route_type = "Posts: Page $query->{map}";
  771. # Return the map of the particular range of dynamic posts
  772. $query->{limit} = 50000;
  773. $query->{page} = $query->{map};
  774. @to_map = _post_helper($query, [], ['public']);
  775. }
  776. if ( $query->{xml} ) {
  777. my $sm;
  778. my $xml_date = time();
  779. my $fmt = "xml";
  780. $fmt .= ".gz" if $query->{compressed};
  781. if ( !$query->{map}) {
  782. require WWW::SitemapIndex::XML;
  783. $sm = WWW::SitemapIndex::XML->new();
  784. foreach my $url (@to_map) {
  785. $sm->add(
  786. loc => "http://$query->{domain}/sitemap/$url.$fmt",
  787. lastmod => $xml_date,
  788. );
  789. }
  790. } else {
  791. require WWW::Sitemap::XML;
  792. $sm = WWW::Sitemap::XML->new();
  793. my $changefreq = $query->{map} eq 'static' ? 'monthly' : 'daily';
  794. foreach my $url (@to_map) {
  795. my $true_uri = "http://$query->{domain}$url";
  796. if (ref $url eq 'HASH') {
  797. my $is_user_page = grep { $_ eq 'about' } @{$url->{tags}};
  798. use Data::Dumper;
  799. print Dumper($url);
  800. $true_uri = "http://$query->{domain}/posts/$url->{id}";
  801. $true_uri = "http://$query->{domain}/users/$url->{title}" if $is_user_page;
  802. }
  803. my %data = (
  804. loc => $true_uri,
  805. lastmod => $xml_date,
  806. mobile => 1,
  807. changefreq => $changefreq,
  808. priority => 1.0,
  809. );
  810. if (ref $url eq 'HASH') {
  811. #add video & preview image if applicable
  812. $data{images} = [{
  813. loc => "http://$query->{domain}$url->{href}",
  814. caption => $url->{data},
  815. title => substr($url->{title},0,100),
  816. }] if $url->{is_image};
  817. $data{videos} = [{
  818. content_loc => "http://$query->{domain}$url->{href}",
  819. thumbnail_loc => "http://$query->{domain}$url->{preview}",
  820. title => substr($url->{title},0,100),
  821. description => $url->{data},
  822. }] if $url->{is_video};
  823. }
  824. $sm->add(%data);
  825. }
  826. }
  827. my $xml = $sm->as_xml();
  828. require IO::String;
  829. my $buf = IO::String->new();
  830. my $ct = 'application/xml';
  831. $xml->toFH($buf, 0);
  832. seek $buf, 0, 0;
  833. if ($query->{compressed}) {
  834. require IO::Compress::Gzip;
  835. my $compressed = IO::String->new();
  836. IO::Compress::Gzip::gzip($buf => $compressed);
  837. $ct = 'application/gzip';
  838. $buf = $compressed;
  839. seek $compressed, 0, 0;
  840. }
  841. return [200,["Content-type" => $ct], $buf];
  842. }
  843. @to_map = sort @to_map unless $is_index;
  844. my $processor = Text::Xslate->new(
  845. path => _dir_for_resource('sitemap.tx'),
  846. );
  847. my $styles = _build_themed_styles('sitemap.css');
  848. $query->{title} = "$query->{domain} : Sitemap";
  849. my $content = $processor->render('sitemap.tx', {
  850. title => "Site Map",
  851. to_map => \@to_map,
  852. is_index => $is_index,
  853. route_type => $route_type,
  854. route => $query->{route},
  855. });
  856. return Trog::Routes::HTML::index($query, $render_cb,$content,$styles);
  857. }
  858. sub _rss ($query,$posts) {
  859. require XML::RSS;
  860. my $rss = XML::RSS->new (version => '2.0');
  861. my $now = DateTime->from_epoch(epoch => time());
  862. $rss->channel(
  863. title => "$query->{domain}",
  864. link => "http://$query->{domain}/$query->{route}?format=rss",
  865. language => 'en', #TODO localization
  866. description => "$query->{domain} : $query->{route}",
  867. pubDate => $now,
  868. lastBuildDate => $now,
  869. );
  870. #TODO configurability
  871. $rss->image(
  872. title => $query->{domain},
  873. url => "$td/img/icon/favicon.ico",
  874. link => "http://$query->{domain}",
  875. width => 88,
  876. height => 31,
  877. description => "$query->{domain} favicon",
  878. );
  879. foreach my $post (@$posts) {
  880. my $url = "http://$query->{domain}/posts/$post->{id}";
  881. $rss->add_item(
  882. title => $post->{title},
  883. permaLink => $url,
  884. link => $url,
  885. enclosure => { url => $url, type=>"text/html" },
  886. description => "<![CDATA[$post->{data}]]>",
  887. pubDate => DateTime->from_epoch(epoch => $post->{created} ), #TODO format like Thu, 23 Aug 1999 07:00:00 GMT
  888. author => $post->{user}, #TODO translate to "email (user)" format
  889. );
  890. }
  891. require Encode;
  892. return [200, ["Content-type" => "application/rss+xml"], [Encode::encode_utf8($rss->as_string)]];
  893. }
  894. =head2 manual
  895. Implements the /manual and /lib/* routes.
  896. Basically a thin wrapper around Pod::Html.
  897. =cut
  898. sub manual ($query, $render_cb) {
  899. require Pod::Html;
  900. require Capture::Tiny;
  901. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  902. #Fix links from Pod::HTML
  903. $query->{module} =~ s/\.html$//g if $query->{module};
  904. my $infile = $query->{module} ? "$query->{module}.pm" : 'tCMS/Manual.pod';
  905. return notfound($query,$render_cb) unless -f "lib/$infile";
  906. my $content = capture { Pod::Html::pod2html(qw{--podpath=lib --podroot=.},"--infile=lib/$infile") };
  907. my @series = _get_series(1);
  908. return $render_cb->('manual.tx', {
  909. title => 'tCMS Manual',
  910. theme_dir => $td,
  911. content => $content,
  912. categories => \@series,
  913. stylesheets => _build_themed_styles('post.css'),
  914. });
  915. }
  916. # Deal with Params which may or may not be arrays
  917. sub _coerce_array ($param) {
  918. my $p = $param || [];
  919. $p = [$param] if $param && (ref $param ne 'ARRAY');
  920. return $p;
  921. }
  922. sub _build_themed_styles ($style) {
  923. my @styles;
  924. @styles = ("/styles/$style") if -f "www/styles/$style";
  925. my $ts = _themed_style($style);
  926. push(@styles, $ts) if $theme_dir && -f "www/$ts";
  927. return \@styles;
  928. }
  929. sub _build_themed_scripts ($script) {
  930. my @scripts = ("/scripts/$script");
  931. my $ts = _themed_style($script);
  932. push(@scripts, $ts) if $theme_dir && -f "www/$ts";
  933. return \@scripts;
  934. }
  935. sub _pick_processor($file, $normal, $themed) {
  936. return _dir_for_resource($file) eq $template_dir ? $normal : $themed;
  937. }
  938. # Pick appropriate dir based on whether theme override exists
  939. sub _dir_for_resource ($resource) {
  940. return $theme_dir && -f "www/$theme_dir/$resource" ? $theme_dir : $template_dir;
  941. }
  942. sub _themed_style ($resource) {
  943. return _dir_for_resource("styles/$resource")."/styles/$resource";
  944. }
  945. sub _themed_script ($resource) {
  946. return _dir_for_resource("scripts/$resource")."/scripts/$resource";
  947. }
  948. 1;