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