HTML.pm 37 KB

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