HTML.pm 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  1. package Trog::Routes::HTML;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures state};
  6. use Errno qw{ENOENT};
  7. use File::Touch();
  8. use List::Util();
  9. use Capture::Tiny qw{capture};
  10. use HTML::SocialMeta;
  11. use Trog::Utils;
  12. use Trog::Config;
  13. use Trog::Data;
  14. my $conf = Trog::Config::get();
  15. my $template_dir = 'www/templates';
  16. my $theme_dir = '';
  17. $theme_dir = "themes/".$conf->param('general.theme') if $conf->param('general.theme') && -d "www/themes/".$conf->param('general.theme');
  18. my $td = $theme_dir ? "/$theme_dir" : '';
  19. use lib 'www';
  20. our $landing_page = 'default.tx';
  21. our $htmltitle = 'title.tx';
  22. our $midtitle = 'midtitle.tx';
  23. our $rightbar = 'rightbar.tx';
  24. our $leftbar = 'leftbar.tx';
  25. our $footbar = 'footbar.tx';
  26. our %routes = (
  27. default => {
  28. callback => \&Trog::Routes::HTML::setup,
  29. },
  30. '/' => {
  31. method => 'GET',
  32. callback => \&Trog::Routes::HTML::index,
  33. },
  34. #Deal with most indexDocument directives interfering with proxied requests to /
  35. '/index.html' => {
  36. method => 'GET',
  37. callback => \&Trog::Routes::HTML::index,
  38. },
  39. '/index.php' => {
  40. method => 'GET',
  41. callback => \&Trog::Routes::HTML::index,
  42. },
  43. # This should only be enabled to debug
  44. # '/setup' => {
  45. # method => 'GET',
  46. # callback => \&Trog::Routes::HTML::setup,
  47. # },
  48. '/login' => {
  49. method => 'GET',
  50. callback => \&Trog::Routes::HTML::login,
  51. },
  52. '/logout' => {
  53. method => 'GET',
  54. callback => \&Trog::Routes::HTML::logout,
  55. },
  56. '/auth' => {
  57. method => 'POST',
  58. nostatic => 1,
  59. callback => \&Trog::Routes::HTML::login,
  60. },
  61. '/post' => {
  62. method => 'GET',
  63. auth => 1,
  64. callback => \&Trog::Routes::HTML::post,
  65. },
  66. '/post/(.*)' => {
  67. method => 'GET',
  68. auth => 1,
  69. callback => \&Trog::Routes::HTML::post,
  70. captures => ['id'],
  71. },
  72. '/post/save' => {
  73. method => 'POST',
  74. auth => 1,
  75. callback => \&Trog::Routes::HTML::post_save,
  76. },
  77. '/post/delete' => {
  78. method => 'POST',
  79. auth => 1,
  80. callback => \&Trog::Routes::HTML::post_delete,
  81. },
  82. '/themeclone' => {
  83. method => 'POST',
  84. auth => 1,
  85. callback => \&Trog::Routes::HTML::themeclone,
  86. },
  87. # Can also be made into posts
  88. '/sitemap', => {
  89. method => 'GET',
  90. callback => \&Trog::Routes::HTML::sitemap,
  91. },
  92. '/sitemap_index.xml', => {
  93. method => 'GET',
  94. callback => \&Trog::Routes::HTML::sitemap,
  95. data => { xml => 1 },
  96. },
  97. '/sitemap_index.xml.gz', => {
  98. method => 'GET',
  99. callback => \&Trog::Routes::HTML::sitemap,
  100. data => { xml => 1, compressed => 1 },
  101. },
  102. '/sitemap/static.xml' => {
  103. method => 'GET',
  104. callback => \&Trog::Routes::HTML::sitemap,
  105. data => { xml => 1, map => 'static' },
  106. },
  107. '/sitemap/static.xml.gz' => {
  108. method => 'GET',
  109. callback => \&Trog::Routes::HTML::sitemap,
  110. data => { xml => 1, compressed => 1, map => 'static' },
  111. },
  112. '/sitemap/(.*).xml' => {
  113. method => 'GET',
  114. callback => \&Trog::Routes::HTML::sitemap,
  115. data => { xml => 1 },
  116. captures => ['map'],
  117. },
  118. '/sitemap/(.*).xml.gz' => {
  119. method => 'GET',
  120. callback => \&Trog::Routes::HTML::sitemap,
  121. data => { xml => 1, compressed => 1},
  122. captures => ['map'],
  123. },
  124. '/robots.txt' => {
  125. method => 'GET',
  126. callback => \&Trog::Routes::HTML::robots,
  127. },
  128. '/humans.txt' => {
  129. method => 'GET',
  130. callback => \&Trog::Routes::HTML::posts,
  131. data => { tag => ['about'] },
  132. },
  133. '/styles/avatars.css' => {
  134. method => 'GET',
  135. callback => \&Trog::Routes::HTML::avatars,
  136. data => { tag => ['about'] },
  137. },
  138. #TODO make all these routes dynamic from data
  139. '/config' => {
  140. method => 'GET',
  141. auth => 1,
  142. callback => \&Trog::Routes::HTML::config,
  143. },
  144. '/config/save' => {
  145. method => 'POST',
  146. auth => 1,
  147. callback => \&Trog::Routes::HTML::config_save,
  148. },
  149. '/posts' => {
  150. method => 'GET',
  151. callback => \&Trog::Routes::HTML::posts,
  152. },
  153. '/profile' => {
  154. method => 'POST',
  155. auth => 1,
  156. callback => \&Trog::Routes::HTML::profile,
  157. },
  158. '/users/(.*)' => {
  159. method => 'GET',
  160. callback => \&Trog::Routes::HTML::users,
  161. captures => ['username'],
  162. },
  163. '/manual' => {
  164. method => 'GET',
  165. auth => 1,
  166. callback => \&Trog::Routes::HTML::manual,
  167. },
  168. '/lib/(.*)' => {
  169. method => 'GET',
  170. auth => 1,
  171. captures => ['module'],
  172. callback => \&Trog::Routes::HTML::manual,
  173. },
  174. );
  175. # Build aliases for /posts and /post with extra data
  176. my @post_aliases = qw{news blog image video audio about files series};
  177. @routes{map { "/$_" } @post_aliases} = map { my %copy = %{$routes{'/posts'}}; $copy{data}{tag} = [$_]; \%copy } @post_aliases;
  178. $routes{'/series'}{data}{exclude_tags} = ['topbar'];
  179. #TODO clean this up so we don't need _build_post_type
  180. @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};
  181. $routes{'/post/news'} = { method => 'GET', auth => 1, callback => \&Trog::Routes::HTML::post, data => { tag => ['news'], type => 'microblog' } };
  182. $routes{'/post/blog'} = { method => 'GET', auth => 1, callback => \&Trog::Routes::HTML::post, data => { tag => ['blog'], type => 'blog' } };
  183. $routes{'/post/about'} = { method => 'GET', auth => 1, callback => \&Trog::Routes::HTML::post, data => { tag => ['about'], type => 'profile' } };
  184. $routes{'/post/series'} = { method => 'GET', auth => 1, callback => \&Trog::Routes::HTML::post, data => { tag => ['series'], type => 'series' } };
  185. # Build aliases for /posts/(.*) and /post/(.*) with extra data
  186. @routes{map { "/post/$_/(.*)" } @post_aliases} = map { my %copy = %{$routes{'/post/(.*)'}}; \%copy } @post_aliases;
  187. # /series/$ID is a bit of a special case, it's actuallly gonna need special processing
  188. $routes{'/series/(.*)'} = { method => 'GET', auth => 1, callback => \&Trog::Routes::HTML::series, captures => ['id'] };
  189. # Grab theme routes
  190. my $themed = 0;
  191. if ($theme_dir) {
  192. my $theme_mod = "$theme_dir/routes.pm";
  193. if (-f "www/$theme_mod" ) {
  194. require $theme_mod;
  195. @routes{keys(%Theme::routes)} = values(%Theme::routes);
  196. $themed = 1;
  197. }
  198. }
  199. =head1 PRIMARY ROUTE
  200. =head2 index
  201. Implements the primary route used by all pages not behind auth.
  202. Most subsequent functions simply pass content to this function.
  203. =cut
  204. sub index ($query,$render_cb, $content = '', $i_styles = []) {
  205. $query->{theme_dir} = $td;
  206. my $processor = Text::Xslate->new(
  207. path => $template_dir,
  208. );
  209. my $t_processor;
  210. $t_processor = Text::Xslate->new(
  211. path => "www/$theme_dir/templates",
  212. ) if $theme_dir;
  213. $content ||= _pick_processor("templates/$landing_page",$processor,$t_processor)->render($landing_page,$query);
  214. my @styles = ('/styles/avatars.css');
  215. if ($theme_dir) {
  216. if ($query->{embed}) {
  217. unshift(@styles, _themed_style("embed.css")) if -f 'www/'._themed_style("embed.css");
  218. }
  219. unshift(@styles, _themed_style("screen.css")) if -f 'www/'._themed_style("screen.css");
  220. unshift(@styles, _themed_style("structure.css")) if -f 'www/'._themed_style("structure.css");
  221. }
  222. push( @styles, @$i_styles );
  223. #TODO allow theming of print css
  224. my $search_info = Trog::Data->new($conf);
  225. my @series = _get_series(0, $search_info);
  226. my $title = $query->{primary_post}{title} // $query->{title} // $Theme::default_title // 'tCMS';
  227. # Handle link "unfurling" correctly
  228. my ($default_tags, $meta_desc, $meta_tags) = _build_social_meta($query,$title);
  229. #Do embed content
  230. my $tmpl = $query->{embed} ? 'embed.tx' : 'index.tx';
  231. return $render_cb->( $tmpl, {
  232. code => $query->{code},
  233. user => $query->{user},
  234. search_lang => $search_info->lang(),
  235. search_help => $search_info->help(),
  236. route => $query->{route},
  237. domain => $query->{domain},
  238. theme_dir => $td,
  239. content => $content,
  240. title => $title,
  241. htmltitle => _pick_processor("templates/$htmltitle" ,$processor,$t_processor)->render($htmltitle,$query),
  242. midtitle => _pick_processor("templates/$midtitle" ,$processor,$t_processor)->render($midtitle,$query),
  243. rightbar => _pick_processor("templates/$rightbar" ,$processor,$t_processor)->render($rightbar,$query),
  244. leftbar => _pick_processor("templates/$leftbar" ,$processor,$t_processor)->render($leftbar,$query),
  245. footbar => _pick_processor("templates/$footbar" ,$processor,$t_processor)->render($footbar,$query),
  246. categories => \@series,
  247. stylesheets => \@styles,
  248. show_madeby => $Theme::show_madeby ? 1 : 0,
  249. embed => $query->{embed} ? 1 : 0,
  250. embed_video => $query->{primary_post}{is_video},
  251. default_tags => $default_tags,
  252. meta_desc => $meta_desc,
  253. meta_tags => $meta_tags,
  254. deflate => $query->{deflate},
  255. });
  256. }
  257. sub _build_social_meta ($query,$title) {
  258. return (undef,undef,undef) unless $query->{social_meta};
  259. my $default_tags = $Theme::default_tags;
  260. $default_tags .= ','.join(',',@{$query->{primary_post}->{tags}}) if $default_tags && $query->{primary_post}->{tags};
  261. my $meta_desc = $query->{primary_post}{data} // $Theme::description // "tCMS Site";
  262. $meta_desc = Trog::Utils::strip_and_trunc($meta_desc);
  263. my $meta_tags = '';
  264. my $card_type = 'summary';
  265. $card_type = 'featured_image' if $query->{primary_post} && $query->{primary_post}{is_image};
  266. $card_type = 'player' if $query->{primary_post} && $query->{primary_post}{is_video};
  267. my $image = $Theme::default_image ? "https://$query->{domain}/$td/$Theme::default_image" : '';
  268. $image = "https://$query->{domain}/$query->{primary_post}{preview}" if $query->{primary_post} && $query->{primary_post}{preview};
  269. $image = "https://$query->{domain}/$query->{primary_post}{href}" if $query->{primary_post} && $query->{primary_post}{is_image};
  270. my $primary_route = "https://$query->{domain}/$query->{route}";
  271. $primary_route =~ s/[\/]+/\//g;
  272. my $display_name = $Theme::display_name // 'Another tCMS Site';
  273. my $extra_tags ='';
  274. my %sopts = (
  275. site_name => $display_name,
  276. app_name => $display_name,
  277. title => $title,
  278. description => $meta_desc,
  279. url => $primary_route,
  280. );
  281. $sopts{site} = $Theme::twitter_account if $Theme::twitter_account;
  282. $sopts{image} = $image if $image;
  283. $sopts{fb_app_id} = $Theme::fb_app_id if $Theme::fb_app_id;
  284. if ($query->{primary_post} && $query->{primary_post}{is_video}) {
  285. #$sopts{player} = "$primary_route?embed=1";
  286. $sopts{player} = "https://$query->{domain}/$query->{primary_post}{href}";
  287. #XXX don't hardcode this
  288. $sopts{player_width} = 1280;
  289. $sopts{player_height} = 720;
  290. $extra_tags .= "<meta property='og:video:type' content='$query->{primary_post}{content_type}' />\n";
  291. }
  292. my $social = HTML::SocialMeta->new(%sopts);
  293. $meta_tags = eval { $social->create($card_type) };
  294. $meta_tags =~ s/content="video"/content="video:other"/mg if $meta_tags;
  295. $meta_tags .= $extra_tags if $extra_tags;
  296. print STDERR "WARNING: Theme misconfigured, social media tags will not be included\n$@\n" unless $meta_tags;
  297. return ($default_tags, $meta_desc, $meta_tags);
  298. }
  299. =head1 ADMIN ROUTES
  300. These are things that issue returns other than 200, and are not directly accessible by users via any defined route.
  301. =head2 notfound, forbidden, badrequest
  302. Implements the 4XX status codes. Override templates named the same for theming this.
  303. =cut
  304. sub _generic_route ($rname, $code, $title, $query, $render_cb) {
  305. $query->{code} = $code;
  306. my $processor = Text::Xslate->new(
  307. path => _dir_for_resource("$rname.tx"),
  308. );
  309. $query->{title} = $title;
  310. my $styles = _build_themed_styles("$rname.css");
  311. my $content = $processor->render("$rname.tx", {
  312. title => $title,
  313. route => $query->{route},
  314. user => $query->{user},
  315. styles => $styles,
  316. deflate => $query->{deflate},
  317. });
  318. return Trog::Routes::HTML::index($query, $render_cb, $content, $styles);
  319. }
  320. sub notfound (@args) {
  321. return _generic_route('notfound',404,"Return to sender, Address unknown", @args);
  322. }
  323. sub forbidden (@args) {
  324. return _generic_route('forbidden', 403, "STAY OUT YOU RED MENACE", @args);
  325. }
  326. sub badrequest (@args) {
  327. return _generic_route('badrequest', 400, "Bad Request", @args);
  328. }
  329. sub redirect ($to) {
  330. return [302, ["Location" => $to],['']]
  331. }
  332. sub redirect_permanent ($to) {
  333. return [301, ["Location" => $to], ['']];
  334. }
  335. # TODO Rate limiting route
  336. =head1 NORMAL ROUTES
  337. These are expected to either return a 200, or redirect to something which does.
  338. =head2 robots
  339. Return an appropriate robots.txt
  340. =cut
  341. sub robots ($query, $render_cb) {
  342. my $processor = Text::Xslate->new(
  343. path => $template_dir,
  344. );
  345. return [200, ["Content-type:text/plain\n"],[$processor->render('robots.tx', { domain => $query->{domain} })]];
  346. }
  347. =head2 setup
  348. One time setup page; should only display to the first user to visit the site which we presume to be the administrator.
  349. =cut
  350. sub setup ($query, $render_cb) {
  351. File::Touch::touch("config/setup");
  352. return $render_cb->('notconfigured.tx', {
  353. title => 'tCMS Requires Setup to Continue...',
  354. stylesheets => _build_themed_styles('notconfigured.css'),
  355. });
  356. }
  357. =head2 login
  358. 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.
  359. =cut
  360. sub login ($query, $render_cb) {
  361. # Redirect if we actually have a logged in user.
  362. # Note to future me -- this user value is overwritten explicitly in server.psgi.
  363. # If that ever changes, you will die
  364. $query->{to} //= $query->{route};
  365. $query->{to} = '/config' if $query->{to} eq '/login';
  366. if ($query->{user}) {
  367. return $routes{$query->{to}}{callback}->($query,$render_cb);
  368. }
  369. #Check and see if we have no users. If so we will just accept whatever creds are passed.
  370. my $hasusers = -f "config/has_users";
  371. my $btnmsg = $hasusers ? "Log In" : "Register";
  372. my @headers;
  373. if ($query->{username} && $query->{password}) {
  374. if (!$hasusers) {
  375. # Make the first user
  376. Trog::Auth::useradd($query->{username}, $query->{password}, ['admin'] );
  377. File::Touch::touch("config/has_users");
  378. }
  379. $query->{failed} = 1;
  380. my $cookie = Trog::Auth::mksession($query->{username}, $query->{password});
  381. if ($cookie) {
  382. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  383. my $secure = '';
  384. $secure = '; Secure' if $query->{scheme} eq 'https';
  385. @headers = (
  386. "Set-Cookie" => "tcmslogin=$cookie; HttpOnly; SameSite=Strict$secure",
  387. );
  388. $query->{failed} = 0;
  389. }
  390. }
  391. $query->{failed} //= -1;
  392. return $render_cb->('login.tx', {
  393. title => 'tCMS 2 ~ Login',
  394. to => $query->{to},
  395. failure => int( $query->{failed} ),
  396. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  397. btnmsg => $btnmsg,
  398. stylesheets => _build_themed_styles('login.css'),
  399. theme_dir => $td,
  400. }, @headers);
  401. }
  402. =head2 logout
  403. Deletes your users' session and opens the login page.
  404. =cut
  405. sub logout ($query, $render_cb) {
  406. Trog::Auth::killsession($query->{user}) if $query->{user};
  407. delete $query->{user};
  408. $query->{to} = '/config';
  409. return login($query,$render_cb);
  410. }
  411. =head2 config
  412. Renders the configuration page, or redirects you back to the login page.
  413. =cut
  414. sub config ($query, $render_cb) {
  415. if (!$query->{user}) {
  416. return login($query,$render_cb);
  417. }
  418. #NOTE: we are relying on this to skip the ACL check with 'admin', this may not be viable in future?
  419. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  420. my $css = _build_themed_styles('config.css');
  421. my $js = _build_themed_scripts('post.js');
  422. $query->{failure} //= -1;
  423. my @series = _get_series(1);
  424. return $render_cb->('config.tx', {
  425. title => 'Configure tCMS',
  426. theme_dir => $td,
  427. stylesheets => $css,
  428. scripts => $js,
  429. categories => \@series,
  430. themes => _get_themes() || [],
  431. data_models => _get_data_models(),
  432. current_theme => $conf->param('general.theme') // '',
  433. current_data_model => $conf->param('general.data_model') // 'DUMMY',
  434. message => $query->{message},
  435. failure => $query->{failure},
  436. to => '/config',
  437. });
  438. }
  439. sub _get_series($edit=0,$search_info=0) {
  440. $search_info ||= Trog::Data->new($conf);
  441. my @series = $search_info->get(
  442. acls => [qw{public}],
  443. tags => [qw{topbar}],
  444. limit => 10,
  445. page => 1,
  446. );
  447. @series = map { $_->{local_href} = "/post$_->{local_href}"; $_ } @series if $edit;
  448. return @series;
  449. }
  450. sub _get_themes {
  451. my $dir = 'www/themes';
  452. opendir(my $dh, $dir) || do { die "Can't opendir $dir: $!" unless $!{ENOENT} };
  453. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  454. closedir $dh;
  455. return \@tdirs;
  456. }
  457. sub _get_data_models {
  458. my $dir = 'lib/Trog/Data';
  459. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  460. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  461. closedir $dh;
  462. return \@dmods
  463. }
  464. =head2 config_save
  465. Implements /config/save route. Saves what little configuration we actually use to ~/.tcms/tcms.conf
  466. =cut
  467. sub config_save ($query, $render_cb) {
  468. $conf->param( 'general.theme', $query->{theme} ) if defined $query->{theme};
  469. $conf->param( 'general.data_model', $query->{data_model} ) if $query->{data_model};
  470. $query->{failure} = 1;
  471. $query->{message} = "Failed to save configuration!";
  472. if ($conf->write($Trog::Config::home_cfg)) {
  473. $query->{failure} = 0;
  474. $query->{message} = "Configuration updated succesfully.";
  475. }
  476. #Get the PID of the parent port using lsof, send HUP
  477. my $parent = getppid;
  478. kill 'HUP', $parent;
  479. return config($query, $render_cb);
  480. }
  481. =head2 themeclone
  482. Clone a theme by copying a directory.
  483. =cut
  484. sub themeclone ($query, $render_cb) {
  485. my ($theme, $newtheme) = ($query->{theme},$query->{newtheme});
  486. my $themedir = 'www/themes';
  487. $query->{failure} = 1;
  488. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  489. require File::Copy::Recursive;
  490. if ($theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" )) {
  491. $query->{failure} = 0;
  492. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  493. }
  494. return config($query, $render_cb);
  495. }
  496. =head2 post
  497. Display the route for making new posts.
  498. =cut
  499. sub post ($query, $render_cb) {
  500. if (!$query->{user}) {
  501. return login($query, $render_cb);
  502. }
  503. $query->{acls} = _coerce_array($query->{acls});
  504. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  505. my $tags = _coerce_array($query->{tag});
  506. my @posts = _post_helper($query, $tags, $query->{acls});
  507. my $css = _build_themed_styles('post.css');
  508. my $js = _build_themed_scripts('post.js');
  509. push(@$css, '/styles/avatars.css');
  510. my @acls = _post_helper({}, ['series'], $query->{acls});
  511. my $app = 'file';
  512. if ($query->{route}) {
  513. $app = 'image' if $query->{route} =~ m/image$/;
  514. $app = 'video' if $query->{route} =~ m/video$/;
  515. $app = 'audio' if $query->{route} =~ m/audio$/;
  516. }
  517. #Filter displaying visibility tags
  518. my @visibuddies = qw{public unlisted private};
  519. foreach my $post (@posts) {
  520. @{$post->{tags}} = grep { my $tag = $_; !grep { $tag eq $_ } @visibuddies } @{$post->{tags}};
  521. }
  522. my $limit = int($query->{limit} || 25);
  523. my @series = _get_series(1);
  524. return $render_cb->('post.tx', {
  525. title => 'New Post',
  526. theme_dir => $td,
  527. to => $query->{to},
  528. failure => $query->{failure} // -1,
  529. message => $query->{message},
  530. post_visibilities => \@visibuddies,
  531. stylesheets => $css,
  532. scripts => $js,
  533. posts => \@posts,
  534. can_edit => 1,
  535. route => $query->{route},
  536. category => '/posts',
  537. categories => \@series,
  538. limit => $limit,
  539. pages => scalar(@posts) == $limit,
  540. older => @posts ? $posts[-1]->{created} : '',
  541. sizes => [25,50,100],
  542. id => $query->{id},
  543. acls => \@acls,
  544. post => { tags => $query->{tag} },
  545. edittype => $query->{type} || 'microblog',
  546. app => $app,
  547. });
  548. }
  549. =head2 post_save
  550. Saves posts submitted via the /post pages
  551. =cut
  552. sub post_save ($query, $render_cb) {
  553. my $to = delete $query->{to};
  554. #Copy this down since it will be deleted later
  555. my $acls = $query->{acls};
  556. state $data = Trog::Data->new($conf);
  557. $query->{tags} = _coerce_array($query->{tags});
  558. $query->{failure} = $data->add($query);
  559. $query->{to} = $to;
  560. $query->{acls} = $acls;
  561. $query->{message} = $query->{failure} ? "Failed to add post!" : "Successfully added Post as $query->{id}";
  562. delete $query->{id};
  563. return post($query, $render_cb);
  564. }
  565. =head2 profile
  566. Saves / updates new users.
  567. =cut
  568. sub profile ($query, $render_cb) {
  569. #TODO allow users to do something OTHER than be admins
  570. if ($query->{password}) {
  571. Trog::Auth::useradd($query->{username}, $query->{password}, ['admin'] );
  572. }
  573. #Make sure it is "self-authored", redact pw
  574. $query->{user} = delete $query->{username};
  575. delete $query->{password};
  576. return post_save($query, $render_cb);
  577. }
  578. =head2 post_delete
  579. deletes posts.
  580. =cut
  581. sub post_delete ($query, $render_cb) {
  582. state $data = Trog::Data->new($conf);
  583. $query->{failure} = $data->delete($query);
  584. $query->{to} = $query->{to};
  585. $query->{message} = $query->{failure} ? "Failed to delete post $query->{id}!" : "Successfully deleted Post $query->{id}";
  586. delete $query->{id};
  587. return post($query, $render_cb);
  588. }
  589. =head2 series
  590. Series specific view, much like the users/ route
  591. Displays identified series, not all series.
  592. =cut
  593. sub series ($query, $render_cb) {
  594. #Grab the relevant tag (aclname), then pass that to posts
  595. my @posts = _post_helper($query, [], $query->{acls});
  596. delete $query->{id};
  597. $query->{subhead} = $posts[0]->{data};
  598. $query->{title} = $posts[0]->{title};
  599. $query->{tag} = $posts[0]->{aclname};
  600. $query->{primary_post} = $posts[0];
  601. return posts($query,$render_cb);
  602. }
  603. =head2 avatars
  604. Returns the avatars.css. Limited to 1000 users.
  605. =cut
  606. sub avatars ($query, $render_cb) {
  607. #XXX if you have more than 1000 editors you should stop
  608. push(@{$query->{acls}}, 'public');
  609. my $tags = _coerce_array($query->{tag});
  610. $query->{limit} = 1000;
  611. my $processor = Text::Xslate->new(
  612. path => $template_dir,
  613. );
  614. my @posts = _post_helper($query, $tags, $query->{acls});
  615. my $content = $processor->render('avatars.tx', {
  616. users => \@posts,
  617. });
  618. return [200, ["Content-type" => "text/css" ],[$content]];
  619. }
  620. =head2 users
  621. Implements direct user profile view.
  622. =cut
  623. sub users ($query, $render_cb) {
  624. push(@{$query->{acls}}, 'public');
  625. my @posts = _post_helper({ limit => 10000 }, ['about'], $query->{acls});
  626. my @user = grep { $_->{user} eq $query->{username} } @posts;
  627. $query->{id} = $user[0]->{id};
  628. $query->{title} = $user[0]->{title};
  629. $query->{user_obj} = $user[0];
  630. $query->{primary_post} = $posts[0];
  631. return posts($query,$render_cb);
  632. }
  633. =head2 posts
  634. Display multi or single posts, supports RSS and pagination.
  635. =cut
  636. sub posts ($query, $render_cb) {
  637. #Process the input URI to capture tag/id
  638. my (undef, $tag, $id) = split(/\//, $query->{route});
  639. my $tags = _coerce_array($query->{tag});
  640. push(@$tags, $tag) if $tag && $tag ne 'posts';
  641. $query->{id} = $id if $id;
  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;