HTML.pm 37 KB

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