HTML.pm 36 KB

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