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 sub migrate_to_internal { #{{{
125 if (! lockaggregate()) {
126 error("an aggregation process is already running");
133 foreach my $data (values %guids) {
134 next unless $data->{page};
136 $config{aggregateinternal} = 0;
137 my $oldname = pagefile($data->{page});
139 $config{aggregateinternal} = 1;
140 my $newname = pagefile($data->{page});
142 print "I: $oldname -> $newname\n";
145 error("$newname already exists");
149 "W: already renamed to $newname?\n";
152 elsif (-e $oldname) {
153 rename($oldname, $newname) || error("$!");
156 print "W: $oldname not found\n";
166 sub needsbuild (@) { #{{{
167 my $needsbuild=shift;
171 foreach my $feed (values %feeds) {
172 if (exists $pagesources{$feed->{sourcepage}} &&
173 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
174 # Mark all feeds originating on this page as
175 # not yet seen; preprocess will unmark those that
177 markunseen($feed->{sourcepage});
182 sub preprocess (@) { #{{{
185 foreach my $required (qw{name url}) {
186 if (! exists $params{$required}) {
187 error sprintf(gettext("missing %s parameter"), $required)
192 my $name=$params{name};
193 if (exists $feeds{$name}) {
200 $feed->{sourcepage}=$params{page};
201 $feed->{url}=$params{url};
202 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
204 ($dir)=$dir=~/$config{wiki_file_regexp}/;
206 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
207 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
208 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
209 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
210 if (exists $params{template}) {
211 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
214 $params{template} = "aggregatepost"
216 $feed->{template}=$params{template} . ".tmpl";
217 delete $feed->{unseen};
218 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
219 $feed->{numposts}=0 unless defined $feed->{numposts};
220 $feed->{newposts}=0 unless defined $feed->{newposts};
221 $feed->{message}=gettext("new feed") unless defined $feed->{message};
222 $feed->{error}=0 unless defined $feed->{error};
228 push @{$feed->{tags}}, $value;
232 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
233 ($feed->{error} ? "<em>" : "").$feed->{message}.
234 ($feed->{error} ? "</em>" : "").
235 " (".$feed->{numposts}." ".gettext("posts").
236 ($feed->{newposts} ? "; ".$feed->{newposts}.
237 " ".gettext("new") : "").
241 sub delete (@) { #{{{
244 # Remove feed data for removed pages.
245 foreach my $file (@files) {
246 my $page=pagename($file);
251 sub markunseen ($) { #{{{
254 foreach my $id (keys %feeds) {
255 if ($feeds{$id}->{sourcepage} eq $page) {
256 $feeds{$id}->{unseen}=1;
263 sub loadstate () { #{{{
264 return if $state_loaded;
266 if (-e "$config{wikistatedir}/aggregate") {
267 open(IN, "$config{wikistatedir}/aggregate") ||
268 die "$config{wikistatedir}/aggregate: $!";
270 $_=IkiWiki::possibly_foolish_untaint($_);
273 foreach my $i (split(/ /, $_)) {
274 my ($field, $val)=split(/=/, $i, 2);
275 if ($field eq "name" || $field eq "feed" ||
276 $field eq "guid" || $field eq "message") {
277 $data->{$field}=decode_entities($val, " \t\n");
279 elsif ($field eq "tag") {
280 push @{$data->{tags}}, $val;
283 $data->{$field}=$val;
287 if (exists $data->{name}) {
288 $feeds{$data->{name}}=$data;
290 elsif (exists $data->{guid}) {
291 $guids{$data->{guid}}=$data;
299 sub savestate () { #{{{
300 return unless $state_loaded;
302 my $newfile="$config{wikistatedir}/aggregate.new";
303 my $cleanup = sub { unlink($newfile) };
304 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
305 foreach my $data (values %feeds, values %guids) {
307 foreach my $field (keys %$data) {
308 if ($field eq "name" || $field eq "feed" ||
309 $field eq "guid" || $field eq "message") {
310 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
312 elsif ($field eq "tags") {
313 push @line, "tag=$_" foreach @{$data->{tags}};
316 push @line, "$field=".$data->{$field};
319 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
321 close OUT || error("save $newfile: $!", $cleanup);
322 rename($newfile, "$config{wikistatedir}/aggregate") ||
323 error("rename $newfile: $!", $cleanup);
326 sub garbage_collect () { #{{{
327 foreach my $name (keys %feeds) {
328 # remove any feeds that were not seen while building the pages
329 # that used to contain them
330 if ($feeds{$name}->{unseen}) {
331 delete $feeds{$name};
335 foreach my $guid (values %guids) {
336 # any guid whose feed is gone should be removed
337 if (! exists $feeds{$guid->{feed}}) {
338 unlink pagefile($guid->{page})
339 if exists $guid->{page};
340 delete $guids{$guid->{guid}};
342 # handle expired guids
343 elsif ($guid->{expired} && exists $guid->{page}) {
344 unlink pagefile($guid->{page});
345 delete $guid->{page};
351 sub mergestate () { #{{{
352 # Load the current state in from disk, and merge into it
353 # values from the state in memory that might have changed
354 # during aggregation.
360 # All that can change in feed state during aggregation is a few
362 foreach my $name (keys %myfeeds) {
363 if (exists $feeds{$name}) {
364 foreach my $field (qw{message lastupdate numposts
366 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
371 # New guids can be created during aggregation.
372 # It's also possible that guids were removed from the on-disk state
373 # while the aggregation was in process. That would only happen if
374 # their feed was also removed, so any removed guids added back here
375 # will be garbage collected later.
376 foreach my $guid (keys %myguids) {
377 if (! exists $guids{$guid}) {
378 $guids{$guid}=$myguids{$guid};
383 sub clearstate () { #{{{
390 foreach my $feed (values %feeds) {
391 next unless $feed->{expireage} || $feed->{expirecount};
394 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
395 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
397 if ($feed->{expireage}) {
398 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
399 if ($days_old > $feed->{expireage}) {
400 debug(sprintf(gettext("expiring %s (%s days old)"),
401 $item->{page}, int($days_old)));
405 elsif ($feed->{expirecount} &&
406 $count >= $feed->{expirecount}) {
407 debug(sprintf(gettext("expiring %s"), $item->{page}));
411 if (! $seen{$item->{page}}) {
412 $seen{$item->{page}}=1;
420 sub needsaggregate () { #{{{
421 return values %feeds if $config{rebuild};
422 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
425 sub aggregate (@) { #{{{
426 eval q{use XML::Feed};
428 eval q{use URI::Fetch};
431 foreach my $feed (@_) {
432 $feed->{lastupdate}=time;
434 $feed->{message}=sprintf(gettext("processed ok at %s"),
435 displaytime($feed->{lastupdate}));
438 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
440 if (! length $feed->{feedurl}) {
441 my @urls=XML::Feed->find_feeds($feed->{url});
443 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
445 debug($feed->{message});
448 $feed->{feedurl}=pop @urls;
450 my $res=URI::Fetch->fetch($feed->{feedurl});
452 $feed->{message}=URI::Fetch->errstr;
454 debug($feed->{message});
457 if ($res->status == URI::Fetch::URI_GONE()) {
458 $feed->{message}=gettext("feed not found");
460 debug($feed->{message});
463 my $content=$res->content;
464 my $f=eval{XML::Feed->parse(\$content)};
466 # One common cause of XML::Feed crashing is a feed
467 # that contains invalid UTF-8 sequences. Convert
468 # feed to ascii to try to work around.
469 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
470 $content=Encode::decode_utf8($content, 0);
471 $f=eval{XML::Feed->parse(\$content)};
474 # Another possibility is badly escaped entities.
475 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
476 $content=~s/\&(?!amp)(\w+);/&$1;/g;
477 $content=Encode::decode_utf8($content, 0);
478 $f=eval{XML::Feed->parse(\$content)};
481 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
483 debug($feed->{message});
487 $feed->{message}=XML::Feed->errstr;
489 debug($feed->{message});
493 foreach my $entry ($f->entries) {
496 copyright => $f->copyright,
497 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
498 link => $entry->link,
499 content => defined $entry->content->body ? $entry->content->body : "",
500 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
501 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
507 sub add_page (@) { #{{{
510 my $feed=$params{feed};
513 if (exists $guids{$params{guid}}) {
514 # updating an existing post
515 $guid=$guids{$params{guid}};
516 return if $guid->{expired};
520 $guid->{guid}=$params{guid};
521 $guids{$params{guid}}=$guid;
522 $mtime=$params{ctime};
526 # assign it an unused page
527 my $page=IkiWiki::titlepage($params{title});
528 # escape slashes and periods in title so it doesn't specify
529 # directory name or trigger ".." disallowing code.
530 $page=~s!([/.])!"__".ord($1)."__"!eg;
531 $page=$feed->{dir}."/".$page;
532 ($page)=$page=~/$config{wiki_file_regexp}/;
533 if (! defined $page || ! length $page) {
534 $page=$feed->{dir}."/item";
537 while (exists $IkiWiki::pagecase{lc $page.$c} ||
538 -e pagefile($page.$c)) {
542 # Make sure that the file name isn't too long.
543 # NB: This doesn't check for path length limits.
544 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
545 if (defined $max && length(htmlfn($page)) >= $max) {
547 $page=$feed->{dir}."/item";
548 while (exists $IkiWiki::pagecase{lc $page.$c} ||
549 -e pagefile($page.$c)) {
555 debug(sprintf(gettext("creating new page %s"), $page));
557 $guid->{feed}=$feed->{name};
559 # To write or not to write? Need to avoid writing unchanged pages
560 # to avoid unneccessary rebuilding. The mtime from rss cannot be
561 # trusted; let's use a digest.
562 eval q{use Digest::MD5 'md5_hex'};
565 my $digest=md5_hex(Encode::encode_utf8($params{content}));
566 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
567 $guid->{md5}=$digest;
570 my $template=template($feed->{template}, blind_cache => 1);
571 $template->param(title => $params{title})
572 if defined $params{title} && length($params{title});
573 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
574 $template->param(name => $feed->{name});
575 $template->param(url => $feed->{url});
576 $template->param(copyright => $params{copyright})
577 if defined $params{copyright} && length $params{copyright};
578 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
579 if defined $params{link};
580 if (ref $feed->{tags}) {
581 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
583 writefile(htmlfn($guid->{page}), $config{srcdir},
586 # Set the mtime, this lets the build process get the right creation
587 # time on record for the new page.
588 utime $mtime, $mtime, pagefile($guid->{page})
589 if defined $mtime && $mtime <= time;
592 sub htmlescape ($) { #{{{
593 # escape accidental wikilinks and preprocessor stuff
595 $html=~s/(?<!\\)\[\[/\\\[\[/g;
599 sub urlabs ($$) { #{{{
603 URI->new_abs($url, $urlbase)->as_string;
606 sub htmlabs ($$) { #{{{
607 # Convert links in html from relative to absolute.
608 # Note that this is a heuristic, which is not specified by the rss
609 # spec and may not be right for all feeds. Also, see Debian
615 my $p = HTML::Parser->new(api_version => 3);
616 $p->handler(default => sub { $ret.=join("", @_) }, "text");
617 $p->handler(start => sub {
618 my ($tagname, $pos, $text) = @_;
619 if (ref $HTML::Tagset::linkElements{$tagname}) {
621 # use attribute sets from right to left
622 # to avoid invalidating the offsets
623 # when replacing the values
624 my($k_offset, $k_len, $v_offset, $v_len) =
626 my $attrname = lc(substr($text, $k_offset, $k_len));
627 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
628 next unless $v_offset; # 0 v_offset means no value
629 my $v = substr($text, $v_offset, $v_len);
630 $v =~ s/^([\'\"])(.*)\1$/$2/;
631 my $new_v=urlabs($v, $urlbase);
632 $new_v =~ s/\"/"/g; # since we quote with ""
633 substr($text, $v_offset, $v_len) = qq("$new_v");
637 }, "tagname, tokenpos, text");
644 sub pagefile ($) { #{{{
647 return "$config{srcdir}/".htmlfn($page);
650 sub htmlfn ($) { #{{{
651 return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
656 sub lockaggregate () { #{{{
657 # Take an exclusive lock to prevent multiple concurrent aggregators.
658 # Returns true if the lock was aquired.
659 if (! -d $config{wikistatedir}) {
660 mkdir($config{wikistatedir});
662 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
663 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
664 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
665 close($aggregatelock) || error("failed closing aggregatelock: $!");
671 sub unlockaggregate () { #{{{
672 return close($aggregatelock) if $aggregatelock;