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 if (! IkiWiki::lockwiki(0)) {
37 debug("wiki is locked by another process, not aggregating");
48 IkiWiki::unlockwiki();
52 sub needsbuild (@) { #{{{
55 loadstate(); # if not already loaded
57 foreach my $feed (values %feeds) {
58 if (exists $pagesources{$feed->{sourcepage}} &&
59 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
60 # Mark all feeds originating on this page as removable;
61 # preprocess will unmark those that still exist.
62 remove_feeds($feed->{sourcepage});
67 sub preprocess (@) { #{{{
70 foreach my $required (qw{name url}) {
71 if (! exists $params{$required}) {
72 return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
77 my $name=$params{name};
78 if (exists $feeds{$name}) {
85 $feed->{sourcepage}=$params{page};
86 $feed->{url}=$params{url};
87 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
89 ($dir)=$dir=~/$config{wiki_file_regexp}/;
91 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
92 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
93 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
94 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
95 delete $feed->{remove};
96 delete $feed->{expired};
97 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
98 $feed->{numposts}=0 unless defined $feed->{numposts};
99 $feed->{newposts}=0 unless defined $feed->{newposts};
100 $feed->{message}=gettext("new feed") unless defined $feed->{message};
101 $feed->{error}=0 unless defined $feed->{error};
107 push @{$feed->{tags}}, $value;
111 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
112 ($feed->{error} ? "<em>" : "").$feed->{message}.
113 ($feed->{error} ? "</em>" : "").
114 " (".$feed->{numposts}." ".gettext("posts").
115 ($feed->{newposts} ? "; ".$feed->{newposts}.
116 " ".gettext("new") : "").
120 sub delete (@) { #{{{
123 # Remove feed data for removed pages.
124 foreach my $file (@files) {
125 my $page=pagename($file);
131 sub loadstate () { #{{{
132 return if $state_loaded;
134 if (-e "$config{wikistatedir}/aggregate") {
135 open(IN, "<", "$config{wikistatedir}/aggregate") ||
136 die "$config{wikistatedir}/aggregate: $!";
138 $_=IkiWiki::possibly_foolish_untaint($_);
141 foreach my $i (split(/ /, $_)) {
142 my ($field, $val)=split(/=/, $i, 2);
143 if ($field eq "name" || $field eq "feed" ||
144 $field eq "guid" || $field eq "message") {
145 $data->{$field}=decode_entities($val, " \t\n");
147 elsif ($field eq "tag") {
148 push @{$data->{tags}}, $val;
151 $data->{$field}=$val;
155 if (exists $data->{name}) {
156 $feeds{$data->{name}}=$data;
158 elsif (exists $data->{guid}) {
159 $guids{$data->{guid}}=$data;
167 sub savestate () { #{{{
168 return unless $state_loaded;
169 eval q{use HTML::Entities};
171 my $newfile="$config{wikistatedir}/aggregate.new";
172 my $cleanup = sub { unlink($newfile) };
173 open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
174 foreach my $data (values %feeds, values %guids) {
175 if ($data->{remove}) {
177 foreach my $guid (values %guids) {
178 if ($guid->{feed} eq $data->{name}) {
184 unlink pagefile($data->{page})
185 if exists $data->{page};
189 elsif ($data->{expired} && exists $data->{page}) {
190 unlink pagefile($data->{page});
191 delete $data->{page};
196 foreach my $field (keys %$data) {
197 if ($field eq "name" || $field eq "feed" ||
198 $field eq "guid" || $field eq "message") {
199 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
201 elsif ($field eq "tags") {
202 push @line, "tag=$_" foreach @{$data->{tags}};
205 push @line, "$field=".$data->{$field};
208 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
210 close OUT || error("save $newfile: $!", $cleanup);
211 rename($newfile, "$config{wikistatedir}/aggregate") ||
212 error("rename $newfile: $!", $cleanup);
215 sub clearstate () { #{{{
222 foreach my $feed (values %feeds) {
223 next unless $feed->{expireage} || $feed->{expirecount};
226 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
227 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
229 if ($feed->{expireage}) {
230 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
231 if ($days_old > $feed->{expireage}) {
232 debug(sprintf(gettext("expiring %s (%s days old)"),
233 $item->{page}, int($days_old)));
237 elsif ($feed->{expirecount} &&
238 $count >= $feed->{expirecount}) {
239 debug(sprintf(gettext("expiring %s"), $item->{page}));
243 if (! $seen{$item->{page}}) {
244 $seen{$item->{page}}=1;
252 sub aggregate () { #{{{
253 eval q{use XML::Feed};
255 eval q{use URI::Fetch};
257 eval q{use HTML::Entities};
260 foreach my $feed (values %feeds) {
261 next unless $config{rebuild} ||
262 time - $feed->{lastupdate} >= $feed->{updateinterval};
263 $feed->{lastupdate}=time;
265 $feed->{message}=sprintf(gettext("processed ok at %s"),
266 displaytime($feed->{lastupdate}));
268 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
270 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
272 if (! length $feed->{feedurl}) {
273 my @urls=XML::Feed->find_feeds($feed->{url});
275 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
277 debug($feed->{message});
280 $feed->{feedurl}=pop @urls;
282 my $res=URI::Fetch->fetch($feed->{feedurl});
284 $feed->{message}=URI::Fetch->errstr;
286 debug($feed->{message});
289 if ($res->status == URI::Fetch::URI_GONE()) {
290 $feed->{message}=gettext("feed not found");
292 debug($feed->{message});
295 my $content=$res->content;
296 my $f=eval{XML::Feed->parse(\$content)};
298 # One common cause of XML::Feed crashing is a feed
299 # that contains invalid UTF-8 sequences. Convert
300 # feed to ascii to try to work around.
301 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
302 $content=Encode::decode_utf8($content);
303 $f=eval{XML::Feed->parse(\$content)};
306 # Another possibility is badly escaped entities.
307 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
308 $content=~s/\&(?!amp)(\w+);/&$1;/g;
309 $content=Encode::decode_utf8($content);
310 $f=eval{XML::Feed->parse(\$content)};
313 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
315 debug($feed->{message});
319 $feed->{message}=XML::Feed->errstr;
321 debug($feed->{message});
325 foreach my $entry ($f->entries) {
328 copyright => $f->copyright,
329 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
330 link => $entry->link,
331 content => defined $entry->content->body ? $entry->content->body : "",
332 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
333 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
339 sub add_page (@) { #{{{
342 my $feed=$params{feed};
345 if (exists $guids{$params{guid}}) {
346 # updating an existing post
347 $guid=$guids{$params{guid}};
348 return if $guid->{expired};
352 $guid->{guid}=$params{guid};
353 $guids{$params{guid}}=$guid;
354 $mtime=$params{ctime};
358 # assign it an unused page
359 my $page=IkiWiki::titlepage($params{title});
360 # escape slashes and periods in title so it doesn't specify
361 # directory name or trigger ".." disallowing code.
362 $page=~s!([/.])!"__".ord($1)."__"!eg;
363 $page=$feed->{dir}."/".$page;
364 ($page)=$page=~/$config{wiki_file_regexp}/;
365 if (! defined $page || ! length $page) {
366 $page=$feed->{dir}."/item";
369 while (exists $IkiWiki::pagecase{lc $page.$c} ||
370 -e pagefile($page.$c)) {
374 # Make sure that the file name isn't too long.
375 # NB: This doesn't check for path length limits.
376 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
377 if (defined $max && length(htmlfn($page)) >= $max) {
379 $page=$feed->{dir}."/item";
380 while (exists $IkiWiki::pagecase{lc $page.$c} ||
381 -e pagefile($page.$c)) {
387 debug(sprintf(gettext("creating new page %s"), $page));
389 $guid->{feed}=$feed->{name};
391 # To write or not to write? Need to avoid writing unchanged pages
392 # to avoid unneccessary rebuilding. The mtime from rss cannot be
393 # trusted; let's use a digest.
394 eval q{use Digest::MD5 'md5_hex'};
397 my $digest=md5_hex(Encode::encode_utf8($params{content}));
398 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
399 $guid->{md5}=$digest;
402 my $template=template("aggregatepost.tmpl", blind_cache => 1);
403 $template->param(title => $params{title})
404 if defined $params{title} && length($params{title});
405 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
406 $template->param(name => $feed->{name});
407 $template->param(url => $feed->{url});
408 $template->param(copyright => $params{copyright})
409 if defined $params{copyright} && length $params{copyright};
410 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
411 if defined $params{link};
412 if (ref $feed->{tags}) {
413 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
415 writefile(htmlfn($guid->{page}), $config{srcdir},
418 # Set the mtime, this lets the build process get the right creation
419 # time on record for the new page.
420 utime $mtime, $mtime, pagefile($guid->{page})
421 if defined $mtime && $mtime <= time;
424 sub htmlescape ($) { #{{{
425 # escape accidental wikilinks and preprocessor stuff
427 $html=~s/(?<!\\)\[\[/\\\[\[/g;
431 sub urlabs ($$) { #{{{
435 URI->new_abs($url, $urlbase)->as_string;
438 sub htmlabs ($$) { #{{{
439 # Convert links in html from relative to absolute.
440 # Note that this is a heuristic, which is not specified by the rss
441 # spec and may not be right for all feeds. Also, see Debian
447 my $p = HTML::Parser->new(api_version => 3);
448 $p->handler(default => sub { $ret.=join("", @_) }, "text");
449 $p->handler(start => sub {
450 my ($tagname, $pos, $text) = @_;
451 if (ref $HTML::Tagset::linkElements{$tagname}) {
453 # use attribute sets from right to left
454 # to avoid invalidating the offsets
455 # when replacing the values
456 my($k_offset, $k_len, $v_offset, $v_len) =
458 my $attrname = lc(substr($text, $k_offset, $k_len));
459 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
460 next unless $v_offset; # 0 v_offset means no value
461 my $v = substr($text, $v_offset, $v_len);
462 $v =~ s/^([\'\"])(.*)\1$/$2/;
463 my $new_v=urlabs($v, $urlbase);
464 $new_v =~ s/\"/"/g; # since we quote with ""
465 substr($text, $v_offset, $v_len) = qq("$new_v");
469 }, "tagname, tokenpos, text");
476 sub remove_feeds () { #{{{
480 foreach my $id (keys %feeds) {
481 if ($feeds{$id}->{sourcepage} eq $page) {
482 $feeds{$id}->{remove}=1;
488 sub pagefile ($) { #{{{
491 return "$config{srcdir}/".htmlfn($page);
494 sub htmlfn ($) { #{{{
495 return shift().".".$config{htmlext};
500 sub lockaggregate () { #{{{
501 # Take an exclusive lock to prevent multiple concurrent aggregators.
502 # Returns true if the lock was aquired.
503 if (! -d $config{wikistatedir}) {
504 mkdir($config{wikistatedir});
506 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
507 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
508 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
509 close($aggregatelock) || error("failed closing aggregatelock: $!");
515 sub unlockaggregate () { #{{{
516 return close($aggregatelock) if $aggregatelock;