summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/inline.pm
blob: 9d7d4b0fd832d32aa7c00ece7ede97ca1847508f (plain)
  1. #!/usr/bin/perl
  2. # Page inlining and blogging.
  3. package IkiWiki::Plugin::inline;
  4. use warnings;
  5. use strict;
  6. use Encode;
  7. use IkiWiki 3.00;
  8. use URI;
  9. my %knownfeeds;
  10. my %page_numfeeds;
  11. my @inline;
  12. my $nested=0;
  13. sub import {
  14. hook(type => "getopt", id => "inline", call => \&getopt);
  15. hook(type => "getsetup", id => "inline", call => \&getsetup);
  16. hook(type => "checkconfig", id => "inline", call => \&checkconfig);
  17. hook(type => "sessioncgi", id => "inline", call => \&sessioncgi);
  18. hook(type => "preprocess", id => "inline",
  19. call => \&IkiWiki::preprocess_inline);
  20. hook(type => "pagetemplate", id => "inline",
  21. call => \&IkiWiki::pagetemplate_inline);
  22. hook(type => "format", id => "inline", call => \&format, first => 1);
  23. # Hook to change to do pinging since it's called late.
  24. # This ensures each page only pings once and prevents slow
  25. # pings interrupting page builds.
  26. hook(type => "change", id => "inline", call => \&IkiWiki::pingurl);
  27. }
  28. sub getopt () {
  29. eval q{use Getopt::Long};
  30. error($@) if $@;
  31. Getopt::Long::Configure('pass_through');
  32. GetOptions(
  33. "rss!" => \$config{rss},
  34. "atom!" => \$config{atom},
  35. "allowrss!" => \$config{allowrss},
  36. "allowatom!" => \$config{allowatom},
  37. "pingurl=s" => sub {
  38. push @{$config{pingurl}}, $_[1];
  39. },
  40. );
  41. }
  42. sub getsetup () {
  43. return
  44. plugin => {
  45. safe => 1,
  46. rebuild => undef,
  47. },
  48. rss => {
  49. type => "boolean",
  50. example => 0,
  51. description => "enable rss feeds by default?",
  52. safe => 1,
  53. rebuild => 1,
  54. },
  55. atom => {
  56. type => "boolean",
  57. example => 0,
  58. description => "enable atom feeds by default?",
  59. safe => 1,
  60. rebuild => 1,
  61. },
  62. allowrss => {
  63. type => "boolean",
  64. example => 0,
  65. description => "allow rss feeds to be used?",
  66. safe => 1,
  67. rebuild => 1,
  68. },
  69. allowatom => {
  70. type => "boolean",
  71. example => 0,
  72. description => "allow atom feeds to be used?",
  73. safe => 1,
  74. rebuild => 1,
  75. },
  76. pingurl => {
  77. type => "string",
  78. example => "http://rpc.technorati.com/rpc/ping",
  79. description => "urls to ping (using XML-RPC) on feed update",
  80. safe => 1,
  81. rebuild => 0,
  82. },
  83. }
  84. sub checkconfig () {
  85. if (($config{rss} || $config{atom}) && ! length $config{url}) {
  86. error(gettext("Must specify url to wiki with --url when using --rss or --atom"));
  87. }
  88. if ($config{rss}) {
  89. push @{$config{wiki_file_prune_regexps}}, qr/\.rss$/;
  90. }
  91. if ($config{atom}) {
  92. push @{$config{wiki_file_prune_regexps}}, qr/\.atom$/;
  93. }
  94. if (! exists $config{pingurl}) {
  95. $config{pingurl}=[];
  96. }
  97. }
  98. sub format (@) {
  99. my %params=@_;
  100. # Fill in the inline content generated earlier. This is actually an
  101. # optimisation.
  102. $params{content}=~s{<div class="inline" id="([^"]+)"></div>}{
  103. delete @inline[$1,]
  104. }eg;
  105. return $params{content};
  106. }
  107. sub sessioncgi ($$) {
  108. my $q=shift;
  109. my $session=shift;
  110. if ($q->param('do') eq 'blog') {
  111. my $page=titlepage(decode_utf8($q->param('title')));
  112. $page=~s/(\/)/"__".ord($1)."__"/eg; # don't create subdirs
  113. # if the page already exists, munge it to be unique
  114. my $from=$q->param('from');
  115. my $add="";
  116. while (exists $IkiWiki::pagecase{lc($from."/".$page.$add)}) {
  117. $add=1 unless length $add;
  118. $add++;
  119. }
  120. $q->param('page', $page.$add);
  121. # now go create the page
  122. $q->param('do', 'create');
  123. # make sure the editpage plugin in loaded
  124. if (IkiWiki->can("cgi_editpage")) {
  125. IkiWiki::cgi_editpage($q, $session);
  126. }
  127. else {
  128. error(gettext("page editing not allowed"));
  129. }
  130. exit;
  131. }
  132. }
  133. # Back to ikiwiki namespace for the rest, this code is very much
  134. # internal to ikiwiki even though it's separated into a plugin.
  135. package IkiWiki;
  136. my %toping;
  137. my %feedlinks;
  138. sub preprocess_inline (@) {
  139. my %params=@_;
  140. if (! exists $params{pages}) {
  141. error gettext("missing pages parameter");
  142. }
  143. my $raw=yesno($params{raw});
  144. my $archive=yesno($params{archive});
  145. my $rss=(($config{rss} || $config{allowrss}) && exists $params{rss}) ? yesno($params{rss}) : $config{rss};
  146. my $atom=(($config{atom} || $config{allowatom}) && exists $params{atom}) ? yesno($params{atom}) : $config{atom};
  147. my $quick=exists $params{quick} ? yesno($params{quick}) : 0;
  148. my $feeds=exists $params{feeds} ? yesno($params{feeds}) : !$quick;
  149. my $emptyfeeds=exists $params{emptyfeeds} ? yesno($params{emptyfeeds}) : 1;
  150. my $feedonly=yesno($params{feedonly});
  151. if (! exists $params{show} && ! $archive) {
  152. $params{show}=10;
  153. }
  154. if (! exists $params{feedshow} && exists $params{show}) {
  155. $params{feedshow}=$params{show};
  156. }
  157. my $desc;
  158. if (exists $params{description}) {
  159. $desc = $params{description}
  160. }
  161. else {
  162. $desc = $config{wikiname};
  163. }
  164. my $actions=yesno($params{actions});
  165. if (exists $params{template}) {
  166. $params{template}=~s/[^-_a-zA-Z0-9]+//g;
  167. }
  168. else {
  169. $params{template} = $archive ? "archivepage" : "inlinepage";
  170. }
  171. my @list;
  172. foreach my $page (keys %pagesources) {
  173. next if $page eq $params{page};
  174. if (pagespec_match($page, $params{pages}, location => $params{page})) {
  175. push @list, $page;
  176. }
  177. }
  178. if (exists $params{sort} && $params{sort} eq 'title') {
  179. @list=sort { pagetitle(basename($a)) cmp pagetitle(basename($b)) } @list;
  180. }
  181. elsif (exists $params{sort} && $params{sort} eq 'title_natural') {
  182. eval q{use Sort::Naturally};
  183. if ($@) {
  184. error(gettext("Sort::Naturally needed for title_natural sort"));
  185. }
  186. @list=sort { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) } @list;
  187. }
  188. elsif (exists $params{sort} && $params{sort} eq 'mtime') {
  189. @list=sort { $pagemtime{$b} <=> $pagemtime{$a} } @list;
  190. }
  191. elsif (! exists $params{sort} || $params{sort} eq 'age') {
  192. @list=sort { $pagectime{$b} <=> $pagectime{$a} } @list;
  193. }
  194. else {
  195. error sprintf(gettext("unknown sort type %s"), $params{sort});
  196. }
  197. if (yesno($params{reverse})) {
  198. @list=reverse(@list);
  199. }
  200. if (exists $params{skip}) {
  201. @list=@list[$params{skip} .. scalar @list - 1];
  202. }
  203. my @feedlist;
  204. if ($feeds) {
  205. if (exists $params{feedshow} &&
  206. $params{feedshow} && @list > $params{feedshow}) {
  207. @feedlist=@list[0..$params{feedshow} - 1];
  208. }
  209. else {
  210. @feedlist=@list;
  211. }
  212. }
  213. if ($params{show} && @list > $params{show}) {
  214. @list=@list[0..$params{show} - 1];
  215. }
  216. add_depends($params{page}, $params{pages});
  217. # Explicitly add all currently displayed pages as dependencies, so
  218. # that if they are removed or otherwise changed, the inline will be
  219. # sure to be updated.
  220. add_depends($params{page}, join(" or ", $#list >= $#feedlist ? @list : @feedlist));
  221. if ($feeds && exists $params{feedpages}) {
  222. @feedlist=grep { pagespec_match($_, $params{feedpages}, location => $params{page}) } @feedlist;
  223. }
  224. my ($feedbase, $feednum);
  225. if ($feeds) {
  226. # Ensure that multiple feeds on a page go to unique files.
  227. # Feedfile can lead to conflicts if usedirs is not enabled,
  228. # so avoid supporting it in that case.
  229. delete $params{feedfile} if ! $config{usedirs};
  230. # Tight limits on legal feedfiles, to avoid security issues
  231. # and conflicts.
  232. if (defined $params{feedfile}) {
  233. if ($params{feedfile} =~ /\// ||
  234. $params{feedfile} !~ /$config{wiki_file_regexp}/) {
  235. error("illegal feedfile");
  236. }
  237. $params{feedfile}=possibly_foolish_untaint($params{feedfile});
  238. }
  239. $feedbase=targetpage($params{destpage}, "", $params{feedfile});
  240. my $feedid=join("\0", $feedbase, map { $_."\0".$params{$_} } sort keys %params);
  241. if (exists $knownfeeds{$feedid}) {
  242. $feednum=$knownfeeds{$feedid};
  243. }
  244. else {
  245. if (exists $page_numfeeds{$params{destpage}}{$feedbase}) {
  246. if ($feeds) {
  247. $feednum=$knownfeeds{$feedid}=++$page_numfeeds{$params{destpage}}{$feedbase};
  248. }
  249. }
  250. else {
  251. $feednum=$knownfeeds{$feedid}="";
  252. if ($feeds) {
  253. $page_numfeeds{$params{destpage}}{$feedbase}=1;
  254. }
  255. }
  256. }
  257. }
  258. my $rssurl=abs2rel($feedbase."rss".$feednum, dirname(htmlpage($params{destpage}))) if $feeds && $rss;
  259. my $atomurl=abs2rel($feedbase."atom".$feednum, dirname(htmlpage($params{destpage}))) if $feeds && $atom;
  260. my $ret="";
  261. if (length $config{cgiurl} && ! $params{preview} && (exists $params{rootpage} ||
  262. (exists $params{postform} && yesno($params{postform}))) &&
  263. IkiWiki->can("cgi_editpage")) {
  264. # Add a blog post form, with feed buttons.
  265. my $formtemplate=template("blogpost.tmpl", blind_cache => 1);
  266. $formtemplate->param(cgiurl => $config{cgiurl});
  267. my $rootpage;
  268. if (exists $params{rootpage}) {
  269. $rootpage=bestlink($params{page}, $params{rootpage});
  270. if (!length $rootpage) {
  271. $rootpage=$params{rootpage};
  272. }
  273. }
  274. else {
  275. $rootpage=$params{page};
  276. }
  277. $formtemplate->param(rootpage => $rootpage);
  278. $formtemplate->param(rssurl => $rssurl) if $feeds && $rss;
  279. $formtemplate->param(atomurl => $atomurl) if $feeds && $atom;
  280. if (exists $params{postformtext}) {
  281. $formtemplate->param(postformtext =>
  282. $params{postformtext});
  283. }
  284. else {
  285. $formtemplate->param(postformtext =>
  286. gettext("Add a new post titled:"));
  287. }
  288. $ret.=$formtemplate->output;
  289. # The post form includes the feed buttons, so
  290. # emptyfeeds cannot be hidden.
  291. $emptyfeeds=1;
  292. }
  293. elsif ($feeds && !$params{preview} && ($emptyfeeds || @feedlist)) {
  294. # Add feed buttons.
  295. my $linktemplate=template("feedlink.tmpl", blind_cache => 1);
  296. $linktemplate->param(rssurl => $rssurl) if $rss;
  297. $linktemplate->param(atomurl => $atomurl) if $atom;
  298. $ret.=$linktemplate->output;
  299. }
  300. if (! $feedonly) {
  301. require HTML::Template;
  302. my @params=IkiWiki::template_params($params{template}.".tmpl", blind_cache => 1);
  303. if (! @params) {
  304. error sprintf(gettext("nonexistant template %s"), $params{template});
  305. }
  306. my $template=HTML::Template->new(@params) unless $raw;
  307. foreach my $page (@list) {
  308. my $file = $pagesources{$page};
  309. my $type = pagetype($file);
  310. if (! $raw || ($raw && ! defined $type)) {
  311. unless ($archive && $quick) {
  312. # Get the content before populating the
  313. # template, since getting the content uses
  314. # the same template if inlines are nested.
  315. my $content=get_inline_content($page, $params{destpage});
  316. $template->param(content => $content);
  317. }
  318. $template->param(pageurl => urlto(bestlink($params{page}, $page), $params{destpage}));
  319. $template->param(inlinepage => $page);
  320. $template->param(title => pagetitle(basename($page)));
  321. $template->param(ctime => displaytime($pagectime{$page}, $params{timeformat}));
  322. $template->param(mtime => displaytime($pagemtime{$page}, $params{timeformat}));
  323. $template->param(first => 1) if $page eq $list[0];
  324. $template->param(last => 1) if $page eq $list[$#list];
  325. if ($actions) {
  326. my $file = $pagesources{$page};
  327. my $type = pagetype($file);
  328. if ($config{discussion}) {
  329. my $discussionlink=gettext("discussion");
  330. if ($page !~ /.*\/\Q$discussionlink\E$/ &&
  331. (length $config{cgiurl} ||
  332. exists $links{$page."/".$discussionlink})) {
  333. $template->param(have_actions => 1);
  334. $template->param(discussionlink =>
  335. htmllink($page,
  336. $params{destpage},
  337. gettext("Discussion"),
  338. noimageinline => 1,
  339. forcesubpage => 1));
  340. }
  341. }
  342. if (length $config{cgiurl} && defined $type) {
  343. $template->param(have_actions => 1);
  344. $template->param(editurl => cgiurl(do => "edit", page => $page));
  345. }
  346. }
  347. run_hooks(pagetemplate => sub {
  348. shift->(page => $page, destpage => $params{destpage},
  349. template => $template,);
  350. });
  351. $ret.=$template->output;
  352. $template->clear_params;
  353. }
  354. else {
  355. if (defined $type) {
  356. $ret.="\n".
  357. linkify($page, $params{destpage},
  358. preprocess($page, $params{destpage},
  359. filter($page, $params{destpage},
  360. readfile(srcfile($file)))));
  361. }
  362. }
  363. }
  364. }
  365. if ($feeds && ($emptyfeeds || @feedlist)) {
  366. if ($rss) {
  367. my $rssp=$feedbase."rss".$feednum;
  368. will_render($params{destpage}, $rssp);
  369. if (! $params{preview}) {
  370. writefile($rssp, $config{destdir},
  371. genfeed("rss",
  372. $config{url}."/".$rssp, $desc, $params{guid}, $params{destpage}, @feedlist));
  373. $toping{$params{destpage}}=1 unless $config{rebuild};
  374. $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/rss+xml" title="$desc (RSS)" href="$rssurl" />};
  375. }
  376. }
  377. if ($atom) {
  378. my $atomp=$feedbase."atom".$feednum;
  379. will_render($params{destpage}, $atomp);
  380. if (! $params{preview}) {
  381. writefile($atomp, $config{destdir},
  382. genfeed("atom", $config{url}."/".$atomp, $desc, $params{guid}, $params{destpage}, @feedlist));
  383. $toping{$params{destpage}}=1 unless $config{rebuild};
  384. $feedlinks{$params{destpage}}.=qq{<link rel="alternate" type="application/atom+xml" title="$desc (Atom)" href="$atomurl" />};
  385. }
  386. }
  387. }
  388. return $ret if $raw || $nested;
  389. push @inline, $ret;
  390. return "<div class=\"inline\" id=\"$#inline\"></div>\n\n";
  391. }
  392. sub pagetemplate_inline (@) {
  393. my %params=@_;
  394. my $page=$params{page};
  395. my $template=$params{template};
  396. $template->param(feedlinks => $feedlinks{$page})
  397. if exists $feedlinks{$page} && $template->query(name => "feedlinks");
  398. }
  399. sub get_inline_content ($$) {
  400. my $page=shift;
  401. my $destpage=shift;
  402. my $file=$pagesources{$page};
  403. my $type=pagetype($file);
  404. if (defined $type) {
  405. $nested++;
  406. my $ret=htmlize($page, $destpage, $type,
  407. linkify($page, $destpage,
  408. preprocess($page, $destpage,
  409. filter($page, $destpage,
  410. readfile(srcfile($file))))));
  411. $nested--;
  412. return $ret;
  413. }
  414. else {
  415. return "";
  416. }
  417. }
  418. sub date_822 ($) {
  419. my $time=shift;
  420. my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
  421. POSIX::setlocale(&POSIX::LC_TIME, "C");
  422. my $ret=POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
  423. POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
  424. return $ret;
  425. }
  426. sub date_3339 ($) {
  427. my $time=shift;
  428. my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
  429. POSIX::setlocale(&POSIX::LC_TIME, "C");
  430. my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
  431. POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
  432. return $ret;
  433. }
  434. sub absolute_urls ($$) {
  435. # sucky sub because rss sucks
  436. my $content=shift;
  437. my $baseurl=shift;
  438. my $url=$baseurl;
  439. $url=~s/[^\/]+$//;
  440. # what is the non path part of the url?
  441. my $top_uri = URI->new($url);
  442. $top_uri->path_query(""); # reset the path
  443. my $urltop = $top_uri->as_string;
  444. $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(#[^"]+)"/$1 href="$baseurl$2"/mig;
  445. # relative to another wiki page
  446. $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)([^\/][^"]*)"/$1 href="$url$2"/mig;
  447. $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)([^\/][^"]*)"/$1 src="$url$2"/mig;
  448. # relative to the top of the site
  449. $content=~s/(<a(?:\s+(?:class|id)\s*="?\w+"?)?)\s+href=\s*"(?!\w+:)(\/[^"]*)"/$1 href="$urltop$2"/mig;
  450. $content=~s/(<img(?:\s+(?:class|id|width|height)\s*="?\w+"?)*)\s+src=\s*"(?!\w+:)(\/[^"]*)"/$1 src="$urltop$2"/mig;
  451. return $content;
  452. }
  453. sub genfeed ($$$$$@) {
  454. my $feedtype=shift;
  455. my $feedurl=shift;
  456. my $feeddesc=shift;
  457. my $guid=shift;
  458. my $page=shift;
  459. my @pages=@_;
  460. my $url=URI->new(encode_utf8(urlto($page,"",1)));
  461. my $itemtemplate=template($feedtype."item.tmpl", blind_cache => 1);
  462. my $content="";
  463. my $lasttime = 0;
  464. foreach my $p (@pages) {
  465. my $u=URI->new(encode_utf8(urlto($p, "", 1)));
  466. my $pcontent = absolute_urls(get_inline_content($p, $page), $url);
  467. $itemtemplate->param(
  468. title => pagetitle(basename($p)),
  469. url => $u,
  470. permalink => $u,
  471. cdate_822 => date_822($pagectime{$p}),
  472. mdate_822 => date_822($pagemtime{$p}),
  473. cdate_3339 => date_3339($pagectime{$p}),
  474. mdate_3339 => date_3339($pagemtime{$p}),
  475. );
  476. if (exists $pagestate{$p}) {
  477. if (exists $pagestate{$p}{meta}{guid}) {
  478. $itemtemplate->param(guid => $pagestate{$p}{meta}{guid});
  479. }
  480. if (exists $pagestate{$p}{meta}{updated}) {
  481. $itemtemplate->param(mdate_822 => date_822($pagestate{$p}{meta}{updated}));
  482. $itemtemplate->param(mdate_3339 => date_3339($pagestate{$p}{meta}{updated}));
  483. }
  484. }
  485. if ($itemtemplate->query(name => "enclosure")) {
  486. my $file=$pagesources{$p};
  487. my $type=pagetype($file);
  488. if (defined $type) {
  489. $itemtemplate->param(content => $pcontent);
  490. }
  491. else {
  492. my $size=(srcfile_stat($file))[8];
  493. my $mime="unknown";
  494. eval q{use File::MimeInfo};
  495. if (! $@) {
  496. $mime = mimetype($file);
  497. }
  498. $itemtemplate->param(
  499. enclosure => $u,
  500. type => $mime,
  501. length => $size,
  502. );
  503. }
  504. }
  505. else {
  506. $itemtemplate->param(content => $pcontent);
  507. }
  508. run_hooks(pagetemplate => sub {
  509. shift->(page => $p, destpage => $page,
  510. template => $itemtemplate);
  511. });
  512. $content.=$itemtemplate->output;
  513. $itemtemplate->clear_params;
  514. $lasttime = $pagemtime{$p} if $pagemtime{$p} > $lasttime;
  515. }
  516. my $template=template($feedtype."page.tmpl", blind_cache => 1);
  517. $template->param(
  518. title => $page ne "index" ? pagetitle($page) : $config{wikiname},
  519. wikiname => $config{wikiname},
  520. pageurl => $url,
  521. content => $content,
  522. feeddesc => $feeddesc,
  523. guid => $guid,
  524. feeddate => date_3339($lasttime),
  525. feedurl => $feedurl,
  526. version => $IkiWiki::version,
  527. );
  528. run_hooks(pagetemplate => sub {
  529. shift->(page => $page, destpage => $page,
  530. template => $template);
  531. });
  532. return $template->output;
  533. }
  534. sub pingurl (@) {
  535. return unless @{$config{pingurl}} && %toping;
  536. eval q{require RPC::XML::Client};
  537. if ($@) {
  538. debug(gettext("RPC::XML::Client not found, not pinging"));
  539. return;
  540. }
  541. # daemonize here so slow pings don't slow down wiki updates
  542. defined(my $pid = fork) or error("Can't fork: $!");
  543. return if $pid;
  544. chdir '/';
  545. POSIX::setsid() or error("Can't start a new session: $!");
  546. open STDIN, '/dev/null';
  547. open STDOUT, '>/dev/null';
  548. open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
  549. # Don't need to keep a lock on the wiki as a daemon.
  550. IkiWiki::unlockwiki();
  551. foreach my $page (keys %toping) {
  552. my $title=pagetitle(basename($page), 0);
  553. my $url=urlto($page, "", 1);
  554. foreach my $pingurl (@{$config{pingurl}}) {
  555. debug("Pinging $pingurl for $page");
  556. eval {
  557. my $client = RPC::XML::Client->new($pingurl);
  558. my $req = RPC::XML::request->new('weblogUpdates.ping',
  559. $title, $url);
  560. my $res = $client->send_request($req);
  561. if (! ref $res) {
  562. error("Did not receive response to ping");
  563. }
  564. my $r=$res->value;
  565. if (! exists $r->{flerror} || $r->{flerror}) {
  566. error("Ping rejected: ".(exists $r->{message} ? $r->{message} : "[unknown reason]"));
  567. }
  568. };
  569. if ($@) {
  570. error "Ping failed: $@";
  571. }
  572. }
  573. }
  574. exit 0; # daemon done
  575. }
  576. 1