HTML.pm 36 KB

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