HTML.pm 37 KB

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