2 # Feed aggregation plugin.
3 package IkiWiki::Plugin::aggregate;
12 use open qw{:utf8 :std};
18 hook(type => "getopt", id => "aggregate", call => \&getopt);
19 hook(type => "checkconfig", id => "aggregate", call => \&checkconfig);
20 hook(type => "needsbuild", id => "aggregate", call => \&needsbuild);
21 hook(type => "preprocess", id => "aggregate", call => \&preprocess);
22 hook(type => "delete", id => "aggregate", call => \&delete);
23 hook(type => "savestate", id => "aggregate", call => \&savestate);
24 if (exists $config{aggregate_webtrigger} && $config{aggregate_webtrigger}) {
25 hook(type => "cgi", id => "aggregate", call => \&cgi);
30 eval q{use Getopt::Long};
32 Getopt::Long::Configure('pass_through');
33 GetOptions("aggregate" => \$config{aggregate});
36 sub checkconfig () { #{{{
37 if ($config{aggregate} && ! ($config{post_commit} &&
38 IkiWiki::commit_hook_enabled())) {
46 if (defined $cgi->param('do') &&
47 $cgi->param("do") eq "aggregate_webtrigger") {
49 print "Content-Type: text/plain\n\n";
53 print gettext("Aggregation triggered via web.")."\n\n";
54 if (launchaggregation()) {
57 require IkiWiki::Render;
62 print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
68 sub launchaggregation () { #{{{
69 # See if any feeds need aggregation.
71 my @feeds=needsaggregate();
73 if (! lockaggregate()) {
74 debug("an aggregation process is already running");
77 # force a later rebuild of source pages
78 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
81 # Fork a child process to handle the aggregation.
82 # The parent process will then handle building the
83 # result. This avoids messy code to clear state
84 # accumulated while aggregating.
85 defined(my $pid = fork) or error("Can't fork: $!");
88 # Aggregation happens without the main wiki lock
89 # being held. This allows editing pages etc while
90 # aggregation is running.
94 # Merge changes, since aggregation state may have
95 # changed on disk while the aggregation was happening.
104 error "aggregation failed with code $?";
113 sub needsbuild (@) { #{{{
114 my $needsbuild=shift;
118 foreach my $feed (values %feeds) {
119 if (exists $pagesources{$feed->{sourcepage}} &&
120 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
121 # Mark all feeds originating on this page as
122 # not yet seen; preprocess will unmark those that
124 markunseen($feed->{sourcepage});
129 sub preprocess (@) { #{{{
132 foreach my $required (qw{name url}) {
133 if (! exists $params{$required}) {
134 return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
139 my $name=$params{name};
140 if (exists $feeds{$name}) {
147 $feed->{sourcepage}=$params{page};
148 $feed->{url}=$params{url};
149 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
151 ($dir)=$dir=~/$config{wiki_file_regexp}/;
153 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
154 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
155 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
156 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
157 delete $feed->{unseen};
158 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
159 $feed->{numposts}=0 unless defined $feed->{numposts};
160 $feed->{newposts}=0 unless defined $feed->{newposts};
161 $feed->{message}=gettext("new feed") unless defined $feed->{message};
162 $feed->{error}=0 unless defined $feed->{error};
168 push @{$feed->{tags}}, $value;
172 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
173 ($feed->{error} ? "<em>" : "").$feed->{message}.
174 ($feed->{error} ? "</em>" : "").
175 " (".$feed->{numposts}." ".gettext("posts").
176 ($feed->{newposts} ? "; ".$feed->{newposts}.
177 " ".gettext("new") : "").
181 sub delete (@) { #{{{
184 # Remove feed data for removed pages.
185 foreach my $file (@files) {
186 my $page=pagename($file);
191 sub markunseen ($) { #{{{
194 foreach my $id (keys %feeds) {
195 if ($feeds{$id}->{sourcepage} eq $page) {
196 $feeds{$id}->{unseen}=1;
203 sub loadstate () { #{{{
204 return if $state_loaded;
206 if (-e "$config{wikistatedir}/aggregate") {
207 open(IN, "$config{wikistatedir}/aggregate") ||
208 die "$config{wikistatedir}/aggregate: $!";
210 $_=IkiWiki::possibly_foolish_untaint($_);
213 foreach my $i (split(/ /, $_)) {
214 my ($field, $val)=split(/=/, $i, 2);
215 if ($field eq "name" || $field eq "feed" ||
216 $field eq "guid" || $field eq "message") {
217 $data->{$field}=decode_entities($val, " \t\n");
219 elsif ($field eq "tag") {
220 push @{$data->{tags}}, $val;
223 $data->{$field}=$val;
227 if (exists $data->{name}) {
228 $feeds{$data->{name}}=$data;
230 elsif (exists $data->{guid}) {
231 $guids{$data->{guid}}=$data;
239 sub savestate () { #{{{
240 return unless $state_loaded;
242 my $newfile="$config{wikistatedir}/aggregate.new";
243 my $cleanup = sub { unlink($newfile) };
244 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
245 foreach my $data (values %feeds, values %guids) {
247 foreach my $field (keys %$data) {
248 if ($field eq "name" || $field eq "feed" ||
249 $field eq "guid" || $field eq "message") {
250 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
252 elsif ($field eq "tags") {
253 push @line, "tag=$_" foreach @{$data->{tags}};
256 push @line, "$field=".$data->{$field};
259 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
261 close OUT || error("save $newfile: $!", $cleanup);
262 rename($newfile, "$config{wikistatedir}/aggregate") ||
263 error("rename $newfile: $!", $cleanup);
266 sub garbage_collect () { #{{{
267 foreach my $name (keys %feeds) {
268 # remove any feeds that were not seen while building the pages
269 # that used to contain them
270 if ($feeds{$name}->{unseen}) {
271 delete $feeds{$name};
275 foreach my $guid (values %guids) {
276 # any guid whose feed is gone should be removed
277 if (! exists $feeds{$guid->{feed}}) {
278 unlink pagefile($guid->{page})
279 if exists $guid->{page};
280 delete $guids{$guid->{guid}};
282 # handle expired guids
283 elsif ($guid->{expired} && exists $guid->{page}) {
284 unlink pagefile($guid->{page});
285 delete $guid->{page};
291 sub mergestate () { #{{{
292 # Load the current state in from disk, and merge into it
293 # values from the state in memory that might have changed
294 # during aggregation.
300 # All that can change in feed state during aggregation is a few
302 foreach my $name (keys %myfeeds) {
303 if (exists $feeds{$name}) {
304 foreach my $field (qw{message lastupdate numposts
306 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
311 # New guids can be created during aggregation.
312 # It's also possible that guids were removed from the on-disk state
313 # while the aggregation was in process. That would only happen if
314 # their feed was also removed, so any removed guids added back here
315 # will be garbage collected later.
316 foreach my $guid (keys %myguids) {
317 if (! exists $guids{$guid}) {
318 $guids{$guid}=$myguids{$guid};
323 sub clearstate () { #{{{
330 foreach my $feed (values %feeds) {
331 next unless $feed->{expireage} || $feed->{expirecount};
334 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
335 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
337 if ($feed->{expireage}) {
338 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
339 if ($days_old > $feed->{expireage}) {
340 debug(sprintf(gettext("expiring %s (%s days old)"),
341 $item->{page}, int($days_old)));
345 elsif ($feed->{expirecount} &&
346 $count >= $feed->{expirecount}) {
347 debug(sprintf(gettext("expiring %s"), $item->{page}));
351 if (! $seen{$item->{page}}) {
352 $seen{$item->{page}}=1;
360 sub needsaggregate () { #{{{
361 return values %feeds if $config{rebuild};
362 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
365 sub aggregate (@) { #{{{
366 eval q{use XML::Feed};
368 eval q{use URI::Fetch};
371 foreach my $feed (@_) {
372 $feed->{lastupdate}=time;
374 $feed->{message}=sprintf(gettext("processed ok at %s"),
375 displaytime($feed->{lastupdate}));
378 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
380 if (! length $feed->{feedurl}) {
381 my @urls=XML::Feed->find_feeds($feed->{url});
383 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
385 debug($feed->{message});
388 $feed->{feedurl}=pop @urls;
390 my $res=URI::Fetch->fetch($feed->{feedurl});
392 $feed->{message}=URI::Fetch->errstr;
394 debug($feed->{message});
397 if ($res->status == URI::Fetch::URI_GONE()) {
398 $feed->{message}=gettext("feed not found");
400 debug($feed->{message});
403 my $content=$res->content;
404 my $f=eval{XML::Feed->parse(\$content)};
406 # One common cause of XML::Feed crashing is a feed
407 # that contains invalid UTF-8 sequences. Convert
408 # feed to ascii to try to work around.
409 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
410 $content=Encode::decode_utf8($content);
411 $f=eval{XML::Feed->parse(\$content)};
414 # Another possibility is badly escaped entities.
415 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
416 $content=~s/\&(?!amp)(\w+);/&$1;/g;
417 $content=Encode::decode_utf8($content);
418 $f=eval{XML::Feed->parse(\$content)};
421 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
423 debug($feed->{message});
427 $feed->{message}=XML::Feed->errstr;
429 debug($feed->{message});
433 foreach my $entry ($f->entries) {
436 copyright => $f->copyright,
437 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
438 link => $entry->link,
439 content => defined $entry->content->body ? $entry->content->body : "",
440 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
441 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
447 sub add_page (@) { #{{{
450 my $feed=$params{feed};
453 if (exists $guids{$params{guid}}) {
454 # updating an existing post
455 $guid=$guids{$params{guid}};
456 return if $guid->{expired};
460 $guid->{guid}=$params{guid};
461 $guids{$params{guid}}=$guid;
462 $mtime=$params{ctime};
466 # assign it an unused page
467 my $page=IkiWiki::titlepage($params{title});
468 # escape slashes and periods in title so it doesn't specify
469 # directory name or trigger ".." disallowing code.
470 $page=~s!([/.])!"__".ord($1)."__"!eg;
471 $page=$feed->{dir}."/".$page;
472 ($page)=$page=~/$config{wiki_file_regexp}/;
473 if (! defined $page || ! length $page) {
474 $page=$feed->{dir}."/item";
477 while (exists $IkiWiki::pagecase{lc $page.$c} ||
478 -e pagefile($page.$c)) {
482 # Make sure that the file name isn't too long.
483 # NB: This doesn't check for path length limits.
484 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
485 if (defined $max && length(htmlfn($page)) >= $max) {
487 $page=$feed->{dir}."/item";
488 while (exists $IkiWiki::pagecase{lc $page.$c} ||
489 -e pagefile($page.$c)) {
495 debug(sprintf(gettext("creating new page %s"), $page));
497 $guid->{feed}=$feed->{name};
499 # To write or not to write? Need to avoid writing unchanged pages
500 # to avoid unneccessary rebuilding. The mtime from rss cannot be
501 # trusted; let's use a digest.
502 eval q{use Digest::MD5 'md5_hex'};
505 my $digest=md5_hex(Encode::encode_utf8($params{content}));
506 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
507 $guid->{md5}=$digest;
510 my $template=template("aggregatepost.tmpl", blind_cache => 1);
511 $template->param(title => $params{title})
512 if defined $params{title} && length($params{title});
513 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
514 $template->param(name => $feed->{name});
515 $template->param(url => $feed->{url});
516 $template->param(copyright => $params{copyright})
517 if defined $params{copyright} && length $params{copyright};
518 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
519 if defined $params{link};
520 if (ref $feed->{tags}) {
521 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
523 writefile(htmlfn($guid->{page}), $config{srcdir},
526 # Set the mtime, this lets the build process get the right creation
527 # time on record for the new page.
528 utime $mtime, $mtime, pagefile($guid->{page})
529 if defined $mtime && $mtime <= time;
532 sub htmlescape ($) { #{{{
533 # escape accidental wikilinks and preprocessor stuff
535 $html=~s/(?<!\\)\[\[/\\\[\[/g;
539 sub urlabs ($$) { #{{{
543 URI->new_abs($url, $urlbase)->as_string;
546 sub htmlabs ($$) { #{{{
547 # Convert links in html from relative to absolute.
548 # Note that this is a heuristic, which is not specified by the rss
549 # spec and may not be right for all feeds. Also, see Debian
555 my $p = HTML::Parser->new(api_version => 3);
556 $p->handler(default => sub { $ret.=join("", @_) }, "text");
557 $p->handler(start => sub {
558 my ($tagname, $pos, $text) = @_;
559 if (ref $HTML::Tagset::linkElements{$tagname}) {
561 # use attribute sets from right to left
562 # to avoid invalidating the offsets
563 # when replacing the values
564 my($k_offset, $k_len, $v_offset, $v_len) =
566 my $attrname = lc(substr($text, $k_offset, $k_len));
567 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
568 next unless $v_offset; # 0 v_offset means no value
569 my $v = substr($text, $v_offset, $v_len);
570 $v =~ s/^([\'\"])(.*)\1$/$2/;
571 my $new_v=urlabs($v, $urlbase);
572 $new_v =~ s/\"/"/g; # since we quote with ""
573 substr($text, $v_offset, $v_len) = qq("$new_v");
577 }, "tagname, tokenpos, text");
584 sub pagefile ($) { #{{{
587 return "$config{srcdir}/".htmlfn($page);
590 sub htmlfn ($) { #{{{
591 return shift().".".$config{htmlext};
596 sub lockaggregate () { #{{{
597 # Take an exclusive lock to prevent multiple concurrent aggregators.
598 # Returns true if the lock was aquired.
599 if (! -d $config{wikistatedir}) {
600 mkdir($config{wikistatedir});
602 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
603 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
604 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
605 close($aggregatelock) || error("failed closing aggregatelock: $!");
611 sub unlockaggregate () { #{{{
612 return close($aggregatelock) if $aggregatelock;