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 if (exists $config{aggregate_webtrigger} && $config{aggregate_webtrigger}) {
25 hook(type => "cgi", id => "aggregate", call => \&cgi);
30 eval q{use Getopt::Long};
32 Getopt::Long::Configure('pass_through');
34 "aggregate" => \$config{aggregate},
35 "aggregateinternal!" => \$config{aggregateinternal},
39 sub checkconfig () { #{{{
40 if ($config{aggregate} && ! ($config{post_commit} &&
41 IkiWiki::commit_hook_enabled())) {
49 if (defined $cgi->param('do') &&
50 $cgi->param("do") eq "aggregate_webtrigger") {
52 print "Content-Type: text/plain\n\n";
56 print gettext("Aggregation triggered via web.")."\n\n";
57 if (launchaggregation()) {
60 require IkiWiki::Render;
65 print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
71 sub launchaggregation () { #{{{
72 # See if any feeds need aggregation.
74 my @feeds=needsaggregate();
76 if (! lockaggregate()) {
77 debug("an aggregation process is already running");
80 # force a later rebuild of source pages
81 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
84 # Fork a child process to handle the aggregation.
85 # The parent process will then handle building the
86 # result. This avoids messy code to clear state
87 # accumulated while aggregating.
88 defined(my $pid = fork) or error("Can't fork: $!");
91 # Aggregation happens without the main wiki lock
92 # being held. This allows editing pages etc while
93 # aggregation is running.
97 # Merge changes, since aggregation state may have
98 # changed on disk while the aggregation was happening.
107 error "aggregation failed with code $?";
116 sub migrate_to_internal { #{{{
118 if (! lockaggregate()) {
119 error("an aggregation process is already running");
126 foreach my $data (values %guids) {
127 next unless $data->{page};
129 $config{aggregateinternal} = 0;
130 my $oldname = pagefile($data->{page});
132 $config{aggregateinternal} = 1;
133 my $newname = pagefile($data->{page});
135 print "I: $oldname -> $newname\n";
138 error("$newname already exists");
142 "W: already renamed to $newname?\n";
145 elsif (-e $oldname) {
146 rename($oldname, $newname) || error("$!");
149 print "W: $oldname not found\n";
159 sub needsbuild (@) { #{{{
160 my $needsbuild=shift;
164 foreach my $feed (values %feeds) {
165 if (exists $pagesources{$feed->{sourcepage}} &&
166 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
167 # Mark all feeds originating on this page as
168 # not yet seen; preprocess will unmark those that
170 markunseen($feed->{sourcepage});
175 sub preprocess (@) { #{{{
178 foreach my $required (qw{name url}) {
179 if (! exists $params{$required}) {
180 error sprintf(gettext("missing %s parameter"), $required)
185 my $name=$params{name};
186 if (exists $feeds{$name}) {
193 $feed->{sourcepage}=$params{page};
194 $feed->{url}=$params{url};
195 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
197 ($dir)=$dir=~/$config{wiki_file_regexp}/;
199 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
200 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
201 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
202 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
203 if (exists $params{template}) {
204 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
207 $params{template} = "aggregatepost"
209 $feed->{template}=$params{template} . ".tmpl";
210 delete $feed->{unseen};
211 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
212 $feed->{numposts}=0 unless defined $feed->{numposts};
213 $feed->{newposts}=0 unless defined $feed->{newposts};
214 $feed->{message}=gettext("new feed") unless defined $feed->{message};
215 $feed->{error}=0 unless defined $feed->{error};
221 push @{$feed->{tags}}, $value;
225 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
226 ($feed->{error} ? "<em>" : "").$feed->{message}.
227 ($feed->{error} ? "</em>" : "").
228 " (".$feed->{numposts}." ".gettext("posts").
229 ($feed->{newposts} ? "; ".$feed->{newposts}.
230 " ".gettext("new") : "").
234 sub delete (@) { #{{{
237 # Remove feed data for removed pages.
238 foreach my $file (@files) {
239 my $page=pagename($file);
244 sub markunseen ($) { #{{{
247 foreach my $id (keys %feeds) {
248 if ($feeds{$id}->{sourcepage} eq $page) {
249 $feeds{$id}->{unseen}=1;
256 sub loadstate () { #{{{
257 return if $state_loaded;
259 if (-e "$config{wikistatedir}/aggregate") {
260 open(IN, "$config{wikistatedir}/aggregate") ||
261 die "$config{wikistatedir}/aggregate: $!";
263 $_=IkiWiki::possibly_foolish_untaint($_);
266 foreach my $i (split(/ /, $_)) {
267 my ($field, $val)=split(/=/, $i, 2);
268 if ($field eq "name" || $field eq "feed" ||
269 $field eq "guid" || $field eq "message") {
270 $data->{$field}=decode_entities($val, " \t\n");
272 elsif ($field eq "tag") {
273 push @{$data->{tags}}, $val;
276 $data->{$field}=$val;
280 if (exists $data->{name}) {
281 $feeds{$data->{name}}=$data;
283 elsif (exists $data->{guid}) {
284 $guids{$data->{guid}}=$data;
292 sub savestate () { #{{{
293 return unless $state_loaded;
295 my $newfile="$config{wikistatedir}/aggregate.new";
296 my $cleanup = sub { unlink($newfile) };
297 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
298 foreach my $data (values %feeds, values %guids) {
300 foreach my $field (keys %$data) {
301 if ($field eq "name" || $field eq "feed" ||
302 $field eq "guid" || $field eq "message") {
303 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
305 elsif ($field eq "tags") {
306 push @line, "tag=$_" foreach @{$data->{tags}};
309 push @line, "$field=".$data->{$field};
312 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
314 close OUT || error("save $newfile: $!", $cleanup);
315 rename($newfile, "$config{wikistatedir}/aggregate") ||
316 error("rename $newfile: $!", $cleanup);
319 sub garbage_collect () { #{{{
320 foreach my $name (keys %feeds) {
321 # remove any feeds that were not seen while building the pages
322 # that used to contain them
323 if ($feeds{$name}->{unseen}) {
324 delete $feeds{$name};
328 foreach my $guid (values %guids) {
329 # any guid whose feed is gone should be removed
330 if (! exists $feeds{$guid->{feed}}) {
331 unlink pagefile($guid->{page})
332 if exists $guid->{page};
333 delete $guids{$guid->{guid}};
335 # handle expired guids
336 elsif ($guid->{expired} && exists $guid->{page}) {
337 unlink pagefile($guid->{page});
338 delete $guid->{page};
344 sub mergestate () { #{{{
345 # Load the current state in from disk, and merge into it
346 # values from the state in memory that might have changed
347 # during aggregation.
353 # All that can change in feed state during aggregation is a few
355 foreach my $name (keys %myfeeds) {
356 if (exists $feeds{$name}) {
357 foreach my $field (qw{message lastupdate numposts
359 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
364 # New guids can be created during aggregation.
365 # It's also possible that guids were removed from the on-disk state
366 # while the aggregation was in process. That would only happen if
367 # their feed was also removed, so any removed guids added back here
368 # will be garbage collected later.
369 foreach my $guid (keys %myguids) {
370 if (! exists $guids{$guid}) {
371 $guids{$guid}=$myguids{$guid};
376 sub clearstate () { #{{{
383 foreach my $feed (values %feeds) {
384 next unless $feed->{expireage} || $feed->{expirecount};
387 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
388 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
390 if ($feed->{expireage}) {
391 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
392 if ($days_old > $feed->{expireage}) {
393 debug(sprintf(gettext("expiring %s (%s days old)"),
394 $item->{page}, int($days_old)));
398 elsif ($feed->{expirecount} &&
399 $count >= $feed->{expirecount}) {
400 debug(sprintf(gettext("expiring %s"), $item->{page}));
404 if (! $seen{$item->{page}}) {
405 $seen{$item->{page}}=1;
413 sub needsaggregate () { #{{{
414 return values %feeds if $config{rebuild};
415 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
418 sub aggregate (@) { #{{{
419 eval q{use XML::Feed};
421 eval q{use URI::Fetch};
424 foreach my $feed (@_) {
425 $feed->{lastupdate}=time;
427 $feed->{message}=sprintf(gettext("processed ok at %s"),
428 displaytime($feed->{lastupdate}));
431 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
433 if (! length $feed->{feedurl}) {
434 my @urls=XML::Feed->find_feeds($feed->{url});
436 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
438 debug($feed->{message});
441 $feed->{feedurl}=pop @urls;
443 my $res=URI::Fetch->fetch($feed->{feedurl});
445 $feed->{message}=URI::Fetch->errstr;
447 debug($feed->{message});
450 if ($res->status == URI::Fetch::URI_GONE()) {
451 $feed->{message}=gettext("feed not found");
453 debug($feed->{message});
456 my $content=$res->content;
457 my $f=eval{XML::Feed->parse(\$content)};
459 # One common cause of XML::Feed crashing is a feed
460 # that contains invalid UTF-8 sequences. Convert
461 # feed to ascii to try to work around.
462 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
463 $content=Encode::decode_utf8($content, 0);
464 $f=eval{XML::Feed->parse(\$content)};
467 # Another possibility is badly escaped entities.
468 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
469 $content=~s/\&(?!amp)(\w+);/&$1;/g;
470 $content=Encode::decode_utf8($content, 0);
471 $f=eval{XML::Feed->parse(\$content)};
474 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
476 debug($feed->{message});
480 $feed->{message}=XML::Feed->errstr;
482 debug($feed->{message});
486 foreach my $entry ($f->entries) {
489 copyright => $f->copyright,
490 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
491 link => $entry->link,
492 content => defined $entry->content->body ? $entry->content->body : "",
493 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
494 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
500 sub add_page (@) { #{{{
503 my $feed=$params{feed};
506 if (exists $guids{$params{guid}}) {
507 # updating an existing post
508 $guid=$guids{$params{guid}};
509 return if $guid->{expired};
513 $guid->{guid}=$params{guid};
514 $guids{$params{guid}}=$guid;
515 $mtime=$params{ctime};
519 # assign it an unused page
520 my $page=IkiWiki::titlepage($params{title});
521 # escape slashes and periods in title so it doesn't specify
522 # directory name or trigger ".." disallowing code.
523 $page=~s!([/.])!"__".ord($1)."__"!eg;
524 $page=$feed->{dir}."/".$page;
525 ($page)=$page=~/$config{wiki_file_regexp}/;
526 if (! defined $page || ! length $page) {
527 $page=$feed->{dir}."/item";
530 while (exists $IkiWiki::pagecase{lc $page.$c} ||
531 -e pagefile($page.$c)) {
535 # Make sure that the file name isn't too long.
536 # NB: This doesn't check for path length limits.
537 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
538 if (defined $max && length(htmlfn($page)) >= $max) {
540 $page=$feed->{dir}."/item";
541 while (exists $IkiWiki::pagecase{lc $page.$c} ||
542 -e pagefile($page.$c)) {
548 debug(sprintf(gettext("creating new page %s"), $page));
550 $guid->{feed}=$feed->{name};
552 # To write or not to write? Need to avoid writing unchanged pages
553 # to avoid unneccessary rebuilding. The mtime from rss cannot be
554 # trusted; let's use a digest.
555 eval q{use Digest::MD5 'md5_hex'};
558 my $digest=md5_hex(Encode::encode_utf8($params{content}));
559 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
560 $guid->{md5}=$digest;
563 my $template=template($feed->{template}, blind_cache => 1);
564 $template->param(title => $params{title})
565 if defined $params{title} && length($params{title});
566 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
567 $template->param(name => $feed->{name});
568 $template->param(url => $feed->{url});
569 $template->param(copyright => $params{copyright})
570 if defined $params{copyright} && length $params{copyright};
571 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
572 if defined $params{link};
573 if (ref $feed->{tags}) {
574 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
576 writefile(htmlfn($guid->{page}), $config{srcdir},
579 # Set the mtime, this lets the build process get the right creation
580 # time on record for the new page.
581 utime $mtime, $mtime, pagefile($guid->{page})
582 if defined $mtime && $mtime <= time;
585 sub htmlescape ($) { #{{{
586 # escape accidental wikilinks and preprocessor stuff
588 $html=~s/(?<!\\)\[\[/\\\[\[/g;
592 sub urlabs ($$) { #{{{
596 URI->new_abs($url, $urlbase)->as_string;
599 sub htmlabs ($$) { #{{{
600 # Convert links in html from relative to absolute.
601 # Note that this is a heuristic, which is not specified by the rss
602 # spec and may not be right for all feeds. Also, see Debian
608 my $p = HTML::Parser->new(api_version => 3);
609 $p->handler(default => sub { $ret.=join("", @_) }, "text");
610 $p->handler(start => sub {
611 my ($tagname, $pos, $text) = @_;
612 if (ref $HTML::Tagset::linkElements{$tagname}) {
614 # use attribute sets from right to left
615 # to avoid invalidating the offsets
616 # when replacing the values
617 my($k_offset, $k_len, $v_offset, $v_len) =
619 my $attrname = lc(substr($text, $k_offset, $k_len));
620 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
621 next unless $v_offset; # 0 v_offset means no value
622 my $v = substr($text, $v_offset, $v_len);
623 $v =~ s/^([\'\"])(.*)\1$/$2/;
624 my $new_v=urlabs($v, $urlbase);
625 $new_v =~ s/\"/"/g; # since we quote with ""
626 substr($text, $v_offset, $v_len) = qq("$new_v");
630 }, "tagname, tokenpos, text");
637 sub pagefile ($) { #{{{
640 return "$config{srcdir}/".htmlfn($page);
643 sub htmlfn ($) { #{{{
644 return shift().".".($config{aggregateinternal} ? "_" : "").$config{htmlext};
649 sub lockaggregate () { #{{{
650 # Take an exclusive lock to prevent multiple concurrent aggregators.
651 # Returns true if the lock was aquired.
652 if (! -d $config{wikistatedir}) {
653 mkdir($config{wikistatedir});
655 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
656 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
657 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
658 close($aggregatelock) || error("failed closing aggregatelock: $!");
664 sub unlockaggregate () { #{{{
665 return close($aggregatelock) if $aggregatelock;