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 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},
40 sub checkconfig () { #{{{
41 if ($config{aggregate} && ! ($config{post_commit} &&
42 IkiWiki::commit_hook_enabled())) {
50 if (defined $cgi->param('do') &&
51 $cgi->param("do") eq "aggregate_webtrigger") {
53 print "Content-Type: text/plain\n\n";
57 print gettext("Aggregation triggered via web.")."\n\n";
58 if (launchaggregation()) {
61 require IkiWiki::Render;
66 print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
72 sub launchaggregation () { #{{{
73 # See if any feeds need aggregation.
75 my @feeds=needsaggregate();
77 if (! lockaggregate()) {
78 debug("an aggregation process is already running");
81 # force a later rebuild of source pages
82 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
85 # Fork a child process to handle the aggregation.
86 # The parent process will then handle building the
87 # result. This avoids messy code to clear state
88 # accumulated while aggregating.
89 defined(my $pid = fork) or error("Can't fork: $!");
92 # Aggregation happens without the main wiki lock
93 # being held. This allows editing pages etc while
94 # aggregation is running.
98 # Merge changes, since aggregation state may have
99 # changed on disk while the aggregation was happening.
108 error "aggregation failed with code $?";
117 # Pages with extension _aggregated have plain html markup, pass through.
118 sub htmlize (@) { #{{{
120 return $params{content};
123 # Used by ikiwiki-transition aggregateinternal.
124 sub migrate_to_internal { #{{{
125 if (! lockaggregate()) {
126 error("an aggregation process is currently running");
133 foreach my $data (values %guids) {
134 next unless $data->{page};
135 next if $data->{expired};
137 $config{aggregateinternal} = 0;
138 my $oldname = pagefile($data->{page});
139 my $oldoutput = $config{destdir}."/".IkiWiki::htmlpage($data->{page});
141 $config{aggregateinternal} = 1;
142 my $newname = pagefile($data->{page});
144 debug "moving $oldname -> $newname";
147 error("$newname already exists");
150 debug("already renamed to $newname?");
153 elsif (-e $oldname) {
154 rename($oldname, $newname) || error("$!");
157 debug("$oldname not found");
160 require IkiWiki::Render;
161 debug("removing output file $oldoutput");
162 IkiWiki::prune($oldoutput);
172 sub needsbuild (@) { #{{{
173 my $needsbuild=shift;
177 foreach my $feed (values %feeds) {
178 if (exists $pagesources{$feed->{sourcepage}} &&
179 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
180 # Mark all feeds originating on this page as
181 # not yet seen; preprocess will unmark those that
183 markunseen($feed->{sourcepage});
188 sub preprocess (@) { #{{{
191 foreach my $required (qw{name url}) {
192 if (! exists $params{$required}) {
193 error sprintf(gettext("missing %s parameter"), $required)
198 my $name=$params{name};
199 if (exists $feeds{$name}) {
206 $feed->{sourcepage}=$params{page};
207 $feed->{url}=$params{url};
208 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
210 ($dir)=$dir=~/$config{wiki_file_regexp}/;
212 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
213 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
214 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
215 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
216 if (exists $params{template}) {
217 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
220 $params{template} = "aggregatepost"
222 $feed->{template}=$params{template} . ".tmpl";
223 delete $feed->{unseen};
224 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
225 $feed->{numposts}=0 unless defined $feed->{numposts};
226 $feed->{newposts}=0 unless defined $feed->{newposts};
227 $feed->{message}=gettext("new feed") unless defined $feed->{message};
228 $feed->{error}=0 unless defined $feed->{error};
234 push @{$feed->{tags}}, $value;
238 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
239 ($feed->{error} ? "<em>" : "").$feed->{message}.
240 ($feed->{error} ? "</em>" : "").
241 " (".$feed->{numposts}." ".gettext("posts").
242 ($feed->{newposts} ? "; ".$feed->{newposts}.
243 " ".gettext("new") : "").
247 sub delete (@) { #{{{
250 # Remove feed data for removed pages.
251 foreach my $file (@files) {
252 my $page=pagename($file);
257 sub markunseen ($) { #{{{
260 foreach my $id (keys %feeds) {
261 if ($feeds{$id}->{sourcepage} eq $page) {
262 $feeds{$id}->{unseen}=1;
269 sub loadstate () { #{{{
270 return if $state_loaded;
272 if (-e "$config{wikistatedir}/aggregate") {
273 open(IN, "$config{wikistatedir}/aggregate") ||
274 die "$config{wikistatedir}/aggregate: $!";
276 $_=IkiWiki::possibly_foolish_untaint($_);
279 foreach my $i (split(/ /, $_)) {
280 my ($field, $val)=split(/=/, $i, 2);
281 if ($field eq "name" || $field eq "feed" ||
282 $field eq "guid" || $field eq "message") {
283 $data->{$field}=decode_entities($val, " \t\n");
285 elsif ($field eq "tag") {
286 push @{$data->{tags}}, $val;
289 $data->{$field}=$val;
293 if (exists $data->{name}) {
294 $feeds{$data->{name}}=$data;
296 elsif (exists $data->{guid}) {
297 $guids{$data->{guid}}=$data;
305 sub savestate () { #{{{
306 return unless $state_loaded;
308 my $newfile="$config{wikistatedir}/aggregate.new";
309 my $cleanup = sub { unlink($newfile) };
310 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
311 foreach my $data (values %feeds, values %guids) {
313 foreach my $field (keys %$data) {
314 if ($field eq "name" || $field eq "feed" ||
315 $field eq "guid" || $field eq "message") {
316 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
318 elsif ($field eq "tags") {
319 push @line, "tag=$_" foreach @{$data->{tags}};
322 push @line, "$field=".$data->{$field};
325 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
327 close OUT || error("save $newfile: $!", $cleanup);
328 rename($newfile, "$config{wikistatedir}/aggregate") ||
329 error("rename $newfile: $!", $cleanup);
332 sub garbage_collect () { #{{{
333 foreach my $name (keys %feeds) {
334 # remove any feeds that were not seen while building the pages
335 # that used to contain them
336 if ($feeds{$name}->{unseen}) {
337 delete $feeds{$name};
341 foreach my $guid (values %guids) {
342 # any guid whose feed is gone should be removed
343 if (! exists $feeds{$guid->{feed}}) {
344 unlink pagefile($guid->{page})
345 if exists $guid->{page};
346 delete $guids{$guid->{guid}};
348 # handle expired guids
349 elsif ($guid->{expired} && exists $guid->{page}) {
350 unlink pagefile($guid->{page});
351 delete $guid->{page};
357 sub mergestate () { #{{{
358 # Load the current state in from disk, and merge into it
359 # values from the state in memory that might have changed
360 # during aggregation.
366 # All that can change in feed state during aggregation is a few
368 foreach my $name (keys %myfeeds) {
369 if (exists $feeds{$name}) {
370 foreach my $field (qw{message lastupdate numposts
372 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
377 # New guids can be created during aggregation.
378 # It's also possible that guids were removed from the on-disk state
379 # while the aggregation was in process. That would only happen if
380 # their feed was also removed, so any removed guids added back here
381 # will be garbage collected later.
382 foreach my $guid (keys %myguids) {
383 if (! exists $guids{$guid}) {
384 $guids{$guid}=$myguids{$guid};
389 sub clearstate () { #{{{
396 foreach my $feed (values %feeds) {
397 next unless $feed->{expireage} || $feed->{expirecount};
400 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
401 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
403 if ($feed->{expireage}) {
404 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
405 if ($days_old > $feed->{expireage}) {
406 debug(sprintf(gettext("expiring %s (%s days old)"),
407 $item->{page}, int($days_old)));
411 elsif ($feed->{expirecount} &&
412 $count >= $feed->{expirecount}) {
413 debug(sprintf(gettext("expiring %s"), $item->{page}));
417 if (! $seen{$item->{page}}) {
418 $seen{$item->{page}}=1;
426 sub needsaggregate () { #{{{
427 return values %feeds if $config{rebuild};
428 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
431 sub aggregate (@) { #{{{
432 eval q{use XML::Feed};
434 eval q{use URI::Fetch};
437 foreach my $feed (@_) {
438 $feed->{lastupdate}=time;
440 $feed->{message}=sprintf(gettext("processed ok at %s"),
441 displaytime($feed->{lastupdate}));
444 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
446 if (! length $feed->{feedurl}) {
447 my @urls=XML::Feed->find_feeds($feed->{url});
449 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
451 debug($feed->{message});
454 $feed->{feedurl}=pop @urls;
456 my $res=URI::Fetch->fetch($feed->{feedurl});
458 $feed->{message}=URI::Fetch->errstr;
460 debug($feed->{message});
463 if ($res->status == URI::Fetch::URI_GONE()) {
464 $feed->{message}=gettext("feed not found");
466 debug($feed->{message});
469 my $content=$res->content;
470 my $f=eval{XML::Feed->parse(\$content)};
472 # One common cause of XML::Feed crashing is a feed
473 # that contains invalid UTF-8 sequences. Convert
474 # feed to ascii to try to work around.
475 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
476 $content=Encode::decode_utf8($content, 0);
477 $f=eval{XML::Feed->parse(\$content)};
480 # Another possibility is badly escaped entities.
481 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
482 $content=~s/\&(?!amp)(\w+);/&$1;/g;
483 $content=Encode::decode_utf8($content, 0);
484 $f=eval{XML::Feed->parse(\$content)};
487 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
489 debug($feed->{message});
493 $feed->{message}=XML::Feed->errstr;
495 debug($feed->{message});
499 foreach my $entry ($f->entries) {
502 copyright => $f->copyright,
503 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
504 link => $entry->link,
505 content => defined $entry->content->body ? $entry->content->body : "",
506 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
507 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
513 sub add_page (@) { #{{{
516 my $feed=$params{feed};
519 if (exists $guids{$params{guid}}) {
520 # updating an existing post
521 $guid=$guids{$params{guid}};
522 return if $guid->{expired};
526 $guid->{guid}=$params{guid};
527 $guids{$params{guid}}=$guid;
528 $mtime=$params{ctime};
532 # assign it an unused page
533 my $page=IkiWiki::titlepage($params{title});
534 # escape slashes and periods in title so it doesn't specify
535 # directory name or trigger ".." disallowing code.
536 $page=~s!([/.])!"__".ord($1)."__"!eg;
537 $page=$feed->{dir}."/".$page;
538 ($page)=$page=~/$config{wiki_file_regexp}/;
539 if (! defined $page || ! length $page) {
540 $page=$feed->{dir}."/item";
543 while (exists $IkiWiki::pagecase{lc $page.$c} ||
544 -e pagefile($page.$c)) {
548 # Make sure that the file name isn't too long.
549 # NB: This doesn't check for path length limits.
550 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
551 if (defined $max && length(htmlfn($page)) >= $max) {
553 $page=$feed->{dir}."/item";
554 while (exists $IkiWiki::pagecase{lc $page.$c} ||
555 -e pagefile($page.$c)) {
561 debug(sprintf(gettext("creating new page %s"), $page));
563 $guid->{feed}=$feed->{name};
565 # To write or not to write? Need to avoid writing unchanged pages
566 # to avoid unneccessary rebuilding. The mtime from rss cannot be
567 # trusted; let's use a digest.
568 eval q{use Digest::MD5 'md5_hex'};
571 my $digest=md5_hex(Encode::encode_utf8($params{content}));
572 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
573 $guid->{md5}=$digest;
576 my $template=template($feed->{template}, blind_cache => 1);
577 $template->param(title => $params{title})
578 if defined $params{title} && length($params{title});
579 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
580 $template->param(name => $feed->{name});
581 $template->param(url => $feed->{url});
582 $template->param(copyright => $params{copyright})
583 if defined $params{copyright} && length $params{copyright};
584 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
585 if defined $params{link};
586 if (ref $feed->{tags}) {
587 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
589 writefile(htmlfn($guid->{page}), $config{srcdir},
592 # Set the mtime, this lets the build process get the right creation
593 # time on record for the new page.
594 utime $mtime, $mtime, pagefile($guid->{page})
595 if defined $mtime && $mtime <= time;
598 sub htmlescape ($) { #{{{
599 # escape accidental wikilinks and preprocessor stuff
601 $html=~s/(?<!\\)\[\[/\\\[\[/g;
605 sub urlabs ($$) { #{{{
609 URI->new_abs($url, $urlbase)->as_string;
612 sub htmlabs ($$) { #{{{
613 # Convert links in html from relative to absolute.
614 # Note that this is a heuristic, which is not specified by the rss
615 # spec and may not be right for all feeds. Also, see Debian
621 my $p = HTML::Parser->new(api_version => 3);
622 $p->handler(default => sub { $ret.=join("", @_) }, "text");
623 $p->handler(start => sub {
624 my ($tagname, $pos, $text) = @_;
625 if (ref $HTML::Tagset::linkElements{$tagname}) {
627 # use attribute sets from right to left
628 # to avoid invalidating the offsets
629 # when replacing the values
630 my($k_offset, $k_len, $v_offset, $v_len) =
632 my $attrname = lc(substr($text, $k_offset, $k_len));
633 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
634 next unless $v_offset; # 0 v_offset means no value
635 my $v = substr($text, $v_offset, $v_len);
636 $v =~ s/^([\'\"])(.*)\1$/$2/;
637 my $new_v=urlabs($v, $urlbase);
638 $new_v =~ s/\"/"/g; # since we quote with ""
639 substr($text, $v_offset, $v_len) = qq("$new_v");
643 }, "tagname, tokenpos, text");
650 sub pagefile ($) { #{{{
653 return "$config{srcdir}/".htmlfn($page);
656 sub htmlfn ($) { #{{{
657 return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
662 sub lockaggregate () { #{{{
663 # Take an exclusive lock to prevent multiple concurrent aggregators.
664 # Returns true if the lock was aquired.
665 if (! -d $config{wikistatedir}) {
666 mkdir($config{wikistatedir});
668 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
669 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
670 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
671 close($aggregatelock) || error("failed closing aggregatelock: $!");
677 sub unlockaggregate () { #{{{
678 return close($aggregatelock) if $aggregatelock;