HTML.pm 35 KB

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