2 # Feed aggregation plugin.
3 package IkiWiki::Plugin::aggregate;
11 use open qw{:utf8 :std};
17 hook(type => "getopt", id => "aggregate", call => \&getopt);
18 hook(type => "getsetup", id => "aggregate", call => \&getsetup);
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 hook(type => "htmlize", id => "_aggregated", call => \&htmlize);
25 if (exists $config{aggregate_webtrigger} && $config{aggregate_webtrigger}) {
26 hook(type => "cgi", id => "aggregate", call => \&cgi);
31 eval q{use Getopt::Long};
33 Getopt::Long::Configure('pass_through');
35 "aggregate" => \$config{aggregate},
36 "aggregateinternal!" => \$config{aggregateinternal},
46 aggregateinternal => {
49 description => "enable aggregation to internal pages?",
50 safe => 0, # enabling needs manual transition
53 aggregate_webtrigger => {
56 description => "allow aggregation to be triggered via the web?",
62 example => { file => "$ENV{HOME}/.ikiwiki/cookies" },
63 safe => 0, # hooks into perl module internals
64 description => "cookie control",
69 if (! defined $config{aggregateinternal}) {
70 $config{aggregateinternal}=1;
72 if (! defined $config{cookies}) {
73 $config{cookies}={ file => "$ENV{HOME}/.ikiwiki/cookies" };
76 if ($config{aggregate} && ! ($config{post_commit} &&
77 IkiWiki::commit_hook_enabled())) {
85 if (defined $cgi->param('do') &&
86 $cgi->param("do") eq "aggregate_webtrigger") {
88 print "Content-Type: text/plain\n\n";
92 print gettext("Aggregation triggered via web.")."\n\n";
93 if (launchaggregation()) {
96 require IkiWiki::Render;
101 print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
107 sub launchaggregation () {
108 # See if any feeds need aggregation.
110 my @feeds=needsaggregate();
111 return unless @feeds;
112 if (! lockaggregate()) {
113 debug("an aggregation process is already running");
116 # force a later rebuild of source pages
117 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
120 # Fork a child process to handle the aggregation.
121 # The parent process will then handle building the
122 # result. This avoids messy code to clear state
123 # accumulated while aggregating.
124 defined(my $pid = fork) or error("Can't fork: $!");
126 IkiWiki::loadindex();
127 # Aggregation happens without the main wiki lock
128 # being held. This allows editing pages etc while
129 # aggregation is running.
133 # Merge changes, since aggregation state may have
134 # changed on disk while the aggregation was happening.
143 error "aggregation failed with code $?";
152 # Pages with extension _aggregated have plain html markup, pass through.
155 return $params{content};
158 # Used by ikiwiki-transition aggregateinternal.
159 sub migrate_to_internal {
160 if (! lockaggregate()) {
161 error("an aggregation process is currently running");
168 foreach my $data (values %guids) {
169 next unless $data->{page};
170 next if $data->{expired};
172 $config{aggregateinternal} = 0;
173 my $oldname = "$config{srcdir}/".htmlfn($data->{page});
175 $oldname = $IkiWiki::Plugin::transient::transientdir."/".htmlfn($data->{page});
178 my $oldoutput = $config{destdir}."/".IkiWiki::htmlpage($data->{page});
180 $config{aggregateinternal} = 1;
181 my $newname = $IkiWiki::Plugin::transient::transientdir."/".htmlfn($data->{page});
183 debug "moving $oldname -> $newname";
186 error("$newname already exists");
189 debug("already renamed to $newname?");
192 elsif (-e $oldname) {
193 rename($oldname, $newname) || error("$!");
196 debug("$oldname not found");
199 require IkiWiki::Render;
200 debug("removing output file $oldoutput");
201 IkiWiki::prune($oldoutput);
212 my $needsbuild=shift;
216 foreach my $feed (values %feeds) {
217 if (exists $pagesources{$feed->{sourcepage}} &&
218 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
219 # Mark all feeds originating on this page as
220 # not yet seen; preprocess will unmark those that
222 markunseen($feed->{sourcepage});
232 foreach my $required (qw{name url}) {
233 if (! exists $params{$required}) {
234 error sprintf(gettext("missing %s parameter"), $required)
239 my $name=$params{name};
240 if (exists $feeds{$name}) {
247 $feed->{sourcepage}=$params{page};
248 $feed->{url}=$params{url};
249 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
251 ($dir)=$dir=~/$config{wiki_file_regexp}/;
253 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
254 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
255 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
256 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
257 if (exists $params{template}) {
258 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
261 $params{template} = "aggregatepost"
263 $feed->{template}=$params{template} . ".tmpl";
264 delete $feed->{unseen};
265 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
266 $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
267 $feed->{numposts}=0 unless defined $feed->{numposts};
268 $feed->{newposts}=0 unless defined $feed->{newposts};
269 $feed->{message}=gettext("new feed") unless defined $feed->{message};
270 $feed->{error}=0 unless defined $feed->{error};
276 push @{$feed->{tags}}, $value;
280 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
281 ($feed->{error} ? "<em>" : "").$feed->{message}.
282 ($feed->{error} ? "</em>" : "").
283 " (".$feed->{numposts}." ".gettext("posts").
284 ($feed->{newposts} ? "; ".$feed->{newposts}.
285 " ".gettext("new") : "").
292 # Remove feed data for removed pages.
293 foreach my $file (@files) {
294 my $page=pagename($file);
302 foreach my $id (keys %feeds) {
303 if ($feeds{$id}->{sourcepage} eq $page) {
304 $feeds{$id}->{unseen}=1;
312 return if $state_loaded;
314 if (-e "$config{wikistatedir}/aggregate") {
315 open(IN, "<", "$config{wikistatedir}/aggregate") ||
316 die "$config{wikistatedir}/aggregate: $!";
318 $_=IkiWiki::possibly_foolish_untaint($_);
321 foreach my $i (split(/ /, $_)) {
322 my ($field, $val)=split(/=/, $i, 2);
323 if ($field eq "name" || $field eq "feed" ||
324 $field eq "guid" || $field eq "message") {
325 $data->{$field}=decode_entities($val, " \t\n");
327 elsif ($field eq "tag") {
328 push @{$data->{tags}}, $val;
331 $data->{$field}=$val;
335 if (exists $data->{name}) {
336 $feeds{$data->{name}}=$data;
338 elsif (exists $data->{guid}) {
339 $guids{$data->{guid}}=$data;
348 return unless $state_loaded;
350 my $newfile="$config{wikistatedir}/aggregate.new";
351 my $cleanup = sub { unlink($newfile) };
352 open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
353 foreach my $data (values %feeds, values %guids) {
355 foreach my $field (keys %$data) {
356 if ($field eq "name" || $field eq "feed" ||
357 $field eq "guid" || $field eq "message") {
358 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
360 elsif ($field eq "tags") {
361 push @line, "tag=$_" foreach @{$data->{tags}};
364 push @line, "$field=".$data->{$field}
365 if defined $data->{$field};
368 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
370 close OUT || error("save $newfile: $!", $cleanup);
371 rename($newfile, "$config{wikistatedir}/aggregate") ||
372 error("rename $newfile: $!", $cleanup);
375 foreach my $feed (keys %feeds) {
376 my $t=$feeds{$feed}->{lastupdate}+$feeds{$feed}->{updateinterval};
377 if (! defined $timestamp || $timestamp > $t) {
381 $newfile=~s/\.new$/time/;
382 open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
383 if (defined $timestamp) {
384 print OUT $timestamp."\n";
386 close OUT || error("save $newfile: $!", $cleanup);
389 sub garbage_collect () {
390 foreach my $name (keys %feeds) {
391 # remove any feeds that were not seen while building the pages
392 # that used to contain them
393 if ($feeds{$name}->{unseen}) {
394 delete $feeds{$name};
398 foreach my $guid (values %guids) {
399 # any guid whose feed is gone should be removed
400 if (! exists $feeds{$guid->{feed}}) {
401 if (exists $guid->{page}) {
402 unlink $IkiWiki::Plugin::transient::transientdir."/".htmlfn($guid->{page})
403 || unlink "$config{srcdir}/".htmlfn($guid->{page});
405 delete $guids{$guid->{guid}};
407 # handle expired guids
408 elsif ($guid->{expired} && exists $guid->{page}) {
409 unlink "$config{srcdir}/".htmlfn($guid->{page});
410 unlink $IkiWiki::Plugin::transient::transientdir."/".htmlfn($guid->{page});
411 delete $guid->{page};
418 # Load the current state in from disk, and merge into it
419 # values from the state in memory that might have changed
420 # during aggregation.
426 # All that can change in feed state during aggregation is a few
428 foreach my $name (keys %myfeeds) {
429 if (exists $feeds{$name}) {
430 foreach my $field (qw{message lastupdate lasttry
431 numposts newposts error}) {
432 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
437 # New guids can be created during aggregation.
438 # Guids have a few fields that may be updated during aggregation.
439 # It's also possible that guids were removed from the on-disk state
440 # while the aggregation was in process. That would only happen if
441 # their feed was also removed, so any removed guids added back here
442 # will be garbage collected later.
443 foreach my $guid (keys %myguids) {
444 if (! exists $guids{$guid}) {
445 $guids{$guid}=$myguids{$guid};
448 foreach my $field (qw{md5}) {
449 $guids{$guid}->{$field}=$myguids{$guid}->{$field};
462 foreach my $feed (values %feeds) {
463 next unless $feed->{expireage} || $feed->{expirecount};
466 foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
467 grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
469 if ($feed->{expireage}) {
470 my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
471 if ($days_old > $feed->{expireage}) {
472 debug(sprintf(gettext("expiring %s (%s days old)"),
473 $item->{page}, int($days_old)));
477 elsif ($feed->{expirecount} &&
478 $count >= $feed->{expirecount}) {
479 debug(sprintf(gettext("expiring %s"), $item->{page}));
483 if (! $seen{$item->{page}}) {
484 $seen{$item->{page}}=1;
492 sub needsaggregate () {
493 return values %feeds if $config{rebuild};
494 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
498 eval q{use XML::Feed};
500 eval q{use URI::Fetch};
503 foreach my $feed (@_) {
504 $feed->{lasttry}=time;
506 $feed->{message}=sprintf(gettext("last checked %s"),
507 displaytime($feed->{lasttry}));
510 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
512 if (! length $feed->{feedurl}) {
513 my @urls=XML::Feed->find_feeds($feed->{url});
515 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
517 debug($feed->{message});
520 $feed->{feedurl}=pop @urls;
522 my $res=URI::Fetch->fetch($feed->{feedurl},
523 UserAgent => LWP::UserAgent->new(
524 cookie_jar => $config{cookiejar},
528 $feed->{message}=URI::Fetch->errstr;
530 debug($feed->{message});
534 # lastupdate is only set if we were able to contact the server
535 $feed->{lastupdate}=$feed->{lasttry};
537 if ($res->status == URI::Fetch::URI_GONE()) {
538 $feed->{message}=gettext("feed not found");
540 debug($feed->{message});
543 my $content=$res->content;
544 my $f=eval{XML::Feed->parse(\$content)};
546 # One common cause of XML::Feed crashing is a feed
547 # that contains invalid UTF-8 sequences. Convert
548 # feed to ascii to try to work around.
549 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
551 $content=Encode::decode_utf8($content, 0);
552 XML::Feed->parse(\$content)
556 # Another possibility is badly escaped entities.
557 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
558 $content=~s/\&(?!amp)(\w+);/&$1;/g;
560 $content=Encode::decode_utf8($content, 0);
561 XML::Feed->parse(\$content)
565 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
567 debug($feed->{message});
571 $feed->{message}=XML::Feed->errstr;
573 debug($feed->{message});
577 foreach my $entry ($f->entries) {
578 # XML::Feed doesn't work around XML::Atom's bizarre
579 # API, so we will. Real unicode strings? Yes please.
580 # See [[bugs/Aggregated_Atom_feeds_are_double-encoded]]
581 local $XML::Atom::ForceUnicode = 1;
583 my $c=$entry->content;
584 # atom feeds may have no content, only a summary
585 if (! defined $c && ref $entry->summary) {
591 copyright => $f->copyright,
592 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
593 link => $entry->link,
594 content => (defined $c && defined $c->body) ? $c->body : "",
595 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
596 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
597 base => (defined $c && $c->can("base")) ? $c->base : undef,
606 my $feed=$params{feed};
609 if (exists $guids{$params{guid}}) {
610 # updating an existing post
611 $guid=$guids{$params{guid}};
612 return if $guid->{expired};
616 $guid->{guid}=$params{guid};
617 $guids{$params{guid}}=$guid;
618 $mtime=$params{ctime};
622 # assign it an unused page
623 my $page=titlepage($params{title});
624 # escape slashes and periods in title so it doesn't specify
625 # directory name or trigger ".." disallowing code.
626 $page=~s!([/.])!"__".ord($1)."__"!eg;
627 $page=$feed->{dir}."/".$page;
628 ($page)=$page=~/$config{wiki_file_regexp}/;
629 if (! defined $page || ! length $page) {
630 $page=$feed->{dir}."/item";
633 while (exists $IkiWiki::pagecase{lc $page.$c} ||
634 -e $IkiWiki::Plugin::transient::transientdir."/".htmlfn($page.$c) ||
635 -e "$config{srcdir}/".htmlfn($page.$c)) {
639 # Make sure that the file name isn't too long.
640 # NB: This doesn't check for path length limits.
641 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
642 if (defined $max && length(htmlfn($page)) >= $max) {
644 $page=$feed->{dir}."/item";
645 while (exists $IkiWiki::pagecase{lc $page.$c} ||
646 -e $IkiWiki::Plugin::transient::transientdir."/".htmlfn($page.$c) ||
648 -e "$config{srcdir}/".htmlfn($page.$c)) {
654 debug(sprintf(gettext("creating new page %s"), $page));
656 $guid->{feed}=$feed->{name};
658 # To write or not to write? Need to avoid writing unchanged pages
659 # to avoid unneccessary rebuilding. The mtime from rss cannot be
660 # trusted; let's use a digest.
661 eval q{use Digest::MD5 'md5_hex'};
664 my $digest=md5_hex(Encode::encode_utf8($params{content}));
665 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
666 $guid->{md5}=$digest;
671 $template=template($feed->{template}, blind_cache => 1);
674 print STDERR gettext("failed to process template:")." $@";
677 $template->param(title => $params{title})
678 if defined $params{title} && length($params{title});
679 $template->param(content => wikiescape(htmlabs($params{content},
680 defined $params{base} ? $params{base} : $feed->{feedurl})));
681 $template->param(name => $feed->{name});
682 $template->param(url => $feed->{url});
683 $template->param(copyright => $params{copyright})
684 if defined $params{copyright} && length $params{copyright};
685 $template->param(permalink => IkiWiki::urlabs($params{link}, $feed->{feedurl}))
686 if defined $params{link};
687 if (ref $feed->{tags}) {
688 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
690 writefile(htmlfn($guid->{page}),
691 $IkiWiki::Plugin::transient::transientdir, $template->output);
693 if (defined $mtime && $mtime <= time) {
694 # Set the mtime, this lets the build process get the right
695 # creation time on record for the new page.
696 utime $mtime, $mtime,
697 $IkiWiki::Plugin::transient::transientdir."/".htmlfn($guid->{page});
698 # Store it in pagectime for expiry code to use also.
699 $IkiWiki::pagectime{$guid->{page}}=$mtime
700 unless exists $IkiWiki::pagectime{$guid->{page}};
703 # Dummy value for expiry code.
704 $IkiWiki::pagectime{$guid->{page}}=time
705 unless exists $IkiWiki::pagectime{$guid->{page}};
710 # escape accidental wikilinks and preprocessor stuff
711 return encode_entities(shift, '\[\]');
715 # Convert links in html from relative to absolute.
716 # Note that this is a heuristic, which is not specified by the rss
717 # spec and may not be right for all feeds. Also, see Debian
723 my $p = HTML::Parser->new(api_version => 3);
724 $p->handler(default => sub { $ret.=join("", @_) }, "text");
725 $p->handler(start => sub {
726 my ($tagname, $pos, $text) = @_;
727 if (ref $HTML::Tagset::linkElements{$tagname}) {
729 # use attribute sets from right to left
730 # to avoid invalidating the offsets
731 # when replacing the values
732 my($k_offset, $k_len, $v_offset, $v_len) =
734 my $attrname = lc(substr($text, $k_offset, $k_len));
735 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
736 next unless $v_offset; # 0 v_offset means no value
737 my $v = substr($text, $v_offset, $v_len);
738 $v =~ s/^([\'\"])(.*)\1$/$2/;
739 my $new_v=IkiWiki::urlabs($v, $urlbase);
740 $new_v =~ s/\"/"/g; # since we quote with ""
741 substr($text, $v_offset, $v_len) = qq("$new_v");
745 }, "tagname, tokenpos, text");
753 return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
758 sub lockaggregate () {
759 # Take an exclusive lock to prevent multiple concurrent aggregators.
760 # Returns true if the lock was aquired.
761 if (! -d $config{wikistatedir}) {
762 mkdir($config{wikistatedir});
764 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
765 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
766 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
767 close($aggregatelock) || error("failed closing aggregatelock: $!");
773 sub unlockaggregate () {
774 return close($aggregatelock) if $aggregatelock;