HTML.pm 36 KB

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