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 # Used by ikiwiki-transition aggregateinternal.
117 sub migrate_to_internal { #{{{
118 if (! lockaggregate()) {
119 error("an aggregation process is currently 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 debug "moving $oldname -> $newname";
138 error("$newname already exists");
141 debug("already renamed to $newname?");
144 elsif (-e $oldname) {
145 rename($oldname, $newname) || error("$!");
148 debug("$oldname not found");
158 sub needsbuild (@) { #{{{
159 my $needsbuild=shift;
163 foreach my $feed (values %feeds) {
164 if (exists $pagesources{$feed->{sourcepage}} &&
165 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
166 # Mark all feeds originating on this page as
167 # not yet seen; preprocess will unmark those that
169 markunseen($feed->{sourcepage});
174 sub preprocess (@) { #{{{
177 foreach my $required (qw{name url}) {
178 if (! exists $params{$required}) {
179 error sprintf(gettext("missing %s parameter"), $required)
184 my $name=$params{name};
185 if (exists $feeds{$name}) {
192 $feed->{sourcepage}=$params{page};
193 $feed->{url}=$params{url};
194 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
196 ($dir)=$dir=~/$config{wiki_file_regexp}/;
198 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
199 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
200 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
201 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
202 if (exists $params{template}) {
203 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
206 $params{template} = "aggregatepost"
208 $feed->{template}=$params{template} . ".tmpl";
209 delete $feed->{unseen};
210 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
211 $feed->{numposts}=0 unless defined $feed->{numposts};
212 $feed->{newposts}=0 unless defined $feed->{newposts};
213 $feed->{message}=gettext("new feed") unless defined $feed->{message};
214 $feed->{error}=0 unless defined $feed->{error};
220 push @{$feed->{tags}}, $value;
224 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
225 ($feed->{error} ? "<em>" : "").$feed->{message}.
226 ($feed->{error} ? "</em>" : "").
227 " (".$feed->{numposts}." ".gettext("posts").
228 ($feed->{newposts} ? "; ".$feed->{newposts}.
229 " ".gettext("new") : "").
233 sub delete (@) { #{{{
236 # Remove feed data for removed pages.
237 foreach my $file (@files) {
238 my $page=pagename($file);
243 sub markunseen ($) { #{{{
246 foreach my $id (keys %feeds) {
247 if ($feeds{$id}->{sourcepage} eq $page) {
248 $feeds{$id}->{unseen}=1;
255 sub loadstate () { #{{{
256 return if $state_loaded;
258 if (-e "$config{wikistatedir}/aggregate") {
259 open(IN, "$config{wikistatedir}/aggregate") ||
260 die "$config{wikistatedir}/aggregate: $!";
262 $_=IkiWiki::possibly_foolish_untaint($_);
265 foreach my $i (split(/ /, $_)) {
266 my ($field, $val)=split(/=/, $i, 2);
267 if ($field eq "name" || $field eq "feed" ||
268 $field eq "guid" || $field eq "message") {
269 $data->{$field}=decode_entities($val, " \t\n");
271 elsif ($field eq "tag") {
272 push @{$data->{tags}}, $val;
275 $data->{$field}=$val;
279 if (exists $data->{name}) {
280 $feeds{$data->{name}}=$data;
282 elsif (exists $data->{guid}) {
283 $guids{$data->{guid}}=$data;
291 sub savestate () { #{{{
292 return unless $state_loaded;
294 my $newfile="$config{wikistatedir}/aggregate.new";
295 my $cleanup = sub { unlink($newfile) };
296 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
297 foreach my $data (values %feeds, values %guids) {
299 foreach my $field (keys %$data) {
300 if ($field eq "name" || $field eq "feed" ||
301 $field eq "guid" || $field eq "message") {
302 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
304 elsif ($field eq "tags") {
305 push @line, "tag=$_" foreach @{$data->{tags}};
308 push @line, "$field=".$data->{$field};
311 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
313 close OUT || error("save $newfile: $!", $cleanup);
314 rename($newfile, "$config{wikistatedir}/aggregate") ||
315 error("rename $newfile: $!", $cleanup);
318 sub garbage_collect () { #{{{
319 foreach my $name (keys %feeds) {
320 # remove any feeds that were not seen while building the pages
321 # that used to contain them
322 if ($feeds{$name}->{unseen}) {
323 delete $feeds{$name};
327 foreach my $guid (values %guids) {
328 # any guid whose feed is gone should be removed
329 if (! exists $feeds{$guid->{feed}}) {
330 unlink pagefile($guid->{page})
331 if exists $guid->{page};
332 delete $guids{$guid->{guid}};
334 # handle expired guids
335 elsif ($guid->{expired} && exists $guid->{page}) {
336 unlink pagefile($guid->{page});
337 delete $guid->{page};
343 sub mergestate () { #{{{
344 # Load the current state in from disk, and merge into it
345 # values from the state in memory that might have changed
346 # during aggregation.
352 # All that can change in feed state during aggregation is a few
354 foreach my $name (keys %myfeeds) {
355 if (exists $feeds{$name}) {
356 foreach my $field (qw{message lastupdate numposts
358 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
363 # New guids can be created during aggregation.
364 # It's also possible that guids were removed from the on-disk state
365 # while the aggregation was in process. That would only happen if
366 # their feed was also removed, so any removed guids added back here
367 # will be garbage collected later.
368 foreach my $guid (keys %myguids) {
369 if (! exists $guids{$guid}) {
370 $guids{$guid}=$myguids{$guid};
375 sub clearstate () { #{{{
382 foreach my $feed (values %feeds) {
383 next unless $feed->{expireage} || $feed->{expirecount};
386 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
387 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
389 if ($feed->{expireage}) {
390 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
391 if ($days_old > $feed->{expireage}) {
392 debug(sprintf(gettext("expiring %s (%s days old)"),
393 $item->{page}, int($days_old)));
397 elsif ($feed->{expirecount} &&
398 $count >= $feed->{expirecount}) {
399 debug(sprintf(gettext("expiring %s"), $item->{page}));
403 if (! $seen{$item->{page}}) {
404 $seen{$item->{page}}=1;
412 sub needsaggregate () { #{{{
413 return values %feeds if $config{rebuild};
414 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
417 sub aggregate (@) { #{{{
418 eval q{use XML::Feed};
420 eval q{use URI::Fetch};
423 foreach my $feed (@_) {
424 $feed->{lastupdate}=time;
426 $feed->{message}=sprintf(gettext("processed ok at %s"),
427 displaytime($feed->{lastupdate}));
430 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
432 if (! length $feed->{feedurl}) {
433 my @urls=XML::Feed->find_feeds($feed->{url});
435 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
437 debug($feed->{message});
440 $feed->{feedurl}=pop @urls;
442 my $res=URI::Fetch->fetch($feed->{feedurl});
444 $feed->{message}=URI::Fetch->errstr;
446 debug($feed->{message});
449 if ($res->status == URI::Fetch::URI_GONE()) {
450 $feed->{message}=gettext("feed not found");
452 debug($feed->{message});
455 my $content=$res->content;
456 my $f=eval{XML::Feed->parse(\$content)};
458 # One common cause of XML::Feed crashing is a feed
459 # that contains invalid UTF-8 sequences. Convert
460 # feed to ascii to try to work around.
461 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
462 $content=Encode::decode_utf8($content, 0);
463 $f=eval{XML::Feed->parse(\$content)};
466 # Another possibility is badly escaped entities.
467 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
468 $content=~s/\&(?!amp)(\w+);/&$1;/g;
469 $content=Encode::decode_utf8($content, 0);
470 $f=eval{XML::Feed->parse(\$content)};
473 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
475 debug($feed->{message});
479 $feed->{message}=XML::Feed->errstr;
481 debug($feed->{message});
485 foreach my $entry ($f->entries) {
488 copyright => $f->copyright,
489 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
490 link => $entry->link,
491 content => defined $entry->content->body ? $entry->content->body : "",
492 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
493 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
499 sub add_page (@) { #{{{
502 my $feed=$params{feed};
505 if (exists $guids{$params{guid}}) {
506 # updating an existing post
507 $guid=$guids{$params{guid}};
508 return if $guid->{expired};
512 $guid->{guid}=$params{guid};
513 $guids{$params{guid}}=$guid;
514 $mtime=$params{ctime};
518 # assign it an unused page
519 my $page=IkiWiki::titlepage($params{title});
520 # escape slashes and periods in title so it doesn't specify
521 # directory name or trigger ".." disallowing code.
522 $page=~s!([/.])!"__".ord($1)."__"!eg;
523 $page=$feed->{dir}."/".$page;
524 ($page)=$page=~/$config{wiki_file_regexp}/;
525 if (! defined $page || ! length $page) {
526 $page=$feed->{dir}."/item";
529 while (exists $IkiWiki::pagecase{lc $page.$c} ||
530 -e pagefile($page.$c)) {
534 # Make sure that the file name isn't too long.
535 # NB: This doesn't check for path length limits.
536 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
537 if (defined $max && length(htmlfn($page)) >= $max) {
539 $page=$feed->{dir}."/item";
540 while (exists $IkiWiki::pagecase{lc $page.$c} ||
541 -e pagefile($page.$c)) {
547 debug(sprintf(gettext("creating new page %s"), $page));
549 $guid->{feed}=$feed->{name};
551 # To write or not to write? Need to avoid writing unchanged pages
552 # to avoid unneccessary rebuilding. The mtime from rss cannot be
553 # trusted; let's use a digest.
554 eval q{use Digest::MD5 'md5_hex'};
557 my $digest=md5_hex(Encode::encode_utf8($params{content}));
558 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
559 $guid->{md5}=$digest;
562 my $template=template($feed->{template}, blind_cache => 1);
563 $template->param(title => $params{title})
564 if defined $params{title} && length($params{title});
565 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
566 $template->param(name => $feed->{name});
567 $template->param(url => $feed->{url});
568 $template->param(copyright => $params{copyright})
569 if defined $params{copyright} && length $params{copyright};
570 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
571 if defined $params{link};
572 if (ref $feed->{tags}) {
573 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
575 writefile(htmlfn($guid->{page}), $config{srcdir},
578 # Set the mtime, this lets the build process get the right creation
579 # time on record for the new page.
580 utime $mtime, $mtime, pagefile($guid->{page})
581 if defined $mtime && $mtime <= time;
584 sub htmlescape ($) { #{{{
585 # escape accidental wikilinks and preprocessor stuff
587 $html=~s/(?<!\\)\[\[/\\\[\[/g;
591 sub urlabs ($$) { #{{{
595 URI->new_abs($url, $urlbase)->as_string;
598 sub htmlabs ($$) { #{{{
599 # Convert links in html from relative to absolute.
600 # Note that this is a heuristic, which is not specified by the rss
601 # spec and may not be right for all feeds. Also, see Debian
607 my $p = HTML::Parser->new(api_version => 3);
608 $p->handler(default => sub { $ret.=join("", @_) }, "text");
609 $p->handler(start => sub {
610 my ($tagname, $pos, $text) = @_;
611 if (ref $HTML::Tagset::linkElements{$tagname}) {
613 # use attribute sets from right to left
614 # to avoid invalidating the offsets
615 # when replacing the values
616 my($k_offset, $k_len, $v_offset, $v_len) =
618 my $attrname = lc(substr($text, $k_offset, $k_len));
619 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
620 next unless $v_offset; # 0 v_offset means no value
621 my $v = substr($text, $v_offset, $v_len);
622 $v =~ s/^([\'\"])(.*)\1$/$2/;
623 my $new_v=urlabs($v, $urlbase);
624 $new_v =~ s/\"/"/g; # since we quote with ""
625 substr($text, $v_offset, $v_len) = qq("$new_v");
629 }, "tagname, tokenpos, text");
636 sub pagefile ($) { #{{{
639 return "$config{srcdir}/".htmlfn($page);
642 sub htmlfn ($) { #{{{
643 return shift().".".($config{aggregateinternal} ? "_" : "").$config{htmlext};
648 sub lockaggregate () { #{{{
649 # Take an exclusive lock to prevent multiple concurrent aggregators.
650 # Returns true if the lock was aquired.
651 if (! -d $config{wikistatedir}) {
652 mkdir($config{wikistatedir});
654 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
655 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
656 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
657 close($aggregatelock) || error("failed closing aggregatelock: $!");
663 sub unlockaggregate () { #{{{
664 return close($aggregatelock) if $aggregatelock;