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 my $newfile="$config{wikistatedir}/aggregate.new";
210 my $cleanup = sub { unlink($newfile) };
211 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
212 foreach my $data (values %feeds, values %guids) {
214 foreach my $field (keys %$data) {
215 if ($field eq "name" || $field eq "feed" ||
216 $field eq "guid" || $field eq "message") {
217 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
219 elsif ($field eq "tags") {
220 push @line, "tag=$_" foreach @{$data->{tags}};
223 push @line, "$field=".$data->{$field};
226 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
228 close OUT || error("save $newfile: $!", $cleanup);
229 rename($newfile, "$config{wikistatedir}/aggregate") ||
230 error("rename $newfile: $!", $cleanup);
233 sub garbage_collect () { #{{{
234 foreach my $name (keys %feeds) {
235 # remove any feeds that were not seen while building the pages
236 # that used to contain them
237 if ($feeds{$name}->{unseen}) {
238 delete $feeds{$name};
242 foreach my $guid (values %guids) {
243 # any guid whose feed is gone should be removed
244 if (! exists $feeds{$guid->{feed}}) {
245 unlink pagefile($guid->{page})
246 if exists $guid->{page};
247 delete $guids{$guid->{guid}};
249 # handle expired guids
250 elsif ($guid->{expired} && exists $guid->{page}) {
251 unlink pagefile($guid->{page});
252 delete $guid->{page};
258 sub mergestate () { #{{{
259 # Load the current state in from disk, and merge into it
260 # values from the state in memory that might have changed
261 # during aggregation.
267 # All that can change in feed state during aggregation is a few
269 foreach my $name (keys %myfeeds) {
270 if (exists $feeds{$name}) {
271 foreach my $field (qw{message lastupdate numposts
273 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
278 # New guids can be created during aggregation.
279 # It's also possible that guids were removed from the on-disk state
280 # while the aggregation was in process. That would only happen if
281 # their feed was also removed, so any removed guids added back here
282 # will be garbage collected later.
283 foreach my $guid (keys %myguids) {
284 if (! exists $guids{$guid}) {
285 $guids{$guid}=$myguids{$guid};
290 sub clearstate () { #{{{
297 foreach my $feed (values %feeds) {
298 next unless $feed->{expireage} || $feed->{expirecount};
301 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
302 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
304 if ($feed->{expireage}) {
305 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
306 if ($days_old > $feed->{expireage}) {
307 debug(sprintf(gettext("expiring %s (%s days old)"),
308 $item->{page}, int($days_old)));
312 elsif ($feed->{expirecount} &&
313 $count >= $feed->{expirecount}) {
314 debug(sprintf(gettext("expiring %s"), $item->{page}));
318 if (! $seen{$item->{page}}) {
319 $seen{$item->{page}}=1;
327 sub needsaggregate () { #{{{
328 return values %feeds if $config{rebuild};
329 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
332 sub aggregate (@) { #{{{
333 eval q{use XML::Feed};
335 eval q{use URI::Fetch};
338 foreach my $feed (@_) {
339 $feed->{lastupdate}=time;
341 $feed->{message}=sprintf(gettext("processed ok at %s"),
342 displaytime($feed->{lastupdate}));
345 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
347 if (! length $feed->{feedurl}) {
348 my @urls=XML::Feed->find_feeds($feed->{url});
350 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
352 debug($feed->{message});
355 $feed->{feedurl}=pop @urls;
357 my $res=URI::Fetch->fetch($feed->{feedurl});
359 $feed->{message}=URI::Fetch->errstr;
361 debug($feed->{message});
364 if ($res->status == URI::Fetch::URI_GONE()) {
365 $feed->{message}=gettext("feed not found");
367 debug($feed->{message});
370 my $content=$res->content;
371 my $f=eval{XML::Feed->parse(\$content)};
373 # One common cause of XML::Feed crashing is a feed
374 # that contains invalid UTF-8 sequences. Convert
375 # feed to ascii to try to work around.
376 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
377 $content=Encode::decode_utf8($content);
378 $f=eval{XML::Feed->parse(\$content)};
381 # Another possibility is badly escaped entities.
382 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
383 $content=~s/\&(?!amp)(\w+);/&$1;/g;
384 $content=Encode::decode_utf8($content);
385 $f=eval{XML::Feed->parse(\$content)};
388 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
390 debug($feed->{message});
394 $feed->{message}=XML::Feed->errstr;
396 debug($feed->{message});
400 foreach my $entry ($f->entries) {
403 copyright => $f->copyright,
404 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
405 link => $entry->link,
406 content => defined $entry->content->body ? $entry->content->body : "",
407 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
408 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
414 sub add_page (@) { #{{{
417 my $feed=$params{feed};
420 if (exists $guids{$params{guid}}) {
421 # updating an existing post
422 $guid=$guids{$params{guid}};
423 return if $guid->{expired};
427 $guid->{guid}=$params{guid};
428 $guids{$params{guid}}=$guid;
429 $mtime=$params{ctime};
433 # assign it an unused page
434 my $page=IkiWiki::titlepage($params{title});
435 # escape slashes and periods in title so it doesn't specify
436 # directory name or trigger ".." disallowing code.
437 $page=~s!([/.])!"__".ord($1)."__"!eg;
438 $page=$feed->{dir}."/".$page;
439 ($page)=$page=~/$config{wiki_file_regexp}/;
440 if (! defined $page || ! length $page) {
441 $page=$feed->{dir}."/item";
444 while (exists $IkiWiki::pagecase{lc $page.$c} ||
445 -e pagefile($page.$c)) {
449 # Make sure that the file name isn't too long.
450 # NB: This doesn't check for path length limits.
451 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
452 if (defined $max && length(htmlfn($page)) >= $max) {
454 $page=$feed->{dir}."/item";
455 while (exists $IkiWiki::pagecase{lc $page.$c} ||
456 -e pagefile($page.$c)) {
462 debug(sprintf(gettext("creating new page %s"), $page));
464 $guid->{feed}=$feed->{name};
466 # To write or not to write? Need to avoid writing unchanged pages
467 # to avoid unneccessary rebuilding. The mtime from rss cannot be
468 # trusted; let's use a digest.
469 eval q{use Digest::MD5 'md5_hex'};
472 my $digest=md5_hex(Encode::encode_utf8($params{content}));
473 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
474 $guid->{md5}=$digest;
477 my $template=template("aggregatepost.tmpl", blind_cache => 1);
478 $template->param(title => $params{title})
479 if defined $params{title} && length($params{title});
480 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
481 $template->param(name => $feed->{name});
482 $template->param(url => $feed->{url});
483 $template->param(copyright => $params{copyright})
484 if defined $params{copyright} && length $params{copyright};
485 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
486 if defined $params{link};
487 if (ref $feed->{tags}) {
488 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
490 writefile(htmlfn($guid->{page}), $config{srcdir},
493 # Set the mtime, this lets the build process get the right creation
494 # time on record for the new page.
495 utime $mtime, $mtime, pagefile($guid->{page})
496 if defined $mtime && $mtime <= time;
499 sub htmlescape ($) { #{{{
500 # escape accidental wikilinks and preprocessor stuff
502 $html=~s/(?<!\\)\[\[/\\\[\[/g;
506 sub urlabs ($$) { #{{{
510 URI->new_abs($url, $urlbase)->as_string;
513 sub htmlabs ($$) { #{{{
514 # Convert links in html from relative to absolute.
515 # Note that this is a heuristic, which is not specified by the rss
516 # spec and may not be right for all feeds. Also, see Debian
522 my $p = HTML::Parser->new(api_version => 3);
523 $p->handler(default => sub { $ret.=join("", @_) }, "text");
524 $p->handler(start => sub {
525 my ($tagname, $pos, $text) = @_;
526 if (ref $HTML::Tagset::linkElements{$tagname}) {
528 # use attribute sets from right to left
529 # to avoid invalidating the offsets
530 # when replacing the values
531 my($k_offset, $k_len, $v_offset, $v_len) =
533 my $attrname = lc(substr($text, $k_offset, $k_len));
534 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
535 next unless $v_offset; # 0 v_offset means no value
536 my $v = substr($text, $v_offset, $v_len);
537 $v =~ s/^([\'\"])(.*)\1$/$2/;
538 my $new_v=urlabs($v, $urlbase);
539 $new_v =~ s/\"/"/g; # since we quote with ""
540 substr($text, $v_offset, $v_len) = qq("$new_v");
544 }, "tagname, tokenpos, text");
551 sub pagefile ($) { #{{{
554 return "$config{srcdir}/".htmlfn($page);
557 sub htmlfn ($) { #{{{
558 return shift().".".$config{htmlext};
563 sub lockaggregate () { #{{{
564 # Take an exclusive lock to prevent multiple concurrent aggregators.
565 # Returns true if the lock was aquired.
566 if (! -d $config{wikistatedir}) {
567 mkdir($config{wikistatedir});
569 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
570 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
571 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
572 close($aggregatelock) || error("failed closing aggregatelock: $!");
578 sub unlockaggregate () { #{{{
579 return close($aggregatelock) if $aggregatelock;