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. $dat->add({
  338. title => $query->{username},
  339. data => 'Default user',
  340. preview => '/img/avatar/humm.gif',
  341. wallpaper => '/img/sys/testpattern.jpg',
  342. tags => ['about'],
  343. visibility => 'public',
  344. acls => ['admin'],
  345. local_href => "/users/$query->{username}",
  346. callback => "Trog::Routes::HTML::users",
  347. user => $query->{username},
  348. form => 'profile.tx',
  349. });
  350. # Ensure we stop registering new users
  351. File::Touch::touch("config/has_users");
  352. #hup the parent to refresh the routing table
  353. my $parent = getppid;
  354. kill 'HUP', $parent;
  355. }
  356. $query->{failed} = 1;
  357. my $cookie = Trog::Auth::mksession($query->{username}, $query->{password});
  358. if ($cookie) {
  359. # TODO secure / sameSite cookie to kill csrf, maybe do rememberme with Expires=~0
  360. my $secure = '';
  361. $secure = '; Secure' if $query->{scheme} eq 'https';
  362. @headers = (
  363. "Set-Cookie" => "tcmslogin=$cookie; HttpOnly; SameSite=Strict$secure",
  364. );
  365. $query->{failed} = 0;
  366. }
  367. }
  368. $query->{failed} //= -1;
  369. return $render_cb->('login.tx', {
  370. title => 'tCMS 2 ~ Login',
  371. to => $query->{to},
  372. failure => int( $query->{failed} ),
  373. message => int( $query->{failed} ) < 1 ? "Login Successful, Redirecting..." : "Login Failed.",
  374. btnmsg => $btnmsg,
  375. stylesheets => _build_themed_styles('login.css'),
  376. theme_dir => $td,
  377. }, @headers);
  378. }
  379. sub _setup_initial_db ($dat, $user) {
  380. $dat->add(
  381. {
  382. "aclname" => "series",
  383. "acls" => [],
  384. "callback" => "Trog::Routes::HTML::series",
  385. "data" => "Series",
  386. "href" => "/series",
  387. "local_href" => "/series",
  388. "preview" => "/img/sys/testpattern.jpg",
  389. "tags" => [qw{series topbar}],
  390. visibility => 'public',
  391. "title" => "Series",
  392. user => $user,
  393. form => 'series.tx',
  394. child_form => 'series.tx',
  395. },
  396. {
  397. "aclname" => "about",
  398. "acls" => [],
  399. "callback" => "Trog::Routes::HTML::series",
  400. "data" => "About",
  401. "href" => "/about",
  402. "local_href" => "/about",
  403. "preview" => "/img/sys/testpattern.jpg",
  404. "tags" => [qw{series topbar public}],
  405. visibility => 'public',
  406. "title" => "About",
  407. user => $user,
  408. form => 'series.tx',
  409. child_form => 'profile.tx',
  410. },
  411. {
  412. "aclname" => "admin",
  413. acls => [],
  414. "callback" => "Trog::Routes::HTML::config",
  415. "content_type" => "text/plain",
  416. "data" => "Config",
  417. "href" => "/config",
  418. "local_href" => "/config",
  419. "preview" => "/img/sys/testpattern.jpg",
  420. "tags" => [qw{admin}],
  421. visibility => 'private',
  422. "title" => "Configure tCMS",
  423. user => $user,
  424. },
  425. );
  426. }
  427. =head2 logout
  428. Deletes your users' session and opens the index.
  429. =cut
  430. sub logout ($query, $render_cb) {
  431. Trog::Auth::killsession($query->{user}) if $query->{user};
  432. delete $query->{user};
  433. return Trog::Routes::HTML::index($query,$render_cb);
  434. }
  435. =head2 config
  436. Renders the configuration page, or redirects you back to the login page.
  437. =cut
  438. sub config ($query, $render_cb) {
  439. if (!$query->{user}) {
  440. return login($query,$render_cb);
  441. }
  442. #NOTE: we are relying on this to skip the ACL check with 'admin', this may not be viable in future?
  443. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  444. my $css = _build_themed_styles('config.css');
  445. my $js = _build_themed_scripts('post.js');
  446. $query->{failure} //= -1;
  447. my @series = _get_series(1);
  448. return $render_cb->('config.tx', {
  449. title => 'Configure tCMS',
  450. theme_dir => $td,
  451. stylesheets => $css,
  452. scripts => $js,
  453. categories => \@series,
  454. themes => _get_themes() || [],
  455. data_models => _get_data_models(),
  456. current_theme => $conf->param('general.theme') // '',
  457. current_data_model => $conf->param('general.data_model') // 'DUMMY',
  458. message => $query->{message},
  459. failure => $query->{failure},
  460. to => '/config',
  461. });
  462. }
  463. sub _get_series($edit=0,$search_info=0) {
  464. $search_info ||= Trog::Data->new($conf);
  465. my @series = $search_info->get(
  466. acls => [qw{public}],
  467. tags => [qw{topbar}],
  468. limit => 10,
  469. page => 1,
  470. );
  471. @series = map { $_->{local_href} = "/post$_->{local_href}"; $_ } @series if $edit;
  472. return @series;
  473. }
  474. sub _get_themes {
  475. my $dir = 'www/themes';
  476. opendir(my $dh, $dir) || do { die "Can't opendir $dir: $!" unless $!{ENOENT} };
  477. my @tdirs = grep { !/^\./ && -d "$dir/$_" } readdir($dh);
  478. closedir $dh;
  479. return \@tdirs;
  480. }
  481. sub _get_data_models {
  482. my $dir = 'lib/Trog/Data';
  483. opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
  484. my @dmods = map { s/\.pm$//g; $_ } grep { /\.pm$/ && -f "$dir/$_" } readdir($dh);
  485. closedir $dh;
  486. return \@dmods
  487. }
  488. =head2 config_save
  489. Implements /config/save route. Saves what little configuration we actually use to ~/.tcms/tcms.conf
  490. =cut
  491. sub config_save ($query, $render_cb) {
  492. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  493. $conf->param( 'general.theme', $query->{theme} ) if defined $query->{theme};
  494. $conf->param( 'general.data_model', $query->{data_model} ) if $query->{data_model};
  495. $query->{failure} = 1;
  496. $query->{message} = "Failed to save configuration!";
  497. if ($conf->write($Trog::Config::home_cfg)) {
  498. $query->{failure} = 0;
  499. $query->{message} = "Configuration updated succesfully.";
  500. }
  501. #Get the PID of the parent port using lsof, send HUP
  502. my $parent = getppid;
  503. kill 'HUP', $parent;
  504. return config($query, $render_cb);
  505. }
  506. =head2 themeclone
  507. Clone a theme by copying a directory.
  508. =cut
  509. sub themeclone ($query, $render_cb) {
  510. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  511. my ($theme, $newtheme) = ($query->{theme},$query->{newtheme});
  512. my $themedir = 'www/themes';
  513. $query->{failure} = 1;
  514. $query->{message} = "Failed to clone theme '$theme' as '$newtheme'!";
  515. require File::Copy::Recursive;
  516. if ($theme && $newtheme && File::Copy::Recursive::dircopy( "$themedir/$theme", "$themedir/$newtheme" )) {
  517. $query->{failure} = 0;
  518. $query->{message} = "Successfully cloned theme '$theme' as '$newtheme'.";
  519. }
  520. return config($query, $render_cb);
  521. }
  522. =head2 post_save
  523. Saves posts submitted via the /post pages
  524. =cut
  525. sub post_save ($query, $render_cb) {
  526. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  527. my $to = delete $query->{to};
  528. #Copy this down since it will be deleted later
  529. my $acls = $query->{acls};
  530. state $data = Trog::Data->new($conf);
  531. $query->{tags} = _coerce_array($query->{tags});
  532. # Filter bits and bobs
  533. delete $query->{primary_post};
  534. delete $query->{social_meta};
  535. delete $query->{deflate};
  536. delete $query->{acls};
  537. # Ensure there are no null tags
  538. @{$query->{tags}} = grep { defined $_ } @{$query->{tags}};
  539. $query->{failure} = $data->add($query);
  540. $query->{to} = $to;
  541. $query->{acls} = $acls;
  542. $query->{message} = $query->{failure} ? "Failed to add post!" : "Successfully added Post";
  543. delete $query->{id};
  544. return posts($query, $render_cb);
  545. }
  546. =head2 profile
  547. Saves / updates new users.
  548. =cut
  549. sub profile ($query, $render_cb) {
  550. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  551. #TODO allow users to do something OTHER than be admins
  552. if ($query->{password}) {
  553. Trog::Auth::useradd($query->{username}, $query->{password}, ['admin'] );
  554. }
  555. #Make sure it is "self-authored", redact pw
  556. $query->{user} = delete $query->{username};
  557. delete $query->{password};
  558. return post_save($query, $render_cb);
  559. }
  560. =head2 post_delete
  561. deletes posts.
  562. =cut
  563. sub post_delete ($query, $render_cb) {
  564. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  565. state $data = Trog::Data->new($conf);
  566. $query->{failure} = $data->delete($query);
  567. $query->{to} = $query->{to};
  568. $query->{message} = $query->{failure} ? "Failed to delete post $query->{id}!" : "Successfully deleted Post $query->{id}";
  569. delete $query->{id};
  570. return posts($query, $render_cb);
  571. }
  572. =head2 series
  573. Series specific view, much like the users/ route
  574. Displays identified series, not all series.
  575. =cut
  576. sub series ($query, $render_cb) {
  577. my $is_admin = grep { $_ eq 'admin' } @{$query->{acls}};
  578. #we are either viewed one of two ways, /post/$id or /$aclname
  579. my (undef,$aclname,$id) = split(/\//,$query->{route});
  580. $query->{aclname} = $aclname if !$id;
  581. # Don't show topbar series on the series page. That said, don't exclude it from direct series view.
  582. $query->{exclude_tags} = ['topbar'] if !$is_admin && $aclname && $aclname eq 'series';
  583. #XXX I'd prefer to overload id to actually *be* the aclname...
  584. # but this way, accomodates things like the flat file time-indexing hack.
  585. # TODO I should probably have it for all posts, and make *everything* a series.
  586. # WE can then do threaded comments/posts.
  587. # That will essentially necessitate it *becoming* the ID for real.
  588. #Grab the relevant tag (aclname), then pass that to posts
  589. my @posts = _post_helper($query, ['series'], $query->{acls});
  590. delete $query->{id};
  591. delete $query->{aclname};
  592. $query->{subhead} = $posts[0]->{data};
  593. $query->{title} = $posts[0]->{title};
  594. $query->{tag} = $posts[0]->{aclname};
  595. $query->{primary_post} = $posts[0];
  596. return posts($query,$render_cb);
  597. }
  598. =head2 avatars
  599. Returns the avatars.css. Limited to 1000 users.
  600. =cut
  601. sub avatars ($query, $render_cb) {
  602. #XXX if you have more than 1000 editors you should stop
  603. push(@{$query->{acls}}, 'public');
  604. my $tags = _coerce_array($query->{tag});
  605. $query->{limit} = 1000;
  606. my $processor = Text::Xslate->new(
  607. path => $template_dir,
  608. );
  609. my @posts = _post_helper($query, $tags, $query->{acls});
  610. my $content = $processor->render('avatars.tx', {
  611. users => \@posts,
  612. });
  613. return [200, ["Content-type" => "text/css" ],[$content]];
  614. }
  615. =head2 users
  616. Implements direct user profile view.
  617. =cut
  618. sub users ($query, $render_cb) {
  619. # Capture the username
  620. my (undef, undef, $username) = split(/\//, $query->{route});
  621. $query->{username} //= $username;
  622. push(@{$query->{acls}}, 'public');
  623. $query->{exclude_tags} = ['about'];
  624. my @posts = _post_helper({ limit => 10000 }, ['about'], $query->{acls});
  625. my @user = grep { $_->{title} eq $query->{username} } @posts;
  626. $query->{id} = $user[0]->{id};
  627. $query->{title} = $user[0]->{title};
  628. $query->{user_obj} = $user[0];
  629. $query->{primary_post} = $posts[0];
  630. return posts($query,$render_cb);
  631. }
  632. =head2 posts
  633. Display multi or single posts, supports RSS and pagination.
  634. =cut
  635. sub posts ($query, $render_cb, $direct=0) {
  636. #Process the input URI to capture tag/id
  637. $query->{route} //= $query->{to};
  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. my $is_admin = grep { $_ eq 'admin' } @{$query->{acls}};
  643. push(@{$query->{acls}}, 'public');
  644. push(@{$query->{acls}}, 'unlisted') if $query->{id};
  645. push(@{$query->{acls}}, 'private') if $is_admin;
  646. my @posts;
  647. if ($query->{user_obj}) {
  648. #Optimize the /users/* route
  649. @posts = ($query->{user_obj});
  650. } else {
  651. @posts = _post_helper($query, $tags, $query->{acls});
  652. }
  653. if ($query->{id}) {
  654. $query->{primary_post} = $posts[0] if @posts;
  655. }
  656. #OK, so if we have a user as the ID we found, go grab the rest of their posts
  657. if ($query->{id} && @posts && grep { $_ eq 'about'} @{$posts[0]->{tags}} ) {
  658. my $user = shift(@posts);
  659. my $id = delete $query->{id};
  660. $query->{author} = $user->{user};
  661. @posts = _post_helper($query, [], $query->{acls});
  662. @posts = grep { $_->{id} ne $id } @posts;
  663. unshift @posts, $user;
  664. }
  665. if (!$is_admin) {
  666. return notfound($query, $render_cb) unless @posts;
  667. }
  668. my $fmt = $query->{format} || '';
  669. return _rss($query,\@posts) if $fmt eq 'rss';
  670. my $processor = Text::Xslate->new(
  671. path => $template_dir,
  672. function => {
  673. render_it => sub {
  674. my ($template_string, $options) = @_;
  675. return Text::Xslate->new(
  676. # Prevent a recursive descent. If the renderer is hit again, just do nothing
  677. # XXX unfortunately if the post tries to include itself, it will die.
  678. function => {
  679. embed => sub {
  680. my ($this_id, $style) = @_;
  681. $style //= 'embed';
  682. # If instead the style is 'content', then we will only show the content w/ no formatting, and no title.
  683. return Text::Xslate::mark_raw(Trog::Routes::HTML::posts(
  684. { route => "/post/$this_id", style => $style },
  685. sub {},
  686. 1));
  687. },
  688. },
  689. )->render_string($template_string,$options);
  690. },
  691. },
  692. );
  693. #XXX Is used by the sitemap, maybe just fix there?
  694. my @post_aliases = map { $_->{local_href} } _get_series();
  695. my ($header,$footer);
  696. my $should_header = grep { $_ eq $query->{route} } (@post_aliases,'/humans.txt');
  697. if ($should_header) {
  698. my $route = $query->{route};
  699. my %alias = ( '/humans.txt' => '/about');
  700. $route = $alias{$route} if exists $alias{$route};
  701. my $t_processor;
  702. $t_processor = Text::Xslate->new(
  703. path => "www/$theme_dir/templates",
  704. ) if $theme_dir;
  705. my $no_leading_slash = $route;
  706. $no_leading_slash =~ tr/\///d;
  707. $header = _pick_processor("templates$route\_header.tx" ,$processor,$t_processor)->render("$no_leading_slash\_header.tx", { theme_dir => $td } );
  708. $footer = _pick_processor("templates$route\_header.tx" ,$processor,$t_processor)->render("$no_leading_slash\_footer.tx", { theme_dir => $td } );
  709. }
  710. my $styles = _build_themed_styles('posts.css');
  711. #Correct page headers
  712. my $ph = $themed ? _themed_title($query->{route}) : $query->{route};
  713. # Build page title if it wasn't set by a wrapping sub
  714. $query->{title} = "$query->{domain} : $query->{title}" if $query->{title} && $query->{domain};
  715. $query->{title} ||= @$tags && $query->{domain} ? "$query->{domain} : @$tags" : undef;
  716. #Handle paginator vars
  717. my $limit = int($query->{limit} || 25);
  718. my $now_year = (localtime(time))[5] + 1900;
  719. my $oldest_year = $now_year - 20; #XXX actually find oldest post year
  720. # Handle post style.
  721. if ($query->{style}) {
  722. undef $header;
  723. undef $footer;
  724. }
  725. my $older = !@posts ? 0 : $posts[-1]->{created};
  726. $query->{failure} //= -1;
  727. $query->{id} //= '';
  728. #XXX messed up data has to be fixed unfortunately
  729. @$tags = List::Util::uniq @$tags;
  730. #XXX also unsure this is actually necessary
  731. my $app = 'file';
  732. if ($query->{route}) {
  733. $app = 'image' if $query->{route} =~ m/image$/;
  734. $app = 'video' if $query->{route} =~ m/video$/;
  735. $app = 'audio' if $query->{route} =~ m/audio$/;
  736. }
  737. #Filter displaying visibility tags
  738. my @visibuddies = qw{public unlisted private};
  739. foreach my $post (@posts) {
  740. @{$post->{tags}} = grep { my $tag = $_; !grep { $tag eq $_ } @visibuddies } @{$post->{tags}};
  741. }
  742. my $aclselected = $tags->[0] || '';
  743. my @acls = map {
  744. $_->{selected} = $_->{aclname} eq $aclselected ? 'selected' : '';
  745. $_
  746. } _post_helper({}, ['series'], $query->{acls});
  747. #TODO make this dynamic with a template subdirectory for users to plop things in
  748. my $forms = [qw{microblog.tx blog.tx file.tx}];
  749. my $edittype = $query->{primary_post} ? $query->{primary_post}->{child_form} : $query->{form};
  750. my $content = $processor->render('posts.tx', {
  751. app => $app,
  752. acls => \@acls,
  753. can_edit => $is_admin,
  754. edittype => $edittype,
  755. forms => $forms,
  756. post => { tags => $tags, form => $edittype },
  757. post_visibilities => \@visibuddies,
  758. failure => $query->{failure},
  759. to => $query->{to},
  760. message => $query->{failure} ? "Failed to add post!" : "Successfully added Post as $query->{id}",
  761. direct => $direct,
  762. title => $query->{title},
  763. style => $query->{style},
  764. posts => \@posts,
  765. like => $query->{like},
  766. in_series => exists $query->{in_series} || !!($query->{route} =~ m/\/series\/\d*$/),
  767. route => $query->{route},
  768. limit => $limit,
  769. pages => scalar(@posts) == $limit,
  770. older => $older,
  771. sizes => [25,50,100],
  772. rss => !$query->{id} && !$query->{older},
  773. tiled => !$is_admin && scalar(grep { $_ eq $query->{route} } qw{/files /audio /video /image /series /about}),
  774. category => $ph,
  775. subhead => $query->{subhead},
  776. header => $header,
  777. footer => $footer,
  778. years => [reverse($oldest_year..$now_year)],
  779. months => [0..11],
  780. });
  781. return $content if $direct;
  782. return Trog::Routes::HTML::index($query, $render_cb, $content, $styles);
  783. }
  784. sub _themed_title ($path) {
  785. return $path unless %Theme::paths;
  786. return $Theme::paths{$path} ? $Theme::paths{$path} : $path;
  787. }
  788. sub _post_helper ($query, $tags, $acls) {
  789. state $data = Trog::Data->new($conf);
  790. return $data->get(
  791. older => $query->{older},
  792. page => int($query->{page} || 1),
  793. limit => int($query->{limit} || 25),
  794. tags => $tags,
  795. exclude_tags => $query->{exclude_tags},
  796. acls => $acls,
  797. aclname => $query->{aclname},
  798. like => $query->{like},
  799. author => $query->{author},
  800. id => $query->{id},
  801. version => $query->{version},
  802. );
  803. }
  804. =head2 sitemap
  805. Return the sitemap index unless the static or a set of dynamic routes is requested.
  806. We have a maximum of 99,990,000 posts we can make under this model
  807. As we have 10,000 * 10,000 posts which are indexable via the sitemap format.
  808. 1 top level index slot (10k posts) is taken by our static routes, the rest will be /posts.
  809. Passing ?xml=1 will result in an appropriate sitemap.xml instead.
  810. This is used to generate the static sitemaps as expected by search engines.
  811. Passing compressed=1 will gzip the output.
  812. =cut
  813. sub sitemap ($query, $render_cb) {
  814. my (@to_map, $is_index, $route_type);
  815. my $warning = '';
  816. $query->{map} //= '';
  817. if ($query->{map} eq 'static') {
  818. # Return the map of static routes
  819. $route_type = 'Static Routes';
  820. @to_map = grep { !defined $routes{$_}->{captures} && $_ !~ m/^default|login|auth$/ && !$routes{$_}->{auth} } keys(%routes);
  821. } elsif ( !$query->{map} ) {
  822. # Return the index instead
  823. @to_map = ('static');
  824. my $data = Trog::Data->new($conf);
  825. my $tot = $data->count();
  826. my $size = 50000;
  827. my $pages = int($tot / $size) + (($tot % $size) ? 1 : 0);
  828. # Truncate pages at 10k due to standard
  829. my $clamped = $pages > 49999 ? 49999 : $pages;
  830. $warning = "More posts than possible to represent in sitemaps & index! Old posts have been truncated." if $pages > 49999;
  831. foreach my $page ($clamped..1) {
  832. push(@to_map, "$page");
  833. }
  834. $is_index = 1;
  835. } else {
  836. $route_type = "Posts: Page $query->{map}";
  837. # Return the map of the particular range of dynamic posts
  838. $query->{limit} = 50000;
  839. $query->{page} = $query->{map};
  840. @to_map = _post_helper($query, [], ['public']);
  841. }
  842. if ( $query->{xml} ) {
  843. my $sm;
  844. my $xml_date = time();
  845. my $fmt = "xml";
  846. $fmt .= ".gz" if $query->{compressed};
  847. if ( !$query->{map}) {
  848. require WWW::SitemapIndex::XML;
  849. $sm = WWW::SitemapIndex::XML->new();
  850. foreach my $url (@to_map) {
  851. $sm->add(
  852. loc => "http://$query->{domain}/sitemap/$url.$fmt",
  853. lastmod => $xml_date,
  854. );
  855. }
  856. } else {
  857. require WWW::Sitemap::XML;
  858. $sm = WWW::Sitemap::XML->new();
  859. my $changefreq = $query->{map} eq 'static' ? 'monthly' : 'daily';
  860. foreach my $url (@to_map) {
  861. my $true_uri = "http://$query->{domain}$url";
  862. if (ref $url eq 'HASH') {
  863. my $is_user_page = grep { $_ eq 'about' } @{$url->{tags}};
  864. use Data::Dumper;
  865. print Dumper($url);
  866. $true_uri = "http://$query->{domain}/posts/$url->{id}";
  867. $true_uri = "http://$query->{domain}/users/$url->{title}" if $is_user_page;
  868. }
  869. my %data = (
  870. loc => $true_uri,
  871. lastmod => $xml_date,
  872. mobile => 1,
  873. changefreq => $changefreq,
  874. priority => 1.0,
  875. );
  876. if (ref $url eq 'HASH') {
  877. #add video & preview image if applicable
  878. $data{images} = [{
  879. loc => "http://$query->{domain}$url->{href}",
  880. caption => $url->{data},
  881. title => substr($url->{title},0,100),
  882. }] if $url->{is_image};
  883. $data{videos} = [{
  884. content_loc => "http://$query->{domain}$url->{href}",
  885. thumbnail_loc => "http://$query->{domain}$url->{preview}",
  886. title => substr($url->{title},0,100),
  887. description => $url->{data},
  888. }] if $url->{is_video};
  889. }
  890. $sm->add(%data);
  891. }
  892. }
  893. my $xml = $sm->as_xml();
  894. require IO::String;
  895. my $buf = IO::String->new();
  896. my $ct = 'application/xml';
  897. $xml->toFH($buf, 0);
  898. seek $buf, 0, 0;
  899. if ($query->{compressed}) {
  900. require IO::Compress::Gzip;
  901. my $compressed = IO::String->new();
  902. IO::Compress::Gzip::gzip($buf => $compressed);
  903. $ct = 'application/gzip';
  904. $buf = $compressed;
  905. seek $compressed, 0, 0;
  906. }
  907. return [200,["Content-type" => $ct], $buf];
  908. }
  909. @to_map = sort @to_map unless $is_index;
  910. my $processor = Text::Xslate->new(
  911. path => _dir_for_resource('sitemap.tx'),
  912. );
  913. my $styles = _build_themed_styles('sitemap.css');
  914. $query->{title} = "$query->{domain} : Sitemap";
  915. my $content = $processor->render('sitemap.tx', {
  916. title => "Site Map",
  917. to_map => \@to_map,
  918. is_index => $is_index,
  919. route_type => $route_type,
  920. route => $query->{route},
  921. });
  922. return Trog::Routes::HTML::index($query, $render_cb,$content,$styles);
  923. }
  924. sub _rss ($query,$posts) {
  925. require XML::RSS;
  926. my $rss = XML::RSS->new (version => '2.0');
  927. my $now = DateTime->from_epoch(epoch => time());
  928. $rss->channel(
  929. title => "$query->{domain}",
  930. link => "http://$query->{domain}/$query->{route}?format=rss",
  931. language => 'en', #TODO localization
  932. description => "$query->{domain} : $query->{route}",
  933. pubDate => $now,
  934. lastBuildDate => $now,
  935. );
  936. #TODO configurability
  937. $rss->image(
  938. title => $query->{domain},
  939. url => "$td/img/icon/favicon.ico",
  940. link => "http://$query->{domain}",
  941. width => 88,
  942. height => 31,
  943. description => "$query->{domain} favicon",
  944. );
  945. foreach my $post (@$posts) {
  946. my $url = "http://$query->{domain}/posts/$post->{id}";
  947. $rss->add_item(
  948. title => $post->{title},
  949. permaLink => $url,
  950. link => $url,
  951. enclosure => { url => $url, type=>"text/html" },
  952. description => "<![CDATA[$post->{data}]]>",
  953. pubDate => DateTime->from_epoch(epoch => $post->{created} ), #TODO format like Thu, 23 Aug 1999 07:00:00 GMT
  954. author => $post->{user}, #TODO translate to "email (user)" format
  955. );
  956. }
  957. require Encode;
  958. return [200, ["Content-type" => "application/rss+xml"], [Encode::encode_utf8($rss->as_string)]];
  959. }
  960. =head2 manual
  961. Implements the /manual and /lib/* routes.
  962. Basically a thin wrapper around Pod::Html.
  963. =cut
  964. sub manual ($query, $render_cb) {
  965. require Pod::Html;
  966. require Capture::Tiny;
  967. return forbidden($query, $render_cb) unless grep { $_ eq 'admin' } @{$query->{acls}};
  968. #Fix links from Pod::HTML
  969. $query->{module} =~ s/\.html$//g if $query->{module};
  970. my $infile = $query->{module} ? "$query->{module}.pm" : 'tCMS/Manual.pod';
  971. return notfound($query,$render_cb) unless -f "lib/$infile";
  972. my $content = capture { Pod::Html::pod2html(qw{--podpath=lib --podroot=.},"--infile=lib/$infile") };
  973. my @series = _get_series(1);
  974. return $render_cb->('manual.tx', {
  975. title => 'tCMS Manual',
  976. theme_dir => $td,
  977. content => $content,
  978. categories => \@series,
  979. stylesheets => _build_themed_styles('post.css'),
  980. });
  981. }
  982. # Deal with Params which may or may not be arrays
  983. sub _coerce_array ($param) {
  984. my $p = $param || [];
  985. $p = [$param] if $param && (ref $param ne 'ARRAY');
  986. return $p;
  987. }
  988. sub _build_themed_styles ($style) {
  989. my @styles;
  990. @styles = ("/styles/$style") if -f "www/styles/$style";
  991. my $ts = _themed_style($style);
  992. push(@styles, $ts) if $theme_dir && -f "www/$ts";
  993. return \@styles;
  994. }
  995. sub _build_themed_scripts ($script) {
  996. my @scripts = ("/scripts/$script");
  997. my $ts = _themed_style($script);
  998. push(@scripts, $ts) if $theme_dir && -f "www/$ts";
  999. return \@scripts;
  1000. }
  1001. sub _pick_processor($file, $normal, $themed) {
  1002. return _dir_for_resource($file) eq $template_dir ? $normal : $themed;
  1003. }
  1004. # Pick appropriate dir based on whether theme override exists
  1005. sub _dir_for_resource ($resource) {
  1006. return $theme_dir && -f "www/$theme_dir/$resource" ? $theme_dir : $template_dir;
  1007. }
  1008. sub _themed_style ($resource) {
  1009. return _dir_for_resource("styles/$resource")."/styles/$resource";
  1010. }
  1011. sub _themed_script ($resource) {
  1012. return _dir_for_resource("scripts/$resource")."/scripts/$resource";
  1013. }
  1014. 1;