HTML.pm 48 KB

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