HTML.pm 48 KB

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