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 => "getsetup", id => "aggregate", call => \&getsetup);
20 hook(type => "checkconfig", id => "aggregate", call => \&checkconfig);
21 hook(type => "needsbuild", id => "aggregate", call => \&needsbuild);
22 hook(type => "preprocess", id => "aggregate", call => \&preprocess);
23 hook(type => "delete", id => "aggregate", call => \&delete);
24 hook(type => "savestate", id => "aggregate", call => \&savestate);
25 hook(type => "htmlize", id => "_aggregated", call => \&htmlize);
26 if (exists $config{aggregate_webtrigger} && $config{aggregate_webtrigger}) {
27 hook(type => "cgi", id => "aggregate", call => \&cgi);
32 eval q{use Getopt::Long};
34 Getopt::Long::Configure('pass_through');
36 "aggregate" => \$config{aggregate},
37 "aggregateinternal!" => \$config{aggregateinternal},
47 aggregateinternal => {
50 description => "enable aggregation to internal pages?",
51 safe => 0, # enabling needs manual transition
54 aggregate_webtrigger => {
57 description => "allow aggregation to be triggered via the web?",
64 if (! defined $config{aggregateinternal}) {
65 $config{aggregateinternal}=1;
68 if ($config{aggregate} && ! ($config{post_commit} &&
69 IkiWiki::commit_hook_enabled())) {
77 if (defined $cgi->param('do') &&
78 $cgi->param("do") eq "aggregate_webtrigger") {
80 print "Content-Type: text/plain\n\n";
84 print gettext("Aggregation triggered via web.")."\n\n";
85 if (launchaggregation()) {
88 require IkiWiki::Render;
93 print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
99 sub launchaggregation () {
100 # See if any feeds need aggregation.
102 my @feeds=needsaggregate();
103 return unless @feeds;
104 if (! lockaggregate()) {
105 debug("an aggregation process is already running");
108 # force a later rebuild of source pages
109 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
112 # Fork a child process to handle the aggregation.
113 # The parent process will then handle building the
114 # result. This avoids messy code to clear state
115 # accumulated while aggregating.
116 defined(my $pid = fork) or error("Can't fork: $!");
118 IkiWiki::loadindex();
119 # Aggregation happens without the main wiki lock
120 # being held. This allows editing pages etc while
121 # aggregation is running.
125 # Merge changes, since aggregation state may have
126 # changed on disk while the aggregation was happening.
135 error "aggregation failed with code $?";
144 # Pages with extension _aggregated have plain html markup, pass through.
147 return $params{content};
150 # Used by ikiwiki-transition aggregateinternal.
151 sub migrate_to_internal {
152 if (! lockaggregate()) {
153 error("an aggregation process is currently running");
160 foreach my $data (values %guids) {
161 next unless $data->{page};
162 next if $data->{expired};
164 $config{aggregateinternal} = 0;
165 my $oldname = "$config{srcdir}/".htmlfn($data->{page});
166 my $oldoutput = $config{destdir}."/".IkiWiki::htmlpage($data->{page});
168 $config{aggregateinternal} = 1;
169 my $newname = "$config{srcdir}/".htmlfn($data->{page});
171 debug "moving $oldname -> $newname";
174 error("$newname already exists");
177 debug("already renamed to $newname?");
180 elsif (-e $oldname) {
181 rename($oldname, $newname) || error("$!");
184 debug("$oldname not found");
187 require IkiWiki::Render;
188 debug("removing output file $oldoutput");
189 IkiWiki::prune($oldoutput);
200 my $needsbuild=shift;
204 foreach my $feed (values %feeds) {
205 if (exists $pagesources{$feed->{sourcepage}} &&
206 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
207 # Mark all feeds originating on this page as
208 # not yet seen; preprocess will unmark those that
210 markunseen($feed->{sourcepage});
218 foreach my $required (qw{name url}) {
219 if (! exists $params{$required}) {
220 error sprintf(gettext("missing %s parameter"), $required)
225 my $name=$params{name};
226 if (exists $feeds{$name}) {
233 $feed->{sourcepage}=$params{page};
234 $feed->{url}=$params{url};
235 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
237 ($dir)=$dir=~/$config{wiki_file_regexp}/;
239 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
240 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
241 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
242 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
243 if (exists $params{template}) {
244 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
247 $params{template} = "aggregatepost"
249 $feed->{template}=$params{template} . ".tmpl";
250 delete $feed->{unseen};
251 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
252 $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
253 $feed->{numposts}=0 unless defined $feed->{numposts};
254 $feed->{newposts}=0 unless defined $feed->{newposts};
255 $feed->{message}=gettext("new feed") unless defined $feed->{message};
256 $feed->{error}=0 unless defined $feed->{error};
262 push @{$feed->{tags}}, $value;
266 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
267 ($feed->{error} ? "<em>" : "").$feed->{message}.
268 ($feed->{error} ? "</em>" : "").
269 " (".$feed->{numposts}." ".gettext("posts").
270 ($feed->{newposts} ? "; ".$feed->{newposts}.
271 " ".gettext("new") : "").
278 # Remove feed data for removed pages.
279 foreach my $file (@files) {
280 my $page=pagename($file);
288 foreach my $id (keys %feeds) {
289 if ($feeds{$id}->{sourcepage} eq $page) {
290 $feeds{$id}->{unseen}=1;
298 return if $state_loaded;
300 if (-e "$config{wikistatedir}/aggregate") {
301 open(IN, "$config{wikistatedir}/aggregate") ||
302 die "$config{wikistatedir}/aggregate: $!";
304 $_=IkiWiki::possibly_foolish_untaint($_);
307 foreach my $i (split(/ /, $_)) {
308 my ($field, $val)=split(/=/, $i, 2);
309 if ($field eq "name" || $field eq "feed" ||
310 $field eq "guid" || $field eq "message") {
311 $data->{$field}=decode_entities($val, " \t\n");
313 elsif ($field eq "tag") {
314 push @{$data->{tags}}, $val;
317 $data->{$field}=$val;
321 if (exists $data->{name}) {
322 $feeds{$data->{name}}=$data;
324 elsif (exists $data->{guid}) {
325 $guids{$data->{guid}}=$data;
334 return unless $state_loaded;
336 my $newfile="$config{wikistatedir}/aggregate.new";
337 my $cleanup = sub { unlink($newfile) };
338 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
339 foreach my $data (values %feeds, values %guids) {
341 foreach my $field (keys %$data) {
342 if ($field eq "name" || $field eq "feed" ||
343 $field eq "guid" || $field eq "message") {
344 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
346 elsif ($field eq "tags") {
347 push @line, "tag=$_" foreach @{$data->{tags}};
350 push @line, "$field=".$data->{$field}
351 if defined $data->{$field};
354 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
356 close OUT || error("save $newfile: $!", $cleanup);
357 rename($newfile, "$config{wikistatedir}/aggregate") ||
358 error("rename $newfile: $!", $cleanup);
361 sub garbage_collect () {
362 foreach my $name (keys %feeds) {
363 # remove any feeds that were not seen while building the pages
364 # that used to contain them
365 if ($feeds{$name}->{unseen}) {
366 delete $feeds{$name};
370 foreach my $guid (values %guids) {
371 # any guid whose feed is gone should be removed
372 if (! exists $feeds{$guid->{feed}}) {
373 unlink "$config{srcdir}/".htmlfn($guid->{page})
374 if exists $guid->{page};
375 delete $guids{$guid->{guid}};
377 # handle expired guids
378 elsif ($guid->{expired} && exists $guid->{page}) {
379 unlink "$config{srcdir}/".htmlfn($guid->{page});
380 delete $guid->{page};
387 # Load the current state in from disk, and merge into it
388 # values from the state in memory that might have changed
389 # during aggregation.
395 # All that can change in feed state during aggregation is a few
397 foreach my $name (keys %myfeeds) {
398 if (exists $feeds{$name}) {
399 foreach my $field (qw{message lastupdate lasttry
400 numposts newposts error}) {
401 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
406 # New guids can be created during aggregation.
407 # Guids have a few fields that may be updated during aggregation.
408 # It's also possible that guids were removed from the on-disk state
409 # while the aggregation was in process. That would only happen if
410 # their feed was also removed, so any removed guids added back here
411 # will be garbage collected later.
412 foreach my $guid (keys %myguids) {
413 if (! exists $guids{$guid}) {
414 $guids{$guid}=$myguids{$guid};
417 foreach my $field (qw{md5}) {
418 $guids{$guid}->{$field}=$myguids{$guid}->{$field};
431 foreach my $feed (values %feeds) {
432 next unless $feed->{expireage} || $feed->{expirecount};
435 foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
436 grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
438 if ($feed->{expireage}) {
439 my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
440 if ($days_old > $feed->{expireage}) {
441 debug(sprintf(gettext("expiring %s (%s days old)"),
442 $item->{page}, int($days_old)));
446 elsif ($feed->{expirecount} &&
447 $count >= $feed->{expirecount}) {
448 debug(sprintf(gettext("expiring %s"), $item->{page}));
452 if (! $seen{$item->{page}}) {
453 $seen{$item->{page}}=1;
461 sub needsaggregate () {
462 return values %feeds if $config{rebuild};
463 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
467 eval q{use XML::Feed};
469 eval q{use URI::Fetch};
472 foreach my $feed (@_) {
473 $feed->{lasttry}=time;
475 $feed->{message}=sprintf(gettext("last checked %s"),
476 displaytime($feed->{lasttry}));
479 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
481 if (! length $feed->{feedurl}) {
482 my @urls=XML::Feed->find_feeds($feed->{url});
484 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
486 debug($feed->{message});
489 $feed->{feedurl}=pop @urls;
491 my $res=URI::Fetch->fetch($feed->{feedurl});
493 $feed->{message}=URI::Fetch->errstr;
495 debug($feed->{message});
499 # lastupdate is only set if we were able to contact the server
500 $feed->{lastupdate}=$feed->{lasttry};
502 if ($res->status == URI::Fetch::URI_GONE()) {
503 $feed->{message}=gettext("feed not found");
505 debug($feed->{message});
508 my $content=$res->content;
509 my $f=eval{XML::Feed->parse(\$content)};
511 # One common cause of XML::Feed crashing is a feed
512 # that contains invalid UTF-8 sequences. Convert
513 # feed to ascii to try to work around.
514 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
516 $content=Encode::decode_utf8($content, 0);
517 XML::Feed->parse(\$content)
521 # Another possibility is badly escaped entities.
522 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
523 $content=~s/\&(?!amp)(\w+);/&$1;/g;
525 $content=Encode::decode_utf8($content, 0);
526 XML::Feed->parse(\$content)
530 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
532 debug($feed->{message});
536 $feed->{message}=XML::Feed->errstr;
538 debug($feed->{message});
542 foreach my $entry ($f->entries) {
543 # XML::Feed doesn't work around XML::Atom's bizarre
544 # API, so we will. Real unicode strings? Yes please.
545 # See [[bugs/Aggregated_Atom_feeds_are_double-encoded]]
546 local $XML::Atom::ForceUnicode = 1;
548 my $c=$entry->content;
549 # atom feeds may have no content, only a summary
550 if (! defined $c && ref $entry->summary) {
556 copyright => $f->copyright,
557 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
558 link => $entry->link,
559 content => (defined $c && defined $c->body) ? $c->body : "",
560 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
561 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
562 base => (defined $c && $c->can("base")) ? $c->base : undef,
571 my $feed=$params{feed};
574 if (exists $guids{$params{guid}}) {
575 # updating an existing post
576 $guid=$guids{$params{guid}};
577 return if $guid->{expired};
581 $guid->{guid}=$params{guid};
582 $guids{$params{guid}}=$guid;
583 $mtime=$params{ctime};
587 # assign it an unused page
588 my $page=titlepage($params{title});
589 # escape slashes and periods in title so it doesn't specify
590 # directory name or trigger ".." disallowing code.
591 $page=~s!([/.])!"__".ord($1)."__"!eg;
592 $page=$feed->{dir}."/".$page;
593 ($page)=$page=~/$config{wiki_file_regexp}/;
594 if (! defined $page || ! length $page) {
595 $page=$feed->{dir}."/item";
598 while (exists $IkiWiki::pagecase{lc $page.$c} ||
599 -e "$config{srcdir}/".htmlfn($page.$c)) {
603 # Make sure that the file name isn't too long.
604 # NB: This doesn't check for path length limits.
605 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
606 if (defined $max && length(htmlfn($page)) >= $max) {
608 $page=$feed->{dir}."/item";
609 while (exists $IkiWiki::pagecase{lc $page.$c} ||
610 -e "$config{srcdir}/".htmlfn($page.$c)) {
616 debug(sprintf(gettext("creating new page %s"), $page));
618 $guid->{feed}=$feed->{name};
620 # To write or not to write? Need to avoid writing unchanged pages
621 # to avoid unneccessary rebuilding. The mtime from rss cannot be
622 # trusted; let's use a digest.
623 eval q{use Digest::MD5 'md5_hex'};
626 my $digest=md5_hex(Encode::encode_utf8($params{content}));
627 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
628 $guid->{md5}=$digest;
631 my $template=template($feed->{template}, blind_cache => 1);
632 $template->param(title => $params{title})
633 if defined $params{title} && length($params{title});
634 $template->param(content => wikiescape(htmlabs($params{content},
635 defined $params{base} ? $params{base} : $feed->{feedurl})));
636 $template->param(name => $feed->{name});
637 $template->param(url => $feed->{url});
638 $template->param(copyright => $params{copyright})
639 if defined $params{copyright} && length $params{copyright};
640 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
641 if defined $params{link};
642 if (ref $feed->{tags}) {
643 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
645 writefile(htmlfn($guid->{page}), $config{srcdir},
648 if (defined $mtime && $mtime <= time) {
649 # Set the mtime, this lets the build process get the right
650 # creation time on record for the new page.
651 utime $mtime, $mtime, "$config{srcdir}/".htmlfn($guid->{page});
652 # Store it in pagectime for expiry code to use also.
653 $IkiWiki::pagectime{$guid->{page}}=$mtime
654 unless exists $IkiWiki::pagectime{$guid->{page}};
657 # Dummy value for expiry code.
658 $IkiWiki::pagectime{$guid->{page}}=time
659 unless exists $IkiWiki::pagectime{$guid->{page}};
664 # escape accidental wikilinks and preprocessor stuff
665 return encode_entities(shift, '\[\]');
672 URI->new_abs($url, $urlbase)->as_string;
676 # Convert links in html from relative to absolute.
677 # Note that this is a heuristic, which is not specified by the rss
678 # spec and may not be right for all feeds. Also, see Debian
684 my $p = HTML::Parser->new(api_version => 3);
685 $p->handler(default => sub { $ret.=join("", @_) }, "text");
686 $p->handler(start => sub {
687 my ($tagname, $pos, $text) = @_;
688 if (ref $HTML::Tagset::linkElements{$tagname}) {
690 # use attribute sets from right to left
691 # to avoid invalidating the offsets
692 # when replacing the values
693 my($k_offset, $k_len, $v_offset, $v_len) =
695 my $attrname = lc(substr($text, $k_offset, $k_len));
696 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
697 next unless $v_offset; # 0 v_offset means no value
698 my $v = substr($text, $v_offset, $v_len);
699 $v =~ s/^([\'\"])(.*)\1$/$2/;
700 my $new_v=urlabs($v, $urlbase);
701 $new_v =~ s/\"/"/g; # since we quote with ""
702 substr($text, $v_offset, $v_len) = qq("$new_v");
706 }, "tagname, tokenpos, text");
714 return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
719 sub lockaggregate () {
720 # Take an exclusive lock to prevent multiple concurrent aggregators.
721 # Returns true if the lock was aquired.
722 if (! -d $config{wikistatedir}) {
723 mkdir($config{wikistatedir});
725 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
726 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
727 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
728 close($aggregatelock) || error("failed closing aggregatelock: $!");
734 sub unlockaggregate () {
735 return close($aggregatelock) if $aggregatelock;