HTML.pm 36 KB

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