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 needsbuild (@) { #{{{
117 my $needsbuild=shift;
121 foreach my $feed (values %feeds) {
122 if (exists $pagesources{$feed->{sourcepage}} &&
123 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
124 # Mark all feeds originating on this page as
125 # not yet seen; preprocess will unmark those that
127 markunseen($feed->{sourcepage});
132 sub preprocess (@) { #{{{
135 foreach my $required (qw{name url}) {
136 if (! exists $params{$required}) {
137 return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
142 my $name=$params{name};
143 if (exists $feeds{$name}) {
150 $feed->{sourcepage}=$params{page};
151 $feed->{url}=$params{url};
152 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
154 ($dir)=$dir=~/$config{wiki_file_regexp}/;
156 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
157 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
158 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
159 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
160 if (exists $params{template}) {
161 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
164 $params{template} = "aggregatepost"
166 $feed->{template}=$params{template} . ".tmpl";
167 delete $feed->{unseen};
168 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
169 $feed->{numposts}=0 unless defined $feed->{numposts};
170 $feed->{newposts}=0 unless defined $feed->{newposts};
171 $feed->{message}=gettext("new feed") unless defined $feed->{message};
172 $feed->{error}=0 unless defined $feed->{error};
178 push @{$feed->{tags}}, $value;
182 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
183 ($feed->{error} ? "<em>" : "").$feed->{message}.
184 ($feed->{error} ? "</em>" : "").
185 " (".$feed->{numposts}." ".gettext("posts").
186 ($feed->{newposts} ? "; ".$feed->{newposts}.
187 " ".gettext("new") : "").
191 sub delete (@) { #{{{
194 # Remove feed data for removed pages.
195 foreach my $file (@files) {
196 my $page=pagename($file);
201 sub markunseen ($) { #{{{
204 foreach my $id (keys %feeds) {
205 if ($feeds{$id}->{sourcepage} eq $page) {
206 $feeds{$id}->{unseen}=1;
213 sub loadstate () { #{{{
214 return if $state_loaded;
216 if (-e "$config{wikistatedir}/aggregate") {
217 open(IN, "$config{wikistatedir}/aggregate") ||
218 die "$config{wikistatedir}/aggregate: $!";
220 $_=IkiWiki::possibly_foolish_untaint($_);
223 foreach my $i (split(/ /, $_)) {
224 my ($field, $val)=split(/=/, $i, 2);
225 if ($field eq "name" || $field eq "feed" ||
226 $field eq "guid" || $field eq "message") {
227 $data->{$field}=decode_entities($val, " \t\n");
229 elsif ($field eq "tag") {
230 push @{$data->{tags}}, $val;
233 $data->{$field}=$val;
237 if (exists $data->{name}) {
238 $feeds{$data->{name}}=$data;
240 elsif (exists $data->{guid}) {
241 $guids{$data->{guid}}=$data;
249 sub savestate () { #{{{
250 return unless $state_loaded;
252 my $newfile="$config{wikistatedir}/aggregate.new";
253 my $cleanup = sub { unlink($newfile) };
254 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
255 foreach my $data (values %feeds, values %guids) {
257 foreach my $field (keys %$data) {
258 if ($field eq "name" || $field eq "feed" ||
259 $field eq "guid" || $field eq "message") {
260 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
262 elsif ($field eq "tags") {
263 push @line, "tag=$_" foreach @{$data->{tags}};
266 push @line, "$field=".$data->{$field};
269 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
271 close OUT || error("save $newfile: $!", $cleanup);
272 rename($newfile, "$config{wikistatedir}/aggregate") ||
273 error("rename $newfile: $!", $cleanup);
276 sub garbage_collect () { #{{{
277 foreach my $name (keys %feeds) {
278 # remove any feeds that were not seen while building the pages
279 # that used to contain them
280 if ($feeds{$name}->{unseen}) {
281 delete $feeds{$name};
285 foreach my $guid (values %guids) {
286 # any guid whose feed is gone should be removed
287 if (! exists $feeds{$guid->{feed}}) {
288 unlink pagefile($guid->{page})
289 if exists $guid->{page};
290 delete $guids{$guid->{guid}};
292 # handle expired guids
293 elsif ($guid->{expired} && exists $guid->{page}) {
294 unlink pagefile($guid->{page});
295 delete $guid->{page};
301 sub mergestate () { #{{{
302 # Load the current state in from disk, and merge into it
303 # values from the state in memory that might have changed
304 # during aggregation.
310 # All that can change in feed state during aggregation is a few
312 foreach my $name (keys %myfeeds) {
313 if (exists $feeds{$name}) {
314 foreach my $field (qw{message lastupdate numposts
316 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
321 # New guids can be created during aggregation.
322 # It's also possible that guids were removed from the on-disk state
323 # while the aggregation was in process. That would only happen if
324 # their feed was also removed, so any removed guids added back here
325 # will be garbage collected later.
326 foreach my $guid (keys %myguids) {
327 if (! exists $guids{$guid}) {
328 $guids{$guid}=$myguids{$guid};
333 sub clearstate () { #{{{
340 foreach my $feed (values %feeds) {
341 next unless $feed->{expireage} || $feed->{expirecount};
344 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
345 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
347 if ($feed->{expireage}) {
348 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
349 if ($days_old > $feed->{expireage}) {
350 debug(sprintf(gettext("expiring %s (%s days old)"),
351 $item->{page}, int($days_old)));
355 elsif ($feed->{expirecount} &&
356 $count >= $feed->{expirecount}) {
357 debug(sprintf(gettext("expiring %s"), $item->{page}));
361 if (! $seen{$item->{page}}) {
362 $seen{$item->{page}}=1;
370 sub needsaggregate () { #{{{
371 return values %feeds if $config{rebuild};
372 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
375 sub aggregate (@) { #{{{
376 eval q{use XML::Feed};
378 eval q{use URI::Fetch};
381 foreach my $feed (@_) {
382 $feed->{lastupdate}=time;
384 $feed->{message}=sprintf(gettext("processed ok at %s"),
385 displaytime($feed->{lastupdate}));
388 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
390 if (! length $feed->{feedurl}) {
391 my @urls=XML::Feed->find_feeds($feed->{url});
393 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
395 debug($feed->{message});
398 $feed->{feedurl}=pop @urls;
400 my $res=URI::Fetch->fetch($feed->{feedurl});
402 $feed->{message}=URI::Fetch->errstr;
404 debug($feed->{message});
407 if ($res->status == URI::Fetch::URI_GONE()) {
408 $feed->{message}=gettext("feed not found");
410 debug($feed->{message});
413 my $content=$res->content;
414 my $f=eval{XML::Feed->parse(\$content)};
416 # One common cause of XML::Feed crashing is a feed
417 # that contains invalid UTF-8 sequences. Convert
418 # feed to ascii to try to work around.
419 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
420 $content=Encode::decode_utf8($content, 0);
421 $f=eval{XML::Feed->parse(\$content)};
424 # Another possibility is badly escaped entities.
425 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
426 $content=~s/\&(?!amp)(\w+);/&$1;/g;
427 $content=Encode::decode_utf8($content, 0);
428 $f=eval{XML::Feed->parse(\$content)};
431 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
433 debug($feed->{message});
437 $feed->{message}=XML::Feed->errstr;
439 debug($feed->{message});
443 foreach my $entry ($f->entries) {
446 copyright => $f->copyright,
447 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
448 link => $entry->link,
449 content => defined $entry->content->body ? $entry->content->body : "",
450 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
451 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
457 sub add_page (@) { #{{{
460 my $feed=$params{feed};
463 if (exists $guids{$params{guid}}) {
464 # updating an existing post
465 $guid=$guids{$params{guid}};
466 return if $guid->{expired};
470 $guid->{guid}=$params{guid};
471 $guids{$params{guid}}=$guid;
472 $mtime=$params{ctime};
476 # assign it an unused page
477 my $page=IkiWiki::titlepage($params{title});
478 # escape slashes and periods in title so it doesn't specify
479 # directory name or trigger ".." disallowing code.
480 $page=~s!([/.])!"__".ord($1)."__"!eg;
481 $page=$feed->{dir}."/".$page;
482 ($page)=$page=~/$config{wiki_file_regexp}/;
483 if (! defined $page || ! length $page) {
484 $page=$feed->{dir}."/item";
487 while (exists $IkiWiki::pagecase{lc $page.$c} ||
488 -e pagefile($page.$c)) {
492 # Make sure that the file name isn't too long.
493 # NB: This doesn't check for path length limits.
494 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
495 if (defined $max && length(htmlfn($page)) >= $max) {
497 $page=$feed->{dir}."/item";
498 while (exists $IkiWiki::pagecase{lc $page.$c} ||
499 -e pagefile($page.$c)) {
505 debug(sprintf(gettext("creating new page %s"), $page));
507 $guid->{feed}=$feed->{name};
509 # To write or not to write? Need to avoid writing unchanged pages
510 # to avoid unneccessary rebuilding. The mtime from rss cannot be
511 # trusted; let's use a digest.
512 eval q{use Digest::MD5 'md5_hex'};
515 my $digest=md5_hex(Encode::encode_utf8($params{content}));
516 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
517 $guid->{md5}=$digest;
520 my $template=template($feed->{template}, blind_cache => 1);
521 $template->param(title => $params{title})
522 if defined $params{title} && length($params{title});
523 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
524 $template->param(name => $feed->{name});
525 $template->param(url => $feed->{url});
526 $template->param(copyright => $params{copyright})
527 if defined $params{copyright} && length $params{copyright};
528 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
529 if defined $params{link};
530 if (ref $feed->{tags}) {
531 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
533 writefile(htmlfn($guid->{page}), $config{srcdir},
536 # Set the mtime, this lets the build process get the right creation
537 # time on record for the new page.
538 utime $mtime, $mtime, pagefile($guid->{page})
539 if defined $mtime && $mtime <= time;
542 sub htmlescape ($) { #{{{
543 # escape accidental wikilinks and preprocessor stuff
545 $html=~s/(?<!\\)\[\[/\\\[\[/g;
549 sub urlabs ($$) { #{{{
553 URI->new_abs($url, $urlbase)->as_string;
556 sub htmlabs ($$) { #{{{
557 # Convert links in html from relative to absolute.
558 # Note that this is a heuristic, which is not specified by the rss
559 # spec and may not be right for all feeds. Also, see Debian
565 my $p = HTML::Parser->new(api_version => 3);
566 $p->handler(default => sub { $ret.=join("", @_) }, "text");
567 $p->handler(start => sub {
568 my ($tagname, $pos, $text) = @_;
569 if (ref $HTML::Tagset::linkElements{$tagname}) {
571 # use attribute sets from right to left
572 # to avoid invalidating the offsets
573 # when replacing the values
574 my($k_offset, $k_len, $v_offset, $v_len) =
576 my $attrname = lc(substr($text, $k_offset, $k_len));
577 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
578 next unless $v_offset; # 0 v_offset means no value
579 my $v = substr($text, $v_offset, $v_len);
580 $v =~ s/^([\'\"])(.*)\1$/$2/;
581 my $new_v=urlabs($v, $urlbase);
582 $new_v =~ s/\"/"/g; # since we quote with ""
583 substr($text, $v_offset, $v_len) = qq("$new_v");
587 }, "tagname, tokenpos, text");
594 sub pagefile ($) { #{{{
597 return "$config{srcdir}/".htmlfn($page);
600 sub htmlfn ($) { #{{{
601 return shift().".".($config{aggregateinternal} ? "_" : "").$config{htmlext};
606 sub lockaggregate () { #{{{
607 # Take an exclusive lock to prevent multiple concurrent aggregators.
608 # Returns true if the lock was aquired.
609 if (! -d $config{wikistatedir}) {
610 mkdir($config{wikistatedir});
612 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
613 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
614 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
615 close($aggregatelock) || error("failed closing aggregatelock: $!");
621 sub unlockaggregate () { #{{{
622 return close($aggregatelock) if $aggregatelock;