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?",
63 if (! defined $config{aggregateinternal}) {
64 $config{aggregateinternal}=1;
67 if ($config{aggregate} && ! ($config{post_commit} &&
68 IkiWiki::commit_hook_enabled())) {
76 if (defined $cgi->param('do') &&
77 $cgi->param("do") eq "aggregate_webtrigger") {
79 print "Content-Type: text/plain\n\n";
83 print gettext("Aggregation triggered via web.")."\n\n";
84 if (launchaggregation()) {
87 require IkiWiki::Render;
92 print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
98 sub launchaggregation () {
99 # See if any feeds need aggregation.
101 my @feeds=needsaggregate();
102 return unless @feeds;
103 if (! lockaggregate()) {
104 debug("an aggregation process is already running");
107 # force a later rebuild of source pages
108 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
111 # Fork a child process to handle the aggregation.
112 # The parent process will then handle building the
113 # result. This avoids messy code to clear state
114 # accumulated while aggregating.
115 defined(my $pid = fork) or error("Can't fork: $!");
117 IkiWiki::loadindex();
118 # Aggregation happens without the main wiki lock
119 # being held. This allows editing pages etc while
120 # aggregation is running.
124 # Merge changes, since aggregation state may have
125 # changed on disk while the aggregation was happening.
134 error "aggregation failed with code $?";
143 # Pages with extension _aggregated have plain html markup, pass through.
146 return $params{content};
149 # Used by ikiwiki-transition aggregateinternal.
150 sub migrate_to_internal {
151 if (! lockaggregate()) {
152 error("an aggregation process is currently running");
159 foreach my $data (values %guids) {
160 next unless $data->{page};
161 next if $data->{expired};
163 $config{aggregateinternal} = 0;
164 my $oldname = "$config{srcdir}/".htmlfn($data->{page});
165 my $oldoutput = $config{destdir}."/".IkiWiki::htmlpage($data->{page});
167 $config{aggregateinternal} = 1;
168 my $newname = "$config{srcdir}/".htmlfn($data->{page});
170 debug "moving $oldname -> $newname";
173 error("$newname already exists");
176 debug("already renamed to $newname?");
179 elsif (-e $oldname) {
180 rename($oldname, $newname) || error("$!");
183 debug("$oldname not found");
186 require IkiWiki::Render;
187 debug("removing output file $oldoutput");
188 IkiWiki::prune($oldoutput);
199 my $needsbuild=shift;
203 foreach my $feed (values %feeds) {
204 if (exists $pagesources{$feed->{sourcepage}} &&
205 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
206 # Mark all feeds originating on this page as
207 # not yet seen; preprocess will unmark those that
209 markunseen($feed->{sourcepage});
219 foreach my $required (qw{name url}) {
220 if (! exists $params{$required}) {
221 error sprintf(gettext("missing %s parameter"), $required)
226 my $name=$params{name};
227 if (exists $feeds{$name}) {
234 $feed->{sourcepage}=$params{page};
235 $feed->{url}=$params{url};
236 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
238 ($dir)=$dir=~/$config{wiki_file_regexp}/;
240 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
241 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
242 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
243 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
244 if (exists $params{template}) {
245 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
248 $params{template} = "aggregatepost"
250 $feed->{template}=$params{template} . ".tmpl";
251 delete $feed->{unseen};
252 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
253 $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
254 $feed->{numposts}=0 unless defined $feed->{numposts};
255 $feed->{newposts}=0 unless defined $feed->{newposts};
256 $feed->{message}=gettext("new feed") unless defined $feed->{message};
257 $feed->{error}=0 unless defined $feed->{error};
263 push @{$feed->{tags}}, $value;
267 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
268 ($feed->{error} ? "<em>" : "").$feed->{message}.
269 ($feed->{error} ? "</em>" : "").
270 " (".$feed->{numposts}." ".gettext("posts").
271 ($feed->{newposts} ? "; ".$feed->{newposts}.
272 " ".gettext("new") : "").
279 # Remove feed data for removed pages.
280 foreach my $file (@files) {
281 my $page=pagename($file);
289 foreach my $id (keys %feeds) {
290 if ($feeds{$id}->{sourcepage} eq $page) {
291 $feeds{$id}->{unseen}=1;
299 return if $state_loaded;
301 if (-e "$config{wikistatedir}/aggregate") {
302 open(IN, "<", "$config{wikistatedir}/aggregate") ||
303 die "$config{wikistatedir}/aggregate: $!";
305 $_=IkiWiki::possibly_foolish_untaint($_);
308 foreach my $i (split(/ /, $_)) {
309 my ($field, $val)=split(/=/, $i, 2);
310 if ($field eq "name" || $field eq "feed" ||
311 $field eq "guid" || $field eq "message") {
312 $data->{$field}=decode_entities($val, " \t\n");
314 elsif ($field eq "tag") {
315 push @{$data->{tags}}, $val;
318 $data->{$field}=$val;
322 if (exists $data->{name}) {
323 $feeds{$data->{name}}=$data;
325 elsif (exists $data->{guid}) {
326 $guids{$data->{guid}}=$data;
335 return unless $state_loaded;
337 my $newfile="$config{wikistatedir}/aggregate.new";
338 my $cleanup = sub { unlink($newfile) };
339 open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
340 foreach my $data (values %feeds, values %guids) {
342 foreach my $field (keys %$data) {
343 if ($field eq "name" || $field eq "feed" ||
344 $field eq "guid" || $field eq "message") {
345 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
347 elsif ($field eq "tags") {
348 push @line, "tag=$_" foreach @{$data->{tags}};
351 push @line, "$field=".$data->{$field}
352 if defined $data->{$field};
355 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
357 close OUT || error("save $newfile: $!", $cleanup);
358 rename($newfile, "$config{wikistatedir}/aggregate") ||
359 error("rename $newfile: $!", $cleanup);
362 foreach my $feed (keys %feeds) {
363 my $t=$feeds{$feed}->{lastupdate}+$feeds{$feed}->{updateinterval};
364 if (! defined $timestamp || $timestamp > $t) {
368 $newfile=~s/\.new$/time/;
369 open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
370 if (defined $timestamp) {
371 print OUT $timestamp."\n";
373 close OUT || error("save $newfile: $!", $cleanup);
376 sub garbage_collect () {
377 foreach my $name (keys %feeds) {
378 # remove any feeds that were not seen while building the pages
379 # that used to contain them
380 if ($feeds{$name}->{unseen}) {
381 delete $feeds{$name};
385 foreach my $guid (values %guids) {
386 # any guid whose feed is gone should be removed
387 if (! exists $feeds{$guid->{feed}}) {
388 unlink "$config{srcdir}/".htmlfn($guid->{page})
389 if exists $guid->{page};
390 delete $guids{$guid->{guid}};
392 # handle expired guids
393 elsif ($guid->{expired} && exists $guid->{page}) {
394 unlink "$config{srcdir}/".htmlfn($guid->{page});
395 delete $guid->{page};
402 # Load the current state in from disk, and merge into it
403 # values from the state in memory that might have changed
404 # during aggregation.
410 # All that can change in feed state during aggregation is a few
412 foreach my $name (keys %myfeeds) {
413 if (exists $feeds{$name}) {
414 foreach my $field (qw{message lastupdate lasttry
415 numposts newposts error}) {
416 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
421 # New guids can be created during aggregation.
422 # Guids have a few fields that may be updated during aggregation.
423 # It's also possible that guids were removed from the on-disk state
424 # while the aggregation was in process. That would only happen if
425 # their feed was also removed, so any removed guids added back here
426 # will be garbage collected later.
427 foreach my $guid (keys %myguids) {
428 if (! exists $guids{$guid}) {
429 $guids{$guid}=$myguids{$guid};
432 foreach my $field (qw{md5}) {
433 $guids{$guid}->{$field}=$myguids{$guid}->{$field};
446 foreach my $feed (values %feeds) {
447 next unless $feed->{expireage} || $feed->{expirecount};
450 foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
451 grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
453 if ($feed->{expireage}) {
454 my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
455 if ($days_old > $feed->{expireage}) {
456 debug(sprintf(gettext("expiring %s (%s days old)"),
457 $item->{page}, int($days_old)));
461 elsif ($feed->{expirecount} &&
462 $count >= $feed->{expirecount}) {
463 debug(sprintf(gettext("expiring %s"), $item->{page}));
467 if (! $seen{$item->{page}}) {
468 $seen{$item->{page}}=1;
476 sub needsaggregate () {
477 return values %feeds if $config{rebuild};
478 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
482 eval q{use XML::Feed};
484 eval q{use URI::Fetch};
487 foreach my $feed (@_) {
488 $feed->{lasttry}=time;
490 $feed->{message}=sprintf(gettext("last checked %s"),
491 displaytime($feed->{lasttry}));
494 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
496 if (! length $feed->{feedurl}) {
497 my @urls=XML::Feed->find_feeds($feed->{url});
499 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
501 debug($feed->{message});
504 $feed->{feedurl}=pop @urls;
506 my $res=URI::Fetch->fetch($feed->{feedurl});
508 $feed->{message}=URI::Fetch->errstr;
510 debug($feed->{message});
514 # lastupdate is only set if we were able to contact the server
515 $feed->{lastupdate}=$feed->{lasttry};
517 if ($res->status == URI::Fetch::URI_GONE()) {
518 $feed->{message}=gettext("feed not found");
520 debug($feed->{message});
523 my $content=$res->content;
524 my $f=eval{XML::Feed->parse(\$content)};
526 # One common cause of XML::Feed crashing is a feed
527 # that contains invalid UTF-8 sequences. Convert
528 # feed to ascii to try to work around.
529 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
531 $content=Encode::decode_utf8($content, 0);
532 XML::Feed->parse(\$content)
536 # Another possibility is badly escaped entities.
537 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
538 $content=~s/\&(?!amp)(\w+);/&$1;/g;
540 $content=Encode::decode_utf8($content, 0);
541 XML::Feed->parse(\$content)
545 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
547 debug($feed->{message});
551 $feed->{message}=XML::Feed->errstr;
553 debug($feed->{message});
557 foreach my $entry ($f->entries) {
558 # XML::Feed doesn't work around XML::Atom's bizarre
559 # API, so we will. Real unicode strings? Yes please.
560 # See [[bugs/Aggregated_Atom_feeds_are_double-encoded]]
561 local $XML::Atom::ForceUnicode = 1;
563 my $c=$entry->content;
564 # atom feeds may have no content, only a summary
565 if (! defined $c && ref $entry->summary) {
571 copyright => $f->copyright,
572 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
573 link => $entry->link,
574 content => (defined $c && defined $c->body) ? $c->body : "",
575 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
576 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
577 base => (defined $c && $c->can("base")) ? $c->base : undef,
586 my $feed=$params{feed};
589 if (exists $guids{$params{guid}}) {
590 # updating an existing post
591 $guid=$guids{$params{guid}};
592 return if $guid->{expired};
596 $guid->{guid}=$params{guid};
597 $guids{$params{guid}}=$guid;
598 $mtime=$params{ctime};
602 # assign it an unused page
603 my $page=titlepage($params{title});
604 # escape slashes and periods in title so it doesn't specify
605 # directory name or trigger ".." disallowing code.
606 $page=~s!([/.])!"__".ord($1)."__"!eg;
607 $page=$feed->{dir}."/".$page;
608 ($page)=$page=~/$config{wiki_file_regexp}/;
609 if (! defined $page || ! length $page) {
610 $page=$feed->{dir}."/item";
613 while (exists $IkiWiki::pagecase{lc $page.$c} ||
614 -e "$config{srcdir}/".htmlfn($page.$c)) {
618 # Make sure that the file name isn't too long.
619 # NB: This doesn't check for path length limits.
620 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
621 if (defined $max && length(htmlfn($page)) >= $max) {
623 $page=$feed->{dir}."/item";
624 while (exists $IkiWiki::pagecase{lc $page.$c} ||
625 -e "$config{srcdir}/".htmlfn($page.$c)) {
631 debug(sprintf(gettext("creating new page %s"), $page));
633 $guid->{feed}=$feed->{name};
635 # To write or not to write? Need to avoid writing unchanged pages
636 # to avoid unneccessary rebuilding. The mtime from rss cannot be
637 # trusted; let's use a digest.
638 eval q{use Digest::MD5 'md5_hex'};
641 my $digest=md5_hex(Encode::encode_utf8($params{content}));
642 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
643 $guid->{md5}=$digest;
648 $template=template($feed->{template}, blind_cache => 1);
651 print STDERR gettext("failed to process template:")." $@";
654 $template->param(title => $params{title})
655 if defined $params{title} && length($params{title});
656 $template->param(content => wikiescape(htmlabs($params{content},
657 defined $params{base} ? $params{base} : $feed->{feedurl})));
658 $template->param(name => $feed->{name});
659 $template->param(url => $feed->{url});
660 $template->param(copyright => $params{copyright})
661 if defined $params{copyright} && length $params{copyright};
662 $template->param(permalink => IkiWiki::urlabs($params{link}, $feed->{feedurl}))
663 if defined $params{link};
664 if (ref $feed->{tags}) {
665 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
667 writefile(htmlfn($guid->{page}), $config{srcdir},
670 if (defined $mtime && $mtime <= time) {
671 # Set the mtime, this lets the build process get the right
672 # creation time on record for the new page.
673 utime $mtime, $mtime, "$config{srcdir}/".htmlfn($guid->{page});
674 # Store it in pagectime for expiry code to use also.
675 $IkiWiki::pagectime{$guid->{page}}=$mtime
676 unless exists $IkiWiki::pagectime{$guid->{page}};
679 # Dummy value for expiry code.
680 $IkiWiki::pagectime{$guid->{page}}=time
681 unless exists $IkiWiki::pagectime{$guid->{page}};
686 # escape accidental wikilinks and preprocessor stuff
687 return encode_entities(shift, '\[\]');
691 # Convert links in html from relative to absolute.
692 # Note that this is a heuristic, which is not specified by the rss
693 # spec and may not be right for all feeds. Also, see Debian
699 my $p = HTML::Parser->new(api_version => 3);
700 $p->handler(default => sub { $ret.=join("", @_) }, "text");
701 $p->handler(start => sub {
702 my ($tagname, $pos, $text) = @_;
703 if (ref $HTML::Tagset::linkElements{$tagname}) {
705 # use attribute sets from right to left
706 # to avoid invalidating the offsets
707 # when replacing the values
708 my($k_offset, $k_len, $v_offset, $v_len) =
710 my $attrname = lc(substr($text, $k_offset, $k_len));
711 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
712 next unless $v_offset; # 0 v_offset means no value
713 my $v = substr($text, $v_offset, $v_len);
714 $v =~ s/^([\'\"])(.*)\1$/$2/;
715 my $new_v=IkiWiki::urlabs($v, $urlbase);
716 $new_v =~ s/\"/"/g; # since we quote with ""
717 substr($text, $v_offset, $v_len) = qq("$new_v");
721 }, "tagname, tokenpos, text");
729 return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
734 sub lockaggregate () {
735 # Take an exclusive lock to prevent multiple concurrent aggregators.
736 # Returns true if the lock was aquired.
737 if (! -d $config{wikistatedir}) {
738 mkdir($config{wikistatedir});
740 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
741 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
742 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
743 close($aggregatelock) || error("failed closing aggregatelock: $!");
749 sub unlockaggregate () {
750 return close($aggregatelock) if $aggregatelock;