HTML.pm 40 KB

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