summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/aggregate.pm
blob: a9c7447fa8faf6a082e714b84cd203f2c4e3355d (plain)
  1. #!/usr/bin/perl
  2. # Feed aggregation plugin.
  3. package IkiWiki::Plugin::aggregate;
  4. use warnings;
  5. use strict;
  6. use IkiWiki 2.00;
  7. use HTML::Parser;
  8. use HTML::Tagset;
  9. use HTML::Entities;
  10. use URI;
  11. use open qw{:utf8 :std};
  12. my %feeds;
  13. my %guids;
  14. sub import { #{{{
  15. hook(type => "getopt", id => "aggregate", call => \&getopt);
  16. hook(type => "checkconfig", id => "aggregate", call => \&checkconfig);
  17. hook(type => "needsbuild", id => "aggregate", call => \&needsbuild);
  18. hook(type => "preprocess", id => "aggregate", call => \&preprocess);
  19. hook(type => "delete", id => "aggregate", call => \&delete);
  20. hook(type => "savestate", id => "aggregate", call => \&savestate);
  21. if (exists $config{aggregate_webtrigger} && $config{aggregate_webtrigger}) {
  22. hook(type => "cgi", id => "aggregate", call => \&cgi);
  23. }
  24. } # }}}
  25. sub getopt () { #{{{
  26. eval q{use Getopt::Long};
  27. error($@) if $@;
  28. Getopt::Long::Configure('pass_through');
  29. GetOptions("aggregate" => \$config{aggregate});
  30. } #}}}
  31. sub checkconfig () { #{{{
  32. if ($config{aggregate} && ! ($config{post_commit} &&
  33. IkiWiki::commit_hook_enabled())) {
  34. launchaggregation();
  35. }
  36. } #}}}
  37. sub cgi ($) { #{{{
  38. my $cgi=shift;
  39. if (defined $cgi->param('do') &&
  40. $cgi->param("do") eq "aggregate_webtrigger") {
  41. $|=1;
  42. print "Content-Type: text/plain\n\n";
  43. $config{cgi}=0;
  44. $config{verbose}=1;
  45. $config{syslog}=0;
  46. print gettext("Aggregation triggered via web.")."\n\n";
  47. if (launchaggregation()) {
  48. IkiWiki::lockwiki();
  49. IkiWiki::loadindex();
  50. require IkiWiki::Render;
  51. IkiWiki::refresh();
  52. IkiWiki::saveindex();
  53. }
  54. else {
  55. print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
  56. }
  57. exit 0;
  58. }
  59. } #}}}
  60. sub launchaggregation () { #{{{
  61. # See if any feeds need aggregation.
  62. loadstate();
  63. my @feeds=needsaggregate();
  64. return unless @feeds;
  65. if (! lockaggregate()) {
  66. debug("an aggregation process is already running");
  67. return;
  68. }
  69. # force a later rebuild of source pages
  70. $IkiWiki::forcerebuild{$_->{sourcepage}}=1
  71. foreach @feeds;
  72. # Fork a child process to handle the aggregation.
  73. # The parent process will then handle building the
  74. # result. This avoids messy code to clear state
  75. # accumulated while aggregating.
  76. defined(my $pid = fork) or error("Can't fork: $!");
  77. if (! $pid) {
  78. IkiWiki::loadindex();
  79. # Aggregation happens without the main wiki lock
  80. # being held. This allows editing pages etc while
  81. # aggregation is running.
  82. aggregate(@feeds);
  83. IkiWiki::lockwiki;
  84. # Merge changes, since aggregation state may have
  85. # changed on disk while the aggregation was happening.
  86. mergestate();
  87. expire();
  88. savestate();
  89. IkiWiki::unlockwiki;
  90. exit 0;
  91. }
  92. waitpid($pid,0);
  93. if ($?) {
  94. error "aggregation failed with code $?";
  95. }
  96. clearstate();
  97. unlockaggregate();
  98. return 1;
  99. } #}}}
  100. sub needsbuild (@) { #{{{
  101. my $needsbuild=shift;
  102. loadstate();
  103. foreach my $feed (values %feeds) {
  104. if (exists $pagesources{$feed->{sourcepage}} &&
  105. grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
  106. # Mark all feeds originating on this page as
  107. # not yet seen; preprocess will unmark those that
  108. # still exist.
  109. markunseen($feed->{sourcepage});
  110. }
  111. }
  112. } # }}}
  113. sub preprocess (@) { #{{{
  114. my %params=@_;
  115. foreach my $required (qw{name url}) {
  116. if (! exists $params{$required}) {
  117. return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
  118. }
  119. }
  120. my $feed={};
  121. my $name=$params{name};
  122. if (exists $feeds{$name}) {
  123. $feed=$feeds{$name};
  124. }
  125. else {
  126. $feeds{$name}=$feed;
  127. }
  128. $feed->{name}=$name;
  129. $feed->{sourcepage}=$params{page};
  130. $feed->{url}=$params{url};
  131. my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
  132. $dir=~s/^\/+//;
  133. ($dir)=$dir=~/$config{wiki_file_regexp}/;
  134. $feed->{dir}=$dir;
  135. $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
  136. $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
  137. $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
  138. $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
  139. delete $feed->{unseen};
  140. $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
  141. $feed->{numposts}=0 unless defined $feed->{numposts};
  142. $feed->{newposts}=0 unless defined $feed->{newposts};
  143. $feed->{message}=gettext("new feed") unless defined $feed->{message};
  144. $feed->{error}=0 unless defined $feed->{error};
  145. $feed->{tags}=[];
  146. while (@_) {
  147. my $key=shift;
  148. my $value=shift;
  149. if ($key eq 'tag') {
  150. push @{$feed->{tags}}, $value;
  151. }
  152. }
  153. return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
  154. ($feed->{error} ? "<em>" : "").$feed->{message}.
  155. ($feed->{error} ? "</em>" : "").
  156. " (".$feed->{numposts}." ".gettext("posts").
  157. ($feed->{newposts} ? "; ".$feed->{newposts}.
  158. " ".gettext("new") : "").
  159. ")";
  160. } # }}}
  161. sub delete (@) { #{{{
  162. my @files=@_;
  163. # Remove feed data for removed pages.
  164. foreach my $file (@files) {
  165. my $page=pagename($file);
  166. markunseen($page);
  167. }
  168. } #}}}
  169. sub markunseen ($) { #{{{
  170. my $page=shift;
  171. foreach my $id (keys %feeds) {
  172. if ($feeds{$id}->{sourcepage} eq $page) {
  173. $feeds{$id}->{unseen}=1;
  174. }
  175. }
  176. } #}}}
  177. my $state_loaded=0;
  178. sub loadstate () { #{{{
  179. return if $state_loaded;
  180. $state_loaded=1;
  181. if (-e "$config{wikistatedir}/aggregate") {
  182. open(IN, "$config{wikistatedir}/aggregate") ||
  183. die "$config{wikistatedir}/aggregate: $!";
  184. while (<IN>) {
  185. $_=IkiWiki::possibly_foolish_untaint($_);
  186. chomp;
  187. my $data={};
  188. foreach my $i (split(/ /, $_)) {
  189. my ($field, $val)=split(/=/, $i, 2);
  190. if ($field eq "name" || $field eq "feed" ||
  191. $field eq "guid" || $field eq "message") {
  192. $data->{$field}=decode_entities($val, " \t\n");
  193. }
  194. elsif ($field eq "tag") {
  195. push @{$data->{tags}}, $val;
  196. }
  197. else {
  198. $data->{$field}=$val;
  199. }
  200. }
  201. if (exists $data->{name}) {
  202. $feeds{$data->{name}}=$data;
  203. }
  204. elsif (exists $data->{guid}) {
  205. $guids{$data->{guid}}=$data;
  206. }
  207. }
  208. close IN;
  209. }
  210. } #}}}
  211. sub savestate () { #{{{
  212. return unless $state_loaded;
  213. garbage_collect();
  214. my $newfile="$config{wikistatedir}/aggregate.new";
  215. my $cleanup = sub { unlink($newfile) };
  216. open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
  217. foreach my $data (values %feeds, values %guids) {
  218. my @line;
  219. foreach my $field (keys %$data) {
  220. if ($field eq "name" || $field eq "feed" ||
  221. $field eq "guid" || $field eq "message") {
  222. push @line, "$field=".encode_entities($data->{$field}, " \t\n");
  223. }
  224. elsif ($field eq "tags") {
  225. push @line, "tag=$_" foreach @{$data->{tags}};
  226. }
  227. else {
  228. push @line, "$field=".$data->{$field};
  229. }
  230. }
  231. print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
  232. }
  233. close OUT || error("save $newfile: $!", $cleanup);
  234. rename($newfile, "$config{wikistatedir}/aggregate") ||
  235. error("rename $newfile: $!", $cleanup);
  236. } #}}}
  237. sub garbage_collect () { #{{{
  238. foreach my $name (keys %feeds) {
  239. # remove any feeds that were not seen while building the pages
  240. # that used to contain them
  241. if ($feeds{$name}->{unseen}) {
  242. delete $feeds{$name};
  243. }
  244. }
  245. foreach my $guid (values %guids) {
  246. # any guid whose feed is gone should be removed
  247. if (! exists $feeds{$guid->{feed}}) {
  248. unlink pagefile($guid->{page})
  249. if exists $guid->{page};
  250. delete $guids{$guid->{guid}};
  251. }
  252. # handle expired guids
  253. elsif ($guid->{expired} && exists $guid->{page}) {
  254. unlink pagefile($guid->{page});
  255. delete $guid->{page};
  256. delete $guid->{md5};
  257. }
  258. }
  259. } #}}}
  260. sub mergestate () { #{{{
  261. # Load the current state in from disk, and merge into it
  262. # values from the state in memory that might have changed
  263. # during aggregation.
  264. my %myfeeds=%feeds;
  265. my %myguids=%guids;
  266. clearstate();
  267. loadstate();
  268. # All that can change in feed state during aggregation is a few
  269. # fields.
  270. foreach my $name (keys %myfeeds) {
  271. if (exists $feeds{$name}) {
  272. foreach my $field (qw{message lastupdate numposts
  273. newposts error}) {
  274. $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
  275. }
  276. }
  277. }
  278. # New guids can be created during aggregation.
  279. # It's also possible that guids were removed from the on-disk state
  280. # while the aggregation was in process. That would only happen if
  281. # their feed was also removed, so any removed guids added back here
  282. # will be garbage collected later.
  283. foreach my $guid (keys %myguids) {
  284. if (! exists $guids{$guid}) {
  285. $guids{$guid}=$myguids{$guid};
  286. }
  287. }
  288. } #}}}
  289. sub clearstate () { #{{{
  290. %feeds=();
  291. %guids=();
  292. $state_loaded=0;
  293. } #}}}
  294. sub expire () { #{{{
  295. foreach my $feed (values %feeds) {
  296. next unless $feed->{expireage} || $feed->{expirecount};
  297. my $count=0;
  298. my %seen;
  299. foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
  300. grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
  301. values %guids) {
  302. if ($feed->{expireage}) {
  303. my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
  304. if ($days_old > $feed->{expireage}) {
  305. debug(sprintf(gettext("expiring %s (%s days old)"),
  306. $item->{page}, int($days_old)));
  307. $item->{expired}=1;
  308. }
  309. }
  310. elsif ($feed->{expirecount} &&
  311. $count >= $feed->{expirecount}) {
  312. debug(sprintf(gettext("expiring %s"), $item->{page}));
  313. $item->{expired}=1;
  314. }
  315. else {
  316. if (! $seen{$item->{page}}) {
  317. $seen{$item->{page}}=1;
  318. $count++;
  319. }
  320. }
  321. }
  322. }
  323. } #}}}
  324. sub needsaggregate () { #{{{
  325. return values %feeds if $config{rebuild};
  326. return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
  327. } #}}}
  328. sub aggregate (@) { #{{{
  329. eval q{use XML::Feed};
  330. error($@) if $@;
  331. eval q{use URI::Fetch};
  332. error($@) if $@;
  333. foreach my $feed (@_) {
  334. $feed->{lastupdate}=time;
  335. $feed->{newposts}=0;
  336. $feed->{message}=sprintf(gettext("processed ok at %s"),
  337. displaytime($feed->{lastupdate}));
  338. $feed->{error}=0;
  339. debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
  340. if (! length $feed->{feedurl}) {
  341. my @urls=XML::Feed->find_feeds($feed->{url});
  342. if (! @urls) {
  343. $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
  344. $feed->{error}=1;
  345. debug($feed->{message});
  346. next;
  347. }
  348. $feed->{feedurl}=pop @urls;
  349. }
  350. my $res=URI::Fetch->fetch($feed->{feedurl});
  351. if (! $res) {
  352. $feed->{message}=URI::Fetch->errstr;
  353. $feed->{error}=1;
  354. debug($feed->{message});
  355. next;
  356. }
  357. if ($res->status == URI::Fetch::URI_GONE()) {
  358. $feed->{message}=gettext("feed not found");
  359. $feed->{error}=1;
  360. debug($feed->{message});
  361. next;
  362. }
  363. my $content=$res->content;
  364. my $f=eval{XML::Feed->parse(\$content)};
  365. if ($@) {
  366. # One common cause of XML::Feed crashing is a feed
  367. # that contains invalid UTF-8 sequences. Convert
  368. # feed to ascii to try to work around.
  369. $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
  370. $content=Encode::decode_utf8($content);
  371. $f=eval{XML::Feed->parse(\$content)};
  372. }
  373. if ($@) {
  374. # Another possibility is badly escaped entities.
  375. $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
  376. $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
  377. $content=Encode::decode_utf8($content);
  378. $f=eval{XML::Feed->parse(\$content)};
  379. }
  380. if ($@) {
  381. $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
  382. $feed->{error}=1;
  383. debug($feed->{message});
  384. next;
  385. }
  386. if (! $f) {
  387. $feed->{message}=XML::Feed->errstr;
  388. $feed->{error}=1;
  389. debug($feed->{message});
  390. next;
  391. }
  392. foreach my $entry ($f->entries) {
  393. add_page(
  394. feed => $feed,
  395. copyright => $f->copyright,
  396. title => defined $entry->title ? decode_entities($entry->title) : "untitled",
  397. link => $entry->link,
  398. content => defined $entry->content->body ? $entry->content->body : "",
  399. guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
  400. ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
  401. );
  402. }
  403. }
  404. } #}}}
  405. sub add_page (@) { #{{{
  406. my %params=@_;
  407. my $feed=$params{feed};
  408. my $guid={};
  409. my $mtime;
  410. if (exists $guids{$params{guid}}) {
  411. # updating an existing post
  412. $guid=$guids{$params{guid}};
  413. return if $guid->{expired};
  414. }
  415. else {
  416. # new post
  417. $guid->{guid}=$params{guid};
  418. $guids{$params{guid}}=$guid;
  419. $mtime=$params{ctime};
  420. $feed->{numposts}++;
  421. $feed->{newposts}++;
  422. # assign it an unused page
  423. my $page=IkiWiki::titlepage($params{title});
  424. # escape slashes and periods in title so it doesn't specify
  425. # directory name or trigger ".." disallowing code.
  426. $page=~s!([/.])!"__".ord($1)."__"!eg;
  427. $page=$feed->{dir}."/".$page;
  428. ($page)=$page=~/$config{wiki_file_regexp}/;
  429. if (! defined $page || ! length $page) {
  430. $page=$feed->{dir}."/item";
  431. }
  432. my $c="";
  433. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  434. -e pagefile($page.$c)) {
  435. $c++
  436. }
  437. # Make sure that the file name isn't too long.
  438. # NB: This doesn't check for path length limits.
  439. my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
  440. if (defined $max && length(htmlfn($page)) >= $max) {
  441. $c="";
  442. $page=$feed->{dir}."/item";
  443. while (exists $IkiWiki::pagecase{lc $page.$c} ||
  444. -e pagefile($page.$c)) {
  445. $c++
  446. }
  447. }
  448. $guid->{page}=$page;
  449. debug(sprintf(gettext("creating new page %s"), $page));
  450. }
  451. $guid->{feed}=$feed->{name};
  452. # To write or not to write? Need to avoid writing unchanged pages
  453. # to avoid unneccessary rebuilding. The mtime from rss cannot be
  454. # trusted; let's use a digest.
  455. eval q{use Digest::MD5 'md5_hex'};
  456. error($@) if $@;
  457. require Encode;
  458. my $digest=md5_hex(Encode::encode_utf8($params{content}));
  459. return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
  460. $guid->{md5}=$digest;
  461. # Create the page.
  462. my $template=template("aggregatepost.tmpl", blind_cache => 1);
  463. $template->param(title => $params{title})
  464. if defined $params{title} && length($params{title});
  465. $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
  466. $template->param(name => $feed->{name});
  467. $template->param(url => $feed->{url});
  468. $template->param(copyright => $params{copyright})
  469. if defined $params{copyright} && length $params{copyright};
  470. $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
  471. if defined $params{link};
  472. if (ref $feed->{tags}) {
  473. $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
  474. }
  475. writefile(htmlfn($guid->{page}), $config{srcdir},
  476. $template->output);
  477. # Set the mtime, this lets the build process get the right creation
  478. # time on record for the new page.
  479. utime $mtime, $mtime, pagefile($guid->{page})
  480. if defined $mtime && $mtime <= time;
  481. } #}}}
  482. sub htmlescape ($) { #{{{
  483. # escape accidental wikilinks and preprocessor stuff
  484. my $html=shift;
  485. $html=~s/(?<!\\)\[\[/\\\[\[/g;
  486. return $html;
  487. } #}}}
  488. sub urlabs ($$) { #{{{
  489. my $url=shift;
  490. my $urlbase=shift;
  491. URI->new_abs($url, $urlbase)->as_string;
  492. } #}}}
  493. sub htmlabs ($$) { #{{{
  494. # Convert links in html from relative to absolute.
  495. # Note that this is a heuristic, which is not specified by the rss
  496. # spec and may not be right for all feeds. Also, see Debian
  497. # bug #381359.
  498. my $html=shift;
  499. my $urlbase=shift;
  500. my $ret="";
  501. my $p = HTML::Parser->new(api_version => 3);
  502. $p->handler(default => sub { $ret.=join("", @_) }, "text");
  503. $p->handler(start => sub {
  504. my ($tagname, $pos, $text) = @_;
  505. if (ref $HTML::Tagset::linkElements{$tagname}) {
  506. while (4 <= @$pos) {
  507. # use attribute sets from right to left
  508. # to avoid invalidating the offsets
  509. # when replacing the values
  510. my($k_offset, $k_len, $v_offset, $v_len) =
  511. splice(@$pos, -4);
  512. my $attrname = lc(substr($text, $k_offset, $k_len));
  513. next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
  514. next unless $v_offset; # 0 v_offset means no value
  515. my $v = substr($text, $v_offset, $v_len);
  516. $v =~ s/^([\'\"])(.*)\1$/$2/;
  517. my $new_v=urlabs($v, $urlbase);
  518. $new_v =~ s/\"/&quot;/g; # since we quote with ""
  519. substr($text, $v_offset, $v_len) = qq("$new_v");
  520. }
  521. }
  522. $ret.=$text;
  523. }, "tagname, tokenpos, text");
  524. $p->parse($html);
  525. $p->eof;
  526. return $ret;
  527. } #}}}
  528. sub pagefile ($) { #{{{
  529. my $page=shift;
  530. return "$config{srcdir}/".htmlfn($page);
  531. } #}}}
  532. sub htmlfn ($) { #{{{
  533. return shift().".".$config{htmlext};
  534. } #}}}
  535. my $aggregatelock;
  536. sub lockaggregate () { #{{{
  537. # Take an exclusive lock to prevent multiple concurrent aggregators.
  538. # Returns true if the lock was aquired.
  539. if (! -d $config{wikistatedir}) {
  540. mkdir($config{wikistatedir});
  541. }
  542. open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
  543. error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
  544. if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
  545. close($aggregatelock) || error("failed closing aggregatelock: $!");
  546. return 0;
  547. }
  548. return 1;
  549. } #}}}
  550. sub unlockaggregate () { #{{{
  551. return close($aggregatelock) if $aggregatelock;
  552. return;
  553. } #}}}
  554. 1