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 ($config{aggregate} && ! ($config{post_commit} &&
65 IkiWiki::commit_hook_enabled())) {
73 if (defined $cgi->param('do') &&
74 $cgi->param("do") eq "aggregate_webtrigger") {
76 print "Content-Type: text/plain\n\n";
80 print gettext("Aggregation triggered via web.")."\n\n";
81 if (launchaggregation()) {
84 require IkiWiki::Render;
89 print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
95 sub launchaggregation () {
96 # See if any feeds need aggregation.
98 my @feeds=needsaggregate();
100 if (! lockaggregate()) {
101 debug("an aggregation process is already running");
104 # force a later rebuild of source pages
105 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
108 # Fork a child process to handle the aggregation.
109 # The parent process will then handle building the
110 # result. This avoids messy code to clear state
111 # accumulated while aggregating.
112 defined(my $pid = fork) or error("Can't fork: $!");
114 IkiWiki::loadindex();
115 # Aggregation happens without the main wiki lock
116 # being held. This allows editing pages etc while
117 # aggregation is running.
121 # Merge changes, since aggregation state may have
122 # changed on disk while the aggregation was happening.
131 error "aggregation failed with code $?";
140 # Pages with extension _aggregated have plain html markup, pass through.
143 return $params{content};
146 # Used by ikiwiki-transition aggregateinternal.
147 sub migrate_to_internal {
148 if (! lockaggregate()) {
149 error("an aggregation process is currently running");
156 foreach my $data (values %guids) {
157 next unless $data->{page};
158 next if $data->{expired};
160 $config{aggregateinternal} = 0;
161 my $oldname = "$config{srcdir}/".htmlfn($data->{page});
162 my $oldoutput = $config{destdir}."/".IkiWiki::htmlpage($data->{page});
164 $config{aggregateinternal} = 1;
165 my $newname = "$config{srcdir}/".htmlfn($data->{page});
167 debug "moving $oldname -> $newname";
170 error("$newname already exists");
173 debug("already renamed to $newname?");
176 elsif (-e $oldname) {
177 rename($oldname, $newname) || error("$!");
180 debug("$oldname not found");
183 require IkiWiki::Render;
184 debug("removing output file $oldoutput");
185 IkiWiki::prune($oldoutput);
196 my $needsbuild=shift;
200 foreach my $feed (values %feeds) {
201 if (exists $pagesources{$feed->{sourcepage}} &&
202 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
203 # Mark all feeds originating on this page as
204 # not yet seen; preprocess will unmark those that
206 markunseen($feed->{sourcepage});
214 foreach my $required (qw{name url}) {
215 if (! exists $params{$required}) {
216 error sprintf(gettext("missing %s parameter"), $required)
221 my $name=$params{name};
222 if (exists $feeds{$name}) {
229 $feed->{sourcepage}=$params{page};
230 $feed->{url}=$params{url};
231 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
233 ($dir)=$dir=~/$config{wiki_file_regexp}/;
235 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
236 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
237 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
238 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
239 if (exists $params{template}) {
240 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
243 $params{template} = "aggregatepost"
245 $feed->{template}=$params{template} . ".tmpl";
246 delete $feed->{unseen};
247 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
248 $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
249 $feed->{numposts}=0 unless defined $feed->{numposts};
250 $feed->{newposts}=0 unless defined $feed->{newposts};
251 $feed->{message}=gettext("new feed") unless defined $feed->{message};
252 $feed->{error}=0 unless defined $feed->{error};
258 push @{$feed->{tags}}, $value;
262 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
263 ($feed->{error} ? "<em>" : "").$feed->{message}.
264 ($feed->{error} ? "</em>" : "").
265 " (".$feed->{numposts}." ".gettext("posts").
266 ($feed->{newposts} ? "; ".$feed->{newposts}.
267 " ".gettext("new") : "").
274 # Remove feed data for removed pages.
275 foreach my $file (@files) {
276 my $page=pagename($file);
284 foreach my $id (keys %feeds) {
285 if ($feeds{$id}->{sourcepage} eq $page) {
286 $feeds{$id}->{unseen}=1;
294 return if $state_loaded;
296 if (-e "$config{wikistatedir}/aggregate") {
297 open(IN, "$config{wikistatedir}/aggregate") ||
298 die "$config{wikistatedir}/aggregate: $!";
300 $_=IkiWiki::possibly_foolish_untaint($_);
303 foreach my $i (split(/ /, $_)) {
304 my ($field, $val)=split(/=/, $i, 2);
305 if ($field eq "name" || $field eq "feed" ||
306 $field eq "guid" || $field eq "message") {
307 $data->{$field}=decode_entities($val, " \t\n");
309 elsif ($field eq "tag") {
310 push @{$data->{tags}}, $val;
313 $data->{$field}=$val;
317 if (exists $data->{name}) {
318 $feeds{$data->{name}}=$data;
320 elsif (exists $data->{guid}) {
321 $guids{$data->{guid}}=$data;
330 return unless $state_loaded;
332 my $newfile="$config{wikistatedir}/aggregate.new";
333 my $cleanup = sub { unlink($newfile) };
334 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
335 foreach my $data (values %feeds, values %guids) {
337 foreach my $field (keys %$data) {
338 if ($field eq "name" || $field eq "feed" ||
339 $field eq "guid" || $field eq "message") {
340 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
342 elsif ($field eq "tags") {
343 push @line, "tag=$_" foreach @{$data->{tags}};
346 push @line, "$field=".$data->{$field}
347 if defined $data->{$field};
350 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
352 close OUT || error("save $newfile: $!", $cleanup);
353 rename($newfile, "$config{wikistatedir}/aggregate") ||
354 error("rename $newfile: $!", $cleanup);
357 sub garbage_collect () {
358 foreach my $name (keys %feeds) {
359 # remove any feeds that were not seen while building the pages
360 # that used to contain them
361 if ($feeds{$name}->{unseen}) {
362 delete $feeds{$name};
366 foreach my $guid (values %guids) {
367 # any guid whose feed is gone should be removed
368 if (! exists $feeds{$guid->{feed}}) {
369 unlink "$config{srcdir}/".htmlfn($guid->{page})
370 if exists $guid->{page};
371 delete $guids{$guid->{guid}};
373 # handle expired guids
374 elsif ($guid->{expired} && exists $guid->{page}) {
375 unlink "$config{srcdir}/".htmlfn($guid->{page});
376 delete $guid->{page};
383 # Load the current state in from disk, and merge into it
384 # values from the state in memory that might have changed
385 # during aggregation.
391 # All that can change in feed state during aggregation is a few
393 foreach my $name (keys %myfeeds) {
394 if (exists $feeds{$name}) {
395 foreach my $field (qw{message lastupdate lasttry
396 numposts newposts error}) {
397 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
402 # New guids can be created during aggregation.
403 # It's also possible that guids were removed from the on-disk state
404 # while the aggregation was in process. That would only happen if
405 # their feed was also removed, so any removed guids added back here
406 # will be garbage collected later.
407 foreach my $guid (keys %myguids) {
408 if (! exists $guids{$guid}) {
409 $guids{$guid}=$myguids{$guid};
421 foreach my $feed (values %feeds) {
422 next unless $feed->{expireage} || $feed->{expirecount};
425 foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
426 grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
428 if ($feed->{expireage}) {
429 my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
430 if ($days_old > $feed->{expireage}) {
431 debug(sprintf(gettext("expiring %s (%s days old)"),
432 $item->{page}, int($days_old)));
436 elsif ($feed->{expirecount} &&
437 $count >= $feed->{expirecount}) {
438 debug(sprintf(gettext("expiring %s"), $item->{page}));
442 if (! $seen{$item->{page}}) {
443 $seen{$item->{page}}=1;
451 sub needsaggregate () {
452 return values %feeds if $config{rebuild};
453 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
457 eval q{use XML::Feed};
459 eval q{use URI::Fetch};
462 foreach my $feed (@_) {
463 $feed->{lasttry}=time;
465 $feed->{message}=sprintf(gettext("last checked %s"),
466 displaytime($feed->{lasttry}));
469 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
471 if (! length $feed->{feedurl}) {
472 my @urls=XML::Feed->find_feeds($feed->{url});
474 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
476 debug($feed->{message});
479 $feed->{feedurl}=pop @urls;
481 my $res=URI::Fetch->fetch($feed->{feedurl});
483 $feed->{message}=URI::Fetch->errstr;
485 debug($feed->{message});
489 # lastupdate is only set if we were able to contact the server
490 $feed->{lastupdate}=$feed->{lasttry};
492 if ($res->status == URI::Fetch::URI_GONE()) {
493 $feed->{message}=gettext("feed not found");
495 debug($feed->{message});
498 my $content=$res->content;
499 my $f=eval{XML::Feed->parse(\$content)};
501 # One common cause of XML::Feed crashing is a feed
502 # that contains invalid UTF-8 sequences. Convert
503 # feed to ascii to try to work around.
504 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
506 $content=Encode::decode_utf8($content, 0);
507 XML::Feed->parse(\$content)
511 # Another possibility is badly escaped entities.
512 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
513 $content=~s/\&(?!amp)(\w+);/&$1;/g;
515 $content=Encode::decode_utf8($content, 0);
516 XML::Feed->parse(\$content)
520 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
522 debug($feed->{message});
526 $feed->{message}=XML::Feed->errstr;
528 debug($feed->{message});
532 foreach my $entry ($f->entries) {
533 my $c=$entry->content;
534 # atom feeds may have no content, only a summary
535 if (! defined $c && ref $entry->summary) {
541 copyright => $f->copyright,
542 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
543 link => $entry->link,
544 content => (defined $c && defined $c->body) ? $c->body : "",
545 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
546 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
547 base => (defined $c && $c->can("base")) ? $c->base : undef,
556 my $feed=$params{feed};
559 if (exists $guids{$params{guid}}) {
560 # updating an existing post
561 $guid=$guids{$params{guid}};
562 return if $guid->{expired};
566 $guid->{guid}=$params{guid};
567 $guids{$params{guid}}=$guid;
568 $mtime=$params{ctime};
572 # assign it an unused page
573 my $page=titlepage($params{title});
574 # escape slashes and periods in title so it doesn't specify
575 # directory name or trigger ".." disallowing code.
576 $page=~s!([/.])!"__".ord($1)."__"!eg;
577 $page=$feed->{dir}."/".$page;
578 ($page)=$page=~/$config{wiki_file_regexp}/;
579 if (! defined $page || ! length $page) {
580 $page=$feed->{dir}."/item";
583 while (exists $IkiWiki::pagecase{lc $page.$c} ||
584 -e "$config{srcdir}/".htmlfn($page.$c)) {
588 # Make sure that the file name isn't too long.
589 # NB: This doesn't check for path length limits.
590 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
591 if (defined $max && length(htmlfn($page)) >= $max) {
593 $page=$feed->{dir}."/item";
594 while (exists $IkiWiki::pagecase{lc $page.$c} ||
595 -e "$config{srcdir}/".htmlfn($page.$c)) {
601 debug(sprintf(gettext("creating new page %s"), $page));
603 $guid->{feed}=$feed->{name};
605 # To write or not to write? Need to avoid writing unchanged pages
606 # to avoid unneccessary rebuilding. The mtime from rss cannot be
607 # trusted; let's use a digest.
608 eval q{use Digest::MD5 'md5_hex'};
611 my $digest=md5_hex(Encode::encode_utf8($params{content}));
612 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
613 $guid->{md5}=$digest;
616 my $template=template($feed->{template}, blind_cache => 1);
617 $template->param(title => $params{title})
618 if defined $params{title} && length($params{title});
619 $template->param(content => wikiescape(htmlabs($params{content},
620 defined $params{base} ? $params{base} : $feed->{feedurl})));
621 $template->param(name => $feed->{name});
622 $template->param(url => $feed->{url});
623 $template->param(copyright => $params{copyright})
624 if defined $params{copyright} && length $params{copyright};
625 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
626 if defined $params{link};
627 if (ref $feed->{tags}) {
628 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
630 writefile(htmlfn($guid->{page}), $config{srcdir},
633 if (defined $mtime && $mtime <= time) {
634 # Set the mtime, this lets the build process get the right
635 # creation time on record for the new page.
636 utime $mtime, $mtime, "$config{srcdir}/".htmlfn($guid->{page});
637 # Store it in pagectime for expiry code to use also.
638 $IkiWiki::pagectime{$guid->{page}}=$mtime;
641 # Dummy value for expiry code.
642 $IkiWiki::pagectime{$guid->{page}}=time;
647 # escape accidental wikilinks and preprocessor stuff
648 return encode_entities(shift, '\[\]');
655 URI->new_abs($url, $urlbase)->as_string;
659 # Convert links in html from relative to absolute.
660 # Note that this is a heuristic, which is not specified by the rss
661 # spec and may not be right for all feeds. Also, see Debian
667 my $p = HTML::Parser->new(api_version => 3);
668 $p->handler(default => sub { $ret.=join("", @_) }, "text");
669 $p->handler(start => sub {
670 my ($tagname, $pos, $text) = @_;
671 if (ref $HTML::Tagset::linkElements{$tagname}) {
673 # use attribute sets from right to left
674 # to avoid invalidating the offsets
675 # when replacing the values
676 my($k_offset, $k_len, $v_offset, $v_len) =
678 my $attrname = lc(substr($text, $k_offset, $k_len));
679 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
680 next unless $v_offset; # 0 v_offset means no value
681 my $v = substr($text, $v_offset, $v_len);
682 $v =~ s/^([\'\"])(.*)\1$/$2/;
683 my $new_v=urlabs($v, $urlbase);
684 $new_v =~ s/\"/"/g; # since we quote with ""
685 substr($text, $v_offset, $v_len) = qq("$new_v");
689 }, "tagname, tokenpos, text");
697 return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
702 sub lockaggregate () {
703 # Take an exclusive lock to prevent multiple concurrent aggregators.
704 # Returns true if the lock was aquired.
705 if (! -d $config{wikistatedir}) {
706 mkdir($config{wikistatedir});
708 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
709 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
710 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
711 close($aggregatelock) || error("failed closing aggregatelock: $!");
717 sub unlockaggregate () {
718 return close($aggregatelock) if $aggregatelock;