HTML.pm 46 KB

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