HTML.pm 40 KB

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