HTML.pm 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  436. $conf->param( 'general.theme', $query->{theme} ) if defined $query->{theme};
  437. $conf->param( 'general.data_model', $query->{data_model} ) if $query->{data_model};
  438. $query->{failure} = 1;
  439. $query->{message} = "Failed to save configuration!";
  440. if ($conf->write($Trog::Config::home_cfg)) {
  441. $query->{failure} = 0;
  442. $query->{message} = "Configuration updated succesfully.";
  443. }
  444. #Get the PID of the parent port using lsof, send HUP
  445. my $parent = getppid;
  446. kill 'HUP', $parent;
  447. return config($query, $render_cb);
  448. }
  449. =head2 themeclone
  450. Clone a theme by copying a directory.
  451. =cut
  452. sub themeclone ($query, $render_cb) {
  453. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  454. my ($theme, $newtheme) = ($query->{theme},$query->{newtheme});
  455. my $themedir = 'www/themes';
  456. $query->{failure} = 1;
  457. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  458. require File::Copy::Recursive;
  459. if ($theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" )) {
  460. $query->{failure} = 0;
  461. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  462. }
  463. return config($query, $render_cb);
  464. }
  465. =head2 post_save
  466. Saves posts submitted via the /post pages
  467. =cut
  468. sub post_save ($query, $render_cb) {
  469. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  470. my $to = delete $query->{to};
  471. #Copy this down since it will be deleted later
  472. my $acls = $query->{acls};
  473. state $data = Trog::Data->new($conf);
  474. $query->{tags} = _coerce_array($query->{tags});
  475. # Filter bits and bobs
  476. delete $query->{primary_post};
  477. delete $query->{social_meta};
  478. delete $query->{deflate};
  479. delete $query->{acls};
  480. # Ensure there are no null tags
  481. @{$query->{tags}} = grep { defined $_ } @{$query->{tags}};
  482. $query->{failure} = $data->add($query);
  483. $query->{to} = $to;
  484. $query->{acls} = $acls;
  485. $query->{message} = $query->{failure} ? "Failed to add post!" : "Successfully added Post";
  486. delete $query->{id};
  487. return posts($query, $render_cb);
  488. }
  489. =head2 profile
  490. Saves / updates new users.
  491. =cut
  492. sub profile ($query, $render_cb) {
  493. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  494. #TODO allow users to do something OTHER than be admins
  495. if ($query->{password}) {
  496. Trog::Auth::useradd($query->{username}, $query->{password}, ['admin'] );
  497. }
  498. #Make sure it is "self-authored", redact pw
  499. $query->{user} = delete $query->{username};
  500. delete $query->{password};
  501. return post_save($query, $render_cb);
  502. }
  503. =head2 post_delete
  504. deletes posts.
  505. =cut
  506. sub post_delete ($query, $render_cb) {
  507. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  508. state $data = Trog::Data->new($conf);
  509. $query->{failure} = $data->delete($query);
  510. $query->{to} = $query->{to};
  511. $query->{message} = $query->{failure} ? "Failed to delete post $query->{id}!" : "Successfully deleted Post $query->{id}";
  512. delete $query->{id};
  513. return post($query, $render_cb);
  514. }
  515. =head2 series
  516. Series specific view, much like the users/ route
  517. Displays identified series, not all series.
  518. =cut
  519. sub series ($query, $render_cb) {
  520. my $is_admin = grep { $_ eq 'admin' } @{$query->{acls}};
  521. $query->{exclude_tags} = ['topbar'] unless $is_admin;
  522. #we are either viewed one of two ways, /series/$id or /$aclname
  523. my (undef,$aclname) = split(/\//,$query->{route});
  524. $query->{aclname} = $aclname if $aclname;
  525. #XXX I'd prefer to overload id to actually *be* the aclname...
  526. # but this way, accomodates things like the flat file time-indexing hack.
  527. # TODO I should probably have it for all posts, and make *everything* a series.
  528. # WE can then do threaded comments/posts.
  529. # That will essentially necessitate it *becoming* the ID for real.
  530. #Grab the relevant tag (aclname), then pass that to posts
  531. my @posts = _post_helper($query, [], $query->{acls});
  532. delete $query->{id};
  533. delete $query->{aclname};
  534. $query->{subhead} = $posts[0]->{data};
  535. $query->{title} = $posts[0]->{title};
  536. $query->{tag} = $posts[0]->{aclname};
  537. $query->{primary_post} = $posts[0];
  538. return posts($query,$render_cb);
  539. }
  540. =head2 avatars
  541. Returns the avatars.css. Limited to 1000 users.
  542. =cut
  543. sub avatars ($query, $render_cb) {
  544. #XXX if you have more than 1000 editors you should stop
  545. push(@{$query->{acls}}, 'public');
  546. my $tags = _coerce_array($query->{tag});
  547. $query->{limit} = 1000;
  548. my $processor = Text::Xslate->new(
  549. path => $template_dir,
  550. );
  551. my @posts = _post_helper($query, $tags, $query->{acls});
  552. my $content = $processor->render('avatars.tx', {
  553. users => \@posts,
  554. });
  555. return [200, ["Content-type" => "text/css" ],[$content]];
  556. }
  557. =head2 users
  558. Implements direct user profile view.
  559. =cut
  560. sub users ($query, $render_cb) {
  561. push(@{$query->{acls}}, 'public');
  562. my @posts = _post_helper({ limit => 10000 }, ['about'], $query->{acls});
  563. my @user = grep { $_->{user} eq $query->{username} } @posts;
  564. $query->{id} = $user[0]->{id};
  565. $query->{title} = $user[0]->{title};
  566. $query->{user_obj} = $user[0];
  567. $query->{primary_post} = $posts[0];
  568. return posts($query,$render_cb);
  569. }
  570. =head2 posts
  571. Display multi or single posts, supports RSS and pagination.
  572. =cut
  573. sub posts ($query, $render_cb, $direct=0) {
  574. #Process the input URI to capture tag/id
  575. $query->{route} //= $query->{to};
  576. my (undef, $tag, $id) = split(/\//, $query->{route});
  577. my $tags = _coerce_array($query->{tag});
  578. push(@$tags, $tag) if $tag && $tag ne 'posts';
  579. $query->{id} = $id if $id;
  580. my $is_admin = grep { $_ eq 'admin' } @{$query->{acls}};
  581. push(@{$query->{acls}}, 'public');
  582. push(@{$query->{acls}}, 'unlisted') if $query->{id};
  583. push(@{$query->{acls}}, 'private') if $is_admin;
  584. my @posts;
  585. if ($query->{user_obj}) {
  586. #Optimize the /users/* route
  587. @posts = ($query->{user_obj});
  588. } else {
  589. @posts = _post_helper($query, $tags, $query->{acls});
  590. }
  591. if ($query->{id}) {
  592. $query->{primary_post} = $posts[0] if @posts;
  593. }
  594. #OK, so if we have a user as the ID we found, go grab the rest of their posts
  595. if ($query->{id} && @posts && grep { $_ eq 'about'} @{$posts[0]->{tags}} ) {
  596. my $user = shift(@posts);
  597. my $id = delete $query->{id};
  598. $query->{author} = $user->{user};
  599. @posts = _post_helper($query, [], $query->{acls});
  600. @posts = grep { $_->{id} ne $id } @posts;
  601. unshift @posts, $user;
  602. }
  603. if (!$is_admin) {
  604. return notfound($query, $render_cb) unless @posts;
  605. }
  606. my $fmt = $query->{format} || '';
  607. return _rss($query,\@posts) if $fmt eq 'rss';
  608. my $processor = Text::Xslate->new(
  609. path => $template_dir,
  610. function => {
  611. render_it => sub {
  612. my ($template_string, $options) = @_;
  613. return Text::Xslate->new(
  614. # Prevent a recursive descent. If the renderer is hit again, just do nothing
  615. # XXX unfortunately if the post tries to include itself, it will die.
  616. function => {
  617. embed => sub {
  618. my ($this_id, $style) = @_;
  619. $style //= 'embed';
  620. # If instead the style is 'content', then we will only show the content w/ no formatting, and no title.
  621. return Text::Xslate::mark_raw(Trog::Routes::HTML::posts(
  622. { route => "/post/$this_id", style => $style },
  623. sub {},
  624. 1));
  625. },
  626. },
  627. )->render_string($template_string,$options);
  628. },
  629. },
  630. );
  631. # Themed header/footer for about page -- TODO maybe make this generic so we can have MESSAGE FROM JIMBO WALES everywhere
  632. my ($header,$footer);
  633. my $should_header = grep { $_ eq $query->{route} } map { "/$_" } (@post_aliases,'humans.txt');
  634. if ($should_header) {
  635. my $route = $query->{route};
  636. my %alias = ( '/humans.txt' => '/about');
  637. $route = $alias{$route} if exists $alias{$route};
  638. my $t_processor;
  639. $t_processor = Text::Xslate->new(
  640. path => "www/$theme_dir/templates",
  641. ) if $theme_dir;
  642. my $no_leading_slash = $route;
  643. $no_leading_slash =~ tr/\///d;
  644. $header = _pick_processor("templates$route\_header.tx" ,$processor,$t_processor)->render("$no_leading_slash\_header.tx", { theme_dir => $td } );
  645. $footer = _pick_processor("templates$route\_header.tx" ,$processor,$t_processor)->render("$no_leading_slash\_footer.tx", { theme_dir => $td } );
  646. }
  647. my $styles = _build_themed_styles('posts.css');
  648. #Correct page headers
  649. my $ph = $themed ? _themed_title($query->{route}) : $query->{route};
  650. $ph = $query->{title} if $query->{title};
  651. # Build page title if it wasn't set by a wrapping sub
  652. $query->{title} = "$query->{domain} : $query->{title}" if $query->{title} && $query->{domain};
  653. $query->{title} ||= @$tags && $query->{domain} ? "$query->{domain} : @$tags" : undef;
  654. #Handle paginator vars
  655. my $limit = int($query->{limit} || 25);
  656. my $now_year = (localtime(time))[5] + 1900;
  657. my $oldest_year = $now_year - 20; #XXX actually find oldest post year
  658. # Handle post style.
  659. if ($query->{style}) {
  660. undef $header;
  661. undef $footer;
  662. }
  663. my %routemap;
  664. @routemap{qw{/news /about /series /image /video /audio /files}} = qw{microblog profile series file file file file};
  665. my $edittype = $routemap{$query->{route}} // 'blog';
  666. my $older = !@posts ? 0 : $posts[-1]->{created};
  667. $query->{failure} //= -1;
  668. $query->{id} //= '';
  669. #XXX messed up data has to be fixed unfortunately
  670. @$tags = List::Util::uniq @$tags;
  671. #XXX also unsure this is actually necessary
  672. my $app = 'file';
  673. if ($query->{route}) {
  674. $app = 'image' if $query->{route} =~ m/image$/;
  675. $app = 'video' if $query->{route} =~ m/video$/;
  676. $app = 'audio' if $query->{route} =~ m/audio$/;
  677. }
  678. #Filter displaying visibility tags
  679. my @visibuddies = qw{public unlisted private};
  680. foreach my $post (@posts) {
  681. @{$post->{tags}} = grep { my $tag = $_; !grep { $tag eq $_ } @visibuddies } @{$post->{tags}};
  682. }
  683. my $aclselected = $tags->[0] || '';
  684. my @acls = map {
  685. $_->{selected} = $_->{aclname} eq $aclselected ? 'selected' : '';
  686. $_
  687. } _post_helper({}, ['series'], $query->{acls});
  688. my $content = $processor->render('posts.tx', {
  689. app => $app,
  690. acls => \@acls,
  691. can_edit => $is_admin,
  692. edittype => $edittype,
  693. post => { tags => $tags },
  694. post_visibilities => \@visibuddies,
  695. failure => $query->{failure},
  696. to => $query->{to},
  697. message => $query->{failure} ? "Failed to add post!" : "Successfully added Post as $query->{id}",
  698. direct => !!$id,
  699. title => $query->{title},
  700. style => $query->{style},
  701. posts => \@posts,
  702. like => $query->{like},
  703. in_series => exists $query->{in_series} || !!($query->{route} =~ m/\/series\/\d*$/),
  704. route => $query->{route},
  705. limit => $limit,
  706. pages => scalar(@posts) == $limit,
  707. older => $older,
  708. sizes => [25,50,100],
  709. rss => !$query->{id} && !$query->{older},
  710. tiled => !$is_admin && scalar(grep { $_ eq $query->{route} } qw{/files /audio /video /image /series /about}),
  711. category => $ph,
  712. subhead => $query->{subhead},
  713. header => $header,
  714. footer => $footer,
  715. years => [reverse($oldest_year..$now_year)],
  716. months => [0..11],
  717. });
  718. return $content if $direct;
  719. return Trog::Routes::HTML::index($query, $render_cb, $content, $styles);
  720. }
  721. sub _themed_title ($path) {
  722. return $path unless %Theme::paths;
  723. return $Theme::paths{$path} ? $Theme::paths{$path} : $path;
  724. }
  725. sub _post_helper ($query, $tags, $acls) {
  726. state $data = Trog::Data->new($conf);
  727. return $data->get(
  728. older => $query->{older},
  729. page => int($query->{page} || 1),
  730. limit => int($query->{limit} || 25),
  731. tags => $tags,
  732. exclude_tags => $query->{exclude_tags},
  733. acls => $acls,
  734. aclname => $query->{aclname},
  735. like => $query->{like},
  736. author => $query->{author},
  737. id => $query->{id},
  738. version => $query->{version},
  739. );
  740. }
  741. =head2 sitemap
  742. Return the sitemap index unless the static or a set of dynamic routes is requested.
  743. We have a maximum of 99,990,000 posts we can make under this model
  744. As we have 10,000 * 10,000 posts which are indexable via the sitemap format.
  745. 1 top level index slot (10k posts) is taken by our static routes, the rest will be /posts.
  746. Passing ?xml=1 will result in an appropriate sitemap.xml instead.
  747. This is used to generate the static sitemaps as expected by search engines.
  748. Passing compressed=1 will gzip the output.
  749. =cut
  750. sub sitemap ($query, $render_cb) {
  751. my (@to_map, $is_index, $route_type);
  752. my $warning = '';
  753. $query->{map} //= '';
  754. if ($query->{map} eq 'static') {
  755. # Return the map of static routes
  756. $route_type = 'Static Routes';
  757. @to_map = grep { !defined $routes{$_}->{captures} && $_ !~ m/^default|login|auth$/ && !$routes{$_}->{auth} } keys(%routes);
  758. } elsif ( !$query->{map} ) {
  759. # Return the index instead
  760. @to_map = ('static');
  761. my $data = Trog::Data->new($conf);
  762. my $tot = $data->count();
  763. my $size = 50000;
  764. my $pages = int($tot / $size) + (($tot % $size) ? 1 : 0);
  765. # Truncate pages at 10k due to standard
  766. my $clamped = $pages > 49999 ? 49999 : $pages;
  767. $warning = "More posts than possible to represent in sitemaps & index! Old posts have been truncated." if $pages > 49999;
  768. foreach my $page ($clamped..1) {
  769. push(@to_map, "$page");
  770. }
  771. $is_index = 1;
  772. } else {
  773. $route_type = "Posts: Page $query->{map}";
  774. # Return the map of the particular range of dynamic posts
  775. $query->{limit} = 50000;
  776. $query->{page} = $query->{map};
  777. @to_map = _post_helper($query, [], ['public']);
  778. }
  779. if ( $query->{xml} ) {
  780. my $sm;
  781. my $xml_date = time();
  782. my $fmt = "xml";
  783. $fmt .= ".gz" if $query->{compressed};
  784. if ( !$query->{map}) {
  785. require WWW::SitemapIndex::XML;
  786. $sm = WWW::SitemapIndex::XML->new();
  787. foreach my $url (@to_map) {
  788. $sm->add(
  789. loc => "http://$query->{domain}/sitemap/$url.$fmt",
  790. lastmod => $xml_date,
  791. );
  792. }
  793. } else {
  794. require WWW::Sitemap::XML;
  795. $sm = WWW::Sitemap::XML->new();
  796. my $changefreq = $query->{map} eq 'static' ? 'monthly' : 'daily';
  797. foreach my $url (@to_map) {
  798. my $true_uri = "http://$query->{domain}$url";
  799. $true_uri = "http://$query->{domain}/posts/$url->{id}" if ref $url eq 'HASH';
  800. my %data = (
  801. loc => $true_uri,
  802. lastmod => $xml_date,
  803. mobile => 1,
  804. changefreq => $changefreq,
  805. priority => 1.0,
  806. );
  807. if (ref $url eq 'HASH') {
  808. #add video & preview image if applicable
  809. $data{images} = [{
  810. loc => "http://$query->{domain}$url->{href}",
  811. caption => $url->{data},
  812. title => substr($url->{title},0,100),
  813. }] if $url->{is_image};
  814. $data{videos} = [{
  815. content_loc => "http://$query->{domain}$url->{href}",
  816. thumbnail_loc => "http://$query->{domain}$url->{preview}",
  817. title => substr($url->{title},0,100),
  818. description => $url->{data},
  819. }] if $url->{is_video};
  820. }
  821. $sm->add(%data);
  822. }
  823. }
  824. my $xml = $sm->as_xml();
  825. require IO::String;
  826. my $buf = IO::String->new();
  827. my $ct = 'application/xml';
  828. $xml->toFH($buf, 0);
  829. seek $buf, 0, 0;
  830. if ($query->{compressed}) {
  831. require IO::Compress::Gzip;
  832. my $compressed = IO::String->new();
  833. IO::Compress::Gzip::gzip($buf => $compressed);
  834. $ct = 'application/gzip';
  835. $buf = $compressed;
  836. seek $compressed, 0, 0;
  837. }
  838. return [200,["Content-type" => $ct], $buf];
  839. }
  840. @to_map = sort @to_map unless $is_index;
  841. my $processor = Text::Xslate->new(
  842. path => _dir_for_resource('sitemap.tx'),
  843. );
  844. my $styles = _build_themed_styles('sitemap.css');
  845. $query->{title} = "$query->{domain} : Sitemap";
  846. my $content = $processor->render('sitemap.tx', {
  847. title => "Site Map",
  848. to_map => \@to_map,
  849. is_index => $is_index,
  850. route_type => $route_type,
  851. route => $query->{route},
  852. });
  853. return Trog::Routes::HTML::index($query, $render_cb,$content,$styles);
  854. }
  855. sub _rss ($query,$posts) {
  856. require XML::RSS;
  857. my $rss = XML::RSS->new (version => '2.0');
  858. my $now = DateTime->from_epoch(epoch => time());
  859. $rss->channel(
  860. title => "$query->{domain}",
  861. link => "http://$query->{domain}/$query->{route}?format=rss",
  862. language => 'en', #TODO localization
  863. description => "$query->{domain} : $query->{route}",
  864. pubDate => $now,
  865. lastBuildDate => $now,
  866. );
  867. #TODO configurability
  868. $rss->image(
  869. title => $query->{domain},
  870. url => "$td/img/icon/favicon.ico",
  871. link => "http://$query->{domain}",
  872. width => 88,
  873. height => 31,
  874. description => "$query->{domain} favicon",
  875. );
  876. foreach my $post (@$posts) {
  877. my $url = "http://$query->{domain}/posts/$post->{id}";
  878. $rss->add_item(
  879. title => $post->{title},
  880. permaLink => $url,
  881. link => $url,
  882. enclosure => { url => $url, type=>"text/html" },
  883. description => "<![CDATA[$post->{data}]]>",
  884. pubDate => DateTime->from_epoch(epoch => $post->{created} ), #TODO format like Thu, 23 Aug 1999 07:00:00 GMT
  885. author => $post->{user}, #TODO translate to "email (user)" format
  886. );
  887. }
  888. require Encode;
  889. return [200, ["Content-type" => "application/rss+xml"], [Encode::encode_utf8($rss->as_string)]];
  890. }
  891. =head2 manual
  892. Implements the /manual and /lib/* routes.
  893. Basically a thin wrapper around Pod::Html.
  894. =cut
  895. sub manual ($query, $render_cb) {
  896. require Pod::Html;
  897. require Capture::Tiny;
  898. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  899. #Fix links from Pod::HTML
  900. $query->{module} =~ s/\.html$//g if $query->{module};
  901. my $infile = $query->{module} ? "$query->{module}.pm" : 'tCMS/Manual.pod';
  902. return notfound($query,$render_cb) unless -f "lib/$infile";
  903. my $content = capture { Pod::Html::pod2html(qw{--podpath=lib --podroot=.},"--infile=lib/$infile") };
  904. my @series = _get_series(1);
  905. return $render_cb->('manual.tx', {
  906. title => 'tCMS Manual',
  907. theme_dir => $td,
  908. content => $content,
  909. categories => \@series,
  910. stylesheets => _build_themed_styles('post.css'),
  911. });
  912. }
  913. # Deal with Params which may or may not be arrays
  914. sub _coerce_array ($param) {
  915. my $p = $param || [];
  916. $p = [$param] if $param && (ref $param ne 'ARRAY');
  917. return $p;
  918. }
  919. sub _build_themed_styles ($style) {
  920. my @styles;
  921. @styles = ("/styles/$style") if -f "www/styles/$style";
  922. my $ts = _themed_style($style);
  923. push(@styles, $ts) if $theme_dir && -f "www/$ts";
  924. return \@styles;
  925. }
  926. sub _build_themed_scripts ($script) {
  927. my @scripts = ("/scripts/$script");
  928. my $ts = _themed_style($script);
  929. push(@scripts, $ts) if $theme_dir && -f "www/$ts";
  930. return \@scripts;
  931. }
  932. sub _pick_processor($file, $normal, $themed) {
  933. return _dir_for_resource($file) eq $template_dir ? $normal : $themed;
  934. }
  935. # Pick appropriate dir based on whether theme override exists
  936. sub _dir_for_resource ($resource) {
  937. return $theme_dir && -f "www/$theme_dir/$resource" ? $theme_dir : $template_dir;
  938. }
  939. sub _themed_style ($resource) {
  940. return _dir_for_resource("styles/$resource")."/styles/$resource";
  941. }
  942. sub _themed_script ($resource) {
  943. return _dir_for_resource("scripts/$resource")."/scripts/$resource";
  944. }
  945. 1;