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");
41 # Fork a child process to handle the aggregation.
42 # The parent process will then handle building the result.
43 # This avoids messy code to clear state accumulated while
45 defined(my $pid = fork) or error("Can't fork: $!");
56 error "aggregation failed with code $?";
59 IkiWiki::unlockwiki();
63 sub needsbuild (@) { #{{{
66 loadstate(); # if not already loaded
68 foreach my $feed (values %feeds) {
69 if (exists $pagesources{$page} &&
70 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
71 # Mark all feeds originating on this page as removable;
72 # preprocess will unmark those that still exist.
73 remove_feeds($feed->{sourcepage});
78 sub preprocess (@) { #{{{
81 foreach my $required (qw{name url}) {
82 if (! exists $params{$required}) {
83 return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
88 my $name=$params{name};
89 if (exists $feeds{$name}) {
96 $feed->{sourcepage}=$params{page};
97 $feed->{url}=$params{url};
98 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
100 ($dir)=$dir=~/$config{wiki_file_regexp}/;
102 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
103 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
104 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
105 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
106 delete $feed->{remove};
107 delete $feed->{expired};
108 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
109 $feed->{numposts}=0 unless defined $feed->{numposts};
110 $feed->{newposts}=0 unless defined $feed->{newposts};
111 $feed->{message}=gettext("new feed") unless defined $feed->{message};
112 $feed->{error}=0 unless defined $feed->{error};
118 push @{$feed->{tags}}, $value;
122 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
123 ($feed->{error} ? "<em>" : "").$feed->{message}.
124 ($feed->{error} ? "</em>" : "").
125 " (".$feed->{numposts}." ".gettext("posts").
126 ($feed->{newposts} ? "; ".$feed->{newposts}.
127 " ".gettext("new") : "").
131 sub delete (@) { #{{{
134 # Remove feed data for removed pages.
135 foreach my $file (@files) {
136 my $page=pagename($file);
142 sub loadstate () { #{{{
143 return if $state_loaded;
145 if (-e "$config{wikistatedir}/aggregate") {
146 open(IN, "$config{wikistatedir}/aggregate") ||
147 die "$config{wikistatedir}/aggregate: $!";
149 $_=IkiWiki::possibly_foolish_untaint($_);
152 foreach my $i (split(/ /, $_)) {
153 my ($field, $val)=split(/=/, $i, 2);
154 if ($field eq "name" || $field eq "feed" ||
155 $field eq "guid" || $field eq "message") {
156 $data->{$field}=decode_entities($val, " \t\n");
158 elsif ($field eq "tag") {
159 push @{$data->{tags}}, $val;
162 $data->{$field}=$val;
166 if (exists $data->{name}) {
167 $feeds{$data->{name}}=$data;
169 elsif (exists $data->{guid}) {
170 $guids{$data->{guid}}=$data;
178 sub savestate () { #{{{
179 return unless $state_loaded;
180 eval q{use HTML::Entities};
182 my $newfile="$config{wikistatedir}/aggregate.new";
183 my $cleanup = sub { unlink($newfile) };
184 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
185 foreach my $data (values %feeds, values %guids) {
186 if ($data->{remove}) {
188 foreach my $guid (values %guids) {
189 if ($guid->{feed} eq $data->{name}) {
195 unlink pagefile($data->{page})
196 if exists $data->{page};
200 elsif ($data->{expired} && exists $data->{page}) {
201 unlink pagefile($data->{page});
202 delete $data->{page};
207 foreach my $field (keys %$data) {
208 if ($field eq "name" || $field eq "feed" ||
209 $field eq "guid" || $field eq "message") {
210 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
212 elsif ($field eq "tags") {
213 push @line, "tag=$_" foreach @{$data->{tags}};
216 push @line, "$field=".$data->{$field};
219 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
221 close OUT || error("save $newfile: $!", $cleanup);
222 rename($newfile, "$config{wikistatedir}/aggregate") ||
223 error("rename $newfile: $!", $cleanup);
227 foreach my $feed (values %feeds) {
228 next unless $feed->{expireage} || $feed->{expirecount};
231 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
232 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
234 if ($feed->{expireage}) {
235 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
236 if ($days_old > $feed->{expireage}) {
237 debug(sprintf(gettext("expiring %s (%s days old)"),
238 $item->{page}, int($days_old)));
242 elsif ($feed->{expirecount} &&
243 $count >= $feed->{expirecount}) {
244 debug(sprintf(gettext("expiring %s"), $item->{page}));
248 if (! $seen{$item->{page}}) {
249 $seen{$item->{page}}=1;
257 sub aggregate () { #{{{
258 eval q{use XML::Feed};
260 eval q{use URI::Fetch};
262 eval q{use HTML::Entities};
265 foreach my $feed (values %feeds) {
266 next unless $config{rebuild} ||
267 time - $feed->{lastupdate} >= $feed->{updateinterval};
268 $feed->{lastupdate}=time;
270 $feed->{message}=sprintf(gettext("processed ok at %s"),
271 displaytime($feed->{lastupdate}));
273 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
275 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
277 if (! length $feed->{feedurl}) {
278 my @urls=XML::Feed->find_feeds($feed->{url});
280 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
282 debug($feed->{message});
285 $feed->{feedurl}=pop @urls;
287 my $res=URI::Fetch->fetch($feed->{feedurl});
289 $feed->{message}=URI::Fetch->errstr;
291 debug($feed->{message});
294 if ($res->status == URI::Fetch::URI_GONE()) {
295 $feed->{message}=gettext("feed not found");
297 debug($feed->{message});
300 my $content=$res->content;
301 my $f=eval{XML::Feed->parse(\$content)};
303 # One common cause of XML::Feed crashing is a feed
304 # that contains invalid UTF-8 sequences. Convert
305 # feed to ascii to try to work around.
306 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
307 $content=Encode::decode_utf8($content);
308 $f=eval{XML::Feed->parse(\$content)};
311 # Another possibility is badly escaped entities.
312 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
313 $content=~s/\&(?!amp)(\w+);/&$1;/g;
314 $content=Encode::decode_utf8($content);
315 $f=eval{XML::Feed->parse(\$content)};
318 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
320 debug($feed->{message});
324 $feed->{message}=XML::Feed->errstr;
326 debug($feed->{message});
330 foreach my $entry ($f->entries) {
333 copyright => $f->copyright,
334 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
335 link => $entry->link,
336 content => defined $entry->content->body ? $entry->content->body : "",
337 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
338 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
344 sub add_page (@) { #{{{
347 my $feed=$params{feed};
350 if (exists $guids{$params{guid}}) {
351 # updating an existing post
352 $guid=$guids{$params{guid}};
353 return if $guid->{expired};
357 $guid->{guid}=$params{guid};
358 $guids{$params{guid}}=$guid;
359 $mtime=$params{ctime};
363 # assign it an unused page
364 my $page=IkiWiki::titlepage($params{title});
365 # escape slashes and periods in title so it doesn't specify
366 # directory name or trigger ".." disallowing code.
367 $page=~s!([/.])!"__".ord($1)."__"!eg;
368 $page=$feed->{dir}."/".$page;
369 ($page)=$page=~/$config{wiki_file_regexp}/;
370 if (! defined $page || ! length $page) {
371 $page=$feed->{dir}."/item";
374 while (exists $IkiWiki::pagecase{lc $page.$c} ||
375 -e pagefile($page.$c)) {
379 # Make sure that the file name isn't too long.
380 # NB: This doesn't check for path length limits.
381 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
382 if (defined $max && length(htmlfn($page)) >= $max) {
384 $page=$feed->{dir}."/item";
385 while (exists $IkiWiki::pagecase{lc $page.$c} ||
386 -e pagefile($page.$c)) {
392 debug(sprintf(gettext("creating new page %s"), $page));
394 $guid->{feed}=$feed->{name};
396 # To write or not to write? Need to avoid writing unchanged pages
397 # to avoid unneccessary rebuilding. The mtime from rss cannot be
398 # trusted; let's use a digest.
399 eval q{use Digest::MD5 'md5_hex'};
402 my $digest=md5_hex(Encode::encode_utf8($params{content}));
403 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
404 $guid->{md5}=$digest;
407 my $template=template("aggregatepost.tmpl", blind_cache => 1);
408 $template->param(title => $params{title})
409 if defined $params{title} && length($params{title});
410 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
411 $template->param(name => $feed->{name});
412 $template->param(url => $feed->{url});
413 $template->param(copyright => $params{copyright})
414 if defined $params{copyright} && length $params{copyright};
415 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
416 if defined $params{link};
417 if (ref $feed->{tags}) {
418 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
420 writefile(htmlfn($guid->{page}), $config{srcdir},
423 # Set the mtime, this lets the build process get the right creation
424 # time on record for the new page.
425 utime $mtime, $mtime, pagefile($guid->{page})
426 if defined $mtime && $mtime <= time;
429 sub htmlescape ($) { #{{{
430 # escape accidental wikilinks and preprocessor stuff
432 $html=~s/(?<!\\)\[\[/\\\[\[/g;
436 sub urlabs ($$) { #{{{
440 URI->new_abs($url, $urlbase)->as_string;
443 sub htmlabs ($$) { #{{{
444 # Convert links in html from relative to absolute.
445 # Note that this is a heuristic, which is not specified by the rss
446 # spec and may not be right for all feeds. Also, see Debian
452 my $p = HTML::Parser->new(api_version => 3);
453 $p->handler(default => sub { $ret.=join("", @_) }, "text");
454 $p->handler(start => sub {
455 my ($tagname, $pos, $text) = @_;
456 if (ref $HTML::Tagset::linkElements{$tagname}) {
458 # use attribute sets from right to left
459 # to avoid invalidating the offsets
460 # when replacing the values
461 my($k_offset, $k_len, $v_offset, $v_len) =
463 my $attrname = lc(substr($text, $k_offset, $k_len));
464 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
465 next unless $v_offset; # 0 v_offset means no value
466 my $v = substr($text, $v_offset, $v_len);
467 $v =~ s/^([\'\"])(.*)\1$/$2/;
468 my $new_v=urlabs($v, $urlbase);
469 $new_v =~ s/\"/"/g; # since we quote with ""
470 substr($text, $v_offset, $v_len) = qq("$new_v");
474 }, "tagname, tokenpos, text");
481 sub remove_feeds () { #{{{
485 foreach my $id (keys %feeds) {
486 if ($feeds{$id}->{sourcepage} eq $page) {
487 $feeds{$id}->{remove}=1;
493 sub pagefile ($) { #{{{
496 return "$config{srcdir}/".htmlfn($page);
499 sub htmlfn ($) { #{{{
500 return shift().".".$config{htmlext};