HTML.pm 40 KB

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