HTML.pm 46 KB

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