HTML.pm 37 KB

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