HTML.pm 46 KB

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