2 # Blog 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);
27 eval q{use Getopt::Long};
29 Getopt::Long::Configure('pass_through');
30 GetOptions("aggregate" => \$config{aggregate});
33 sub checkconfig () { #{{{
34 if ($config{aggregate} && ! ($config{post_commit} &&
35 IkiWiki::commit_hook_enabled())) {
36 # See if any feeds need aggregation.
38 my @feeds=needsaggregate();
40 if (! lockaggregate()) {
41 debug("an aggregation process is already running");
44 # force a later rebuild of source pages
45 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
48 # Fork a child process to handle the aggregation.
49 # The parent process will then handle building the
50 # result. This avoids messy code to clear state
51 # accumulated while aggregating.
52 defined(my $pid = fork) or error("Can't fork: $!");
56 # Aggregation happens without the main wiki lock
57 # being held. This allows editing pages etc while
58 # aggregation is running.
62 # Merge changes, since aggregation state may have
63 # changed on disk while the aggregation was happening.
72 error "aggregation failed with code $?";
80 sub needsbuild (@) { #{{{
85 foreach my $feed (values %feeds) {
86 if (exists $pagesources{$feed->{sourcepage}} &&
87 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
88 # Mark all feeds originating on this page as
89 # not yet seen; preprocess will unmark those that
91 markunseen($feed->{sourcepage});
96 sub preprocess (@) { #{{{
99 foreach my $required (qw{name url}) {
100 if (! exists $params{$required}) {
101 return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
106 my $name=$params{name};
107 if (exists $feeds{$name}) {
114 $feed->{sourcepage}=$params{page};
115 $feed->{url}=$params{url};
116 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
118 ($dir)=$dir=~/$config{wiki_file_regexp}/;
120 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
121 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
122 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
123 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
124 delete $feed->{unseen};
125 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
126 $feed->{numposts}=0 unless defined $feed->{numposts};
127 $feed->{newposts}=0 unless defined $feed->{newposts};
128 $feed->{message}=gettext("new feed") unless defined $feed->{message};
129 $feed->{error}=0 unless defined $feed->{error};
135 push @{$feed->{tags}}, $value;
139 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
140 ($feed->{error} ? "<em>" : "").$feed->{message}.
141 ($feed->{error} ? "</em>" : "").
142 " (".$feed->{numposts}." ".gettext("posts").
143 ($feed->{newposts} ? "; ".$feed->{newposts}.
144 " ".gettext("new") : "").
148 sub delete (@) { #{{{
151 # Remove feed data for removed pages.
152 foreach my $file (@files) {
153 my $page=pagename($file);
158 sub markunseen ($) { #{{{
161 foreach my $id (keys %feeds) {
162 if ($feeds{$id}->{sourcepage} eq $page) {
163 $feeds{$id}->{unseen}=1;
170 sub loadstate () { #{{{
171 return if $state_loaded;
173 if (-e "$config{wikistatedir}/aggregate") {
174 open(IN, "$config{wikistatedir}/aggregate") ||
175 die "$config{wikistatedir}/aggregate: $!";
177 $_=IkiWiki::possibly_foolish_untaint($_);
180 foreach my $i (split(/ /, $_)) {
181 my ($field, $val)=split(/=/, $i, 2);
182 if ($field eq "name" || $field eq "feed" ||
183 $field eq "guid" || $field eq "message") {
184 $data->{$field}=decode_entities($val, " \t\n");
186 elsif ($field eq "tag") {
187 push @{$data->{tags}}, $val;
190 $data->{$field}=$val;
194 if (exists $data->{name}) {
195 $feeds{$data->{name}}=$data;
197 elsif (exists $data->{guid}) {
198 $guids{$data->{guid}}=$data;
206 sub savestate () { #{{{
207 return unless $state_loaded;
209 eval q{use HTML::Entities};
211 my $newfile="$config{wikistatedir}/aggregate.new";
212 my $cleanup = sub { unlink($newfile) };
213 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
214 foreach my $data (values %feeds, values %guids) {
216 foreach my $field (keys %$data) {
217 if ($field eq "name" || $field eq "feed" ||
218 $field eq "guid" || $field eq "message") {
219 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
221 elsif ($field eq "tags") {
222 push @line, "tag=$_" foreach @{$data->{tags}};
225 push @line, "$field=".$data->{$field};
228 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
230 close OUT || error("save $newfile: $!", $cleanup);
231 rename($newfile, "$config{wikistatedir}/aggregate") ||
232 error("rename $newfile: $!", $cleanup);
235 sub garbage_collect () { #{{{
236 foreach my $name (keys %feeds) {
237 # remove any feeds that were not seen while building the pages
238 # that used to contain them
239 if ($feeds{$name}->{unseen}) {
240 delete $feeds{$name};
244 foreach my $guid (values %guids) {
245 # any guid whose feed is gone should be removed
246 if (! exists $feeds{$guid->{feed}}) {
247 unlink pagefile($guid->{page})
248 if exists $guid->{page};
249 delete $guids{$guid->{guid}};
251 # handle expired guids
252 elsif ($guid->{expired} && exists $guid->{page}) {
253 unlink pagefile($guid->{page});
254 delete $guid->{page};
260 sub mergestate () { #{{{
261 # Load the current state in from disk, and merge into it
262 # values from the state in memory that might have changed
263 # during aggregation.
269 # All that can change in feed state during aggregation is a few
271 foreach my $name (keys %myfeeds) {
272 if (exists $feeds{$name}) {
273 foreach my $field (qw{message lastupdate numposts
275 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
280 # New guids can be created during aggregation.
281 # It's also possible that guids were removed from the on-disk state
282 # while the aggregation was in process. That would only happen if
283 # their feed was also removed, so any removed guids added back here
284 # will be garbage collected later.
285 foreach my $guid (keys %myguids) {
286 if (! exists $guids{$guid}) {
287 $guids{$guid}=$myguids{$guid};
292 sub clearstate () { #{{{
299 foreach my $feed (values %feeds) {
300 next unless $feed->{expireage} || $feed->{expirecount};
303 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
304 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
306 if ($feed->{expireage}) {
307 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
308 if ($days_old > $feed->{expireage}) {
309 debug(sprintf(gettext("expiring %s (%s days old)"),
310 $item->{page}, int($days_old)));
314 elsif ($feed->{expirecount} &&
315 $count >= $feed->{expirecount}) {
316 debug(sprintf(gettext("expiring %s"), $item->{page}));
320 if (! $seen{$item->{page}}) {
321 $seen{$item->{page}}=1;
329 sub needsaggregate () { #{{{
330 return values %feeds if $config{rebuild};
331 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
334 sub aggregate (@) { #{{{
335 eval q{use XML::Feed};
337 eval q{use URI::Fetch};
339 eval q{use HTML::Entities};
342 foreach my $feed (@_) {
343 $feed->{lastupdate}=time;
345 $feed->{message}=sprintf(gettext("processed ok at %s"),
346 displaytime($feed->{lastupdate}));
349 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
351 if (! length $feed->{feedurl}) {
352 my @urls=XML::Feed->find_feeds($feed->{url});
354 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
356 debug($feed->{message});
359 $feed->{feedurl}=pop @urls;
361 my $res=URI::Fetch->fetch($feed->{feedurl});
363 $feed->{message}=URI::Fetch->errstr;
365 debug($feed->{message});
368 if ($res->status == URI::Fetch::URI_GONE()) {
369 $feed->{message}=gettext("feed not found");
371 debug($feed->{message});
374 my $content=$res->content;
375 my $f=eval{XML::Feed->parse(\$content)};
377 # One common cause of XML::Feed crashing is a feed
378 # that contains invalid UTF-8 sequences. Convert
379 # feed to ascii to try to work around.
380 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
381 $content=Encode::decode_utf8($content);
382 $f=eval{XML::Feed->parse(\$content)};
385 # Another possibility is badly escaped entities.
386 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
387 $content=~s/\&(?!amp)(\w+);/&$1;/g;
388 $content=Encode::decode_utf8($content);
389 $f=eval{XML::Feed->parse(\$content)};
392 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
394 debug($feed->{message});
398 $feed->{message}=XML::Feed->errstr;
400 debug($feed->{message});
404 foreach my $entry ($f->entries) {
407 copyright => $f->copyright,
408 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
409 link => $entry->link,
410 content => defined $entry->content->body ? $entry->content->body : "",
411 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
412 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
418 sub add_page (@) { #{{{
421 my $feed=$params{feed};
424 if (exists $guids{$params{guid}}) {
425 # updating an existing post
426 $guid=$guids{$params{guid}};
427 return if $guid->{expired};
431 $guid->{guid}=$params{guid};
432 $guids{$params{guid}}=$guid;
433 $mtime=$params{ctime};
437 # assign it an unused page
438 my $page=IkiWiki::titlepage($params{title});
439 # escape slashes and periods in title so it doesn't specify
440 # directory name or trigger ".." disallowing code.
441 $page=~s!([/.])!"__".ord($1)."__"!eg;
442 $page=$feed->{dir}."/".$page;
443 ($page)=$page=~/$config{wiki_file_regexp}/;
444 if (! defined $page || ! length $page) {
445 $page=$feed->{dir}."/item";
448 while (exists $IkiWiki::pagecase{lc $page.$c} ||
449 -e pagefile($page.$c)) {
453 # Make sure that the file name isn't too long.
454 # NB: This doesn't check for path length limits.
455 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
456 if (defined $max && length(htmlfn($page)) >= $max) {
458 $page=$feed->{dir}."/item";
459 while (exists $IkiWiki::pagecase{lc $page.$c} ||
460 -e pagefile($page.$c)) {
466 debug(sprintf(gettext("creating new page %s"), $page));
468 $guid->{feed}=$feed->{name};
470 # To write or not to write? Need to avoid writing unchanged pages
471 # to avoid unneccessary rebuilding. The mtime from rss cannot be
472 # trusted; let's use a digest.
473 eval q{use Digest::MD5 'md5_hex'};
476 my $digest=md5_hex(Encode::encode_utf8($params{content}));
477 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
478 $guid->{md5}=$digest;
481 my $template=template("aggregatepost.tmpl", blind_cache => 1);
482 $template->param(title => $params{title})
483 if defined $params{title} && length($params{title});
484 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
485 $template->param(name => $feed->{name});
486 $template->param(url => $feed->{url});
487 $template->param(copyright => $params{copyright})
488 if defined $params{copyright} && length $params{copyright};
489 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
490 if defined $params{link};
491 if (ref $feed->{tags}) {
492 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
494 writefile(htmlfn($guid->{page}), $config{srcdir},
497 # Set the mtime, this lets the build process get the right creation
498 # time on record for the new page.
499 utime $mtime, $mtime, pagefile($guid->{page})
500 if defined $mtime && $mtime <= time;
503 sub htmlescape ($) { #{{{
504 # escape accidental wikilinks and preprocessor stuff
506 $html=~s/(?<!\\)\[\[/\\\[\[/g;
510 sub urlabs ($$) { #{{{
514 URI->new_abs($url, $urlbase)->as_string;
517 sub htmlabs ($$) { #{{{
518 # Convert links in html from relative to absolute.
519 # Note that this is a heuristic, which is not specified by the rss
520 # spec and may not be right for all feeds. Also, see Debian
526 my $p = HTML::Parser->new(api_version => 3);
527 $p->handler(default => sub { $ret.=join("", @_) }, "text");
528 $p->handler(start => sub {
529 my ($tagname, $pos, $text) = @_;
530 if (ref $HTML::Tagset::linkElements{$tagname}) {
532 # use attribute sets from right to left
533 # to avoid invalidating the offsets
534 # when replacing the values
535 my($k_offset, $k_len, $v_offset, $v_len) =
537 my $attrname = lc(substr($text, $k_offset, $k_len));
538 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
539 next unless $v_offset; # 0 v_offset means no value
540 my $v = substr($text, $v_offset, $v_len);
541 $v =~ s/^([\'\"])(.*)\1$/$2/;
542 my $new_v=urlabs($v, $urlbase);
543 $new_v =~ s/\"/"/g; # since we quote with ""
544 substr($text, $v_offset, $v_len) = qq("$new_v");
548 }, "tagname, tokenpos, text");
555 sub pagefile ($) { #{{{
558 return "$config{srcdir}/".htmlfn($page);
561 sub htmlfn ($) { #{{{
562 return shift().".".$config{htmlext};
567 sub lockaggregate () { #{{{
568 # Take an exclusive lock to prevent multiple concurrent aggregators.
569 # Returns true if the lock was aquired.
570 if (! -d $config{wikistatedir}) {
571 mkdir($config{wikistatedir});
573 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
574 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
575 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
576 close($aggregatelock) || error("failed closing aggregatelock: $!");
582 sub unlockaggregate () { #{{{
583 return close($aggregatelock) if $aggregatelock;