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 (grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
70 # Mark all feeds originating on this page as removable;
71 # preprocess will unmark those that still exist.
72 remove_feeds($feed->{sourcepage});
77 sub preprocess (@) { #{{{
80 foreach my $required (qw{name url}) {
81 if (! exists $params{$required}) {
82 return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
87 my $name=$params{name};
88 if (exists $feeds{$name}) {
95 $feed->{sourcepage}=$params{page};
96 $feed->{url}=$params{url};
97 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
99 ($dir)=$dir=~/$config{wiki_file_regexp}/;
101 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
102 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
103 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
104 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
105 delete $feed->{remove};
106 delete $feed->{expired};
107 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
108 $feed->{numposts}=0 unless defined $feed->{numposts};
109 $feed->{newposts}=0 unless defined $feed->{newposts};
110 $feed->{message}=gettext("new feed") unless defined $feed->{message};
111 $feed->{error}=0 unless defined $feed->{error};
117 push @{$feed->{tags}}, $value;
121 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
122 ($feed->{error} ? "<em>" : "").$feed->{message}.
123 ($feed->{error} ? "</em>" : "").
124 " (".$feed->{numposts}." ".gettext("posts").
125 ($feed->{newposts} ? "; ".$feed->{newposts}.
126 " ".gettext("new") : "").
130 sub delete (@) { #{{{
133 # Remove feed data for removed pages.
134 foreach my $file (@files) {
135 my $page=pagename($file);
141 sub loadstate () { #{{{
142 return if $state_loaded;
144 if (-e "$config{wikistatedir}/aggregate") {
145 open(IN, "$config{wikistatedir}/aggregate") ||
146 die "$config{wikistatedir}/aggregate: $!";
148 $_=IkiWiki::possibly_foolish_untaint($_);
151 foreach my $i (split(/ /, $_)) {
152 my ($field, $val)=split(/=/, $i, 2);
153 if ($field eq "name" || $field eq "feed" ||
154 $field eq "guid" || $field eq "message") {
155 $data->{$field}=decode_entities($val, " \t\n");
157 elsif ($field eq "tag") {
158 push @{$data->{tags}}, $val;
161 $data->{$field}=$val;
165 if (exists $data->{name}) {
166 $feeds{$data->{name}}=$data;
168 elsif (exists $data->{guid}) {
169 $guids{$data->{guid}}=$data;
177 sub savestate () { #{{{
178 return unless $state_loaded;
179 eval q{use HTML::Entities};
181 my $newfile="$config{wikistatedir}/aggregate.new";
182 my $cleanup = sub { unlink($newfile) };
183 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
184 foreach my $data (values %feeds, values %guids) {
185 if ($data->{remove}) {
187 foreach my $guid (values %guids) {
188 if ($guid->{feed} eq $data->{name}) {
194 unlink pagefile($data->{page})
195 if exists $data->{page};
199 elsif ($data->{expired} && exists $data->{page}) {
200 unlink pagefile($data->{page});
201 delete $data->{page};
206 foreach my $field (keys %$data) {
207 if ($field eq "name" || $field eq "feed" ||
208 $field eq "guid" || $field eq "message") {
209 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
211 elsif ($field eq "tags") {
212 push @line, "tag=$_" foreach @{$data->{tags}};
215 push @line, "$field=".$data->{$field};
218 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
220 close OUT || error("save $newfile: $!", $cleanup);
221 rename($newfile, "$config{wikistatedir}/aggregate") ||
222 error("rename $newfile: $!", $cleanup);
226 foreach my $feed (values %feeds) {
227 next unless $feed->{expireage} || $feed->{expirecount};
230 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
231 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
233 if ($feed->{expireage}) {
234 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
235 if ($days_old > $feed->{expireage}) {
236 debug(sprintf(gettext("expiring %s (%s days old)"),
237 $item->{page}, int($days_old)));
241 elsif ($feed->{expirecount} &&
242 $count >= $feed->{expirecount}) {
243 debug(sprintf(gettext("expiring %s"), $item->{page}));
247 if (! $seen{$item->{page}}) {
248 $seen{$item->{page}}=1;
256 sub aggregate () { #{{{
257 eval q{use XML::Feed};
259 eval q{use URI::Fetch};
261 eval q{use HTML::Entities};
264 foreach my $feed (values %feeds) {
265 next unless $config{rebuild} ||
266 time - $feed->{lastupdate} >= $feed->{updateinterval};
267 $feed->{lastupdate}=time;
269 $feed->{message}=sprintf(gettext("processed ok at %s"),
270 displaytime($feed->{lastupdate}));
272 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
274 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
276 if (! length $feed->{feedurl}) {
277 my @urls=XML::Feed->find_feeds($feed->{url});
279 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
281 debug($feed->{message});
284 $feed->{feedurl}=pop @urls;
286 my $res=URI::Fetch->fetch($feed->{feedurl});
288 $feed->{message}=URI::Fetch->errstr;
290 debug($feed->{message});
293 if ($res->status == URI::Fetch::URI_GONE()) {
294 $feed->{message}=gettext("feed not found");
296 debug($feed->{message});
299 my $content=$res->content;
300 my $f=eval{XML::Feed->parse(\$content)};
302 # One common cause of XML::Feed crashing is a feed
303 # that contains invalid UTF-8 sequences. Convert
304 # feed to ascii to try to work around.
305 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
306 $content=Encode::decode_utf8($content);
307 $f=eval{XML::Feed->parse(\$content)};
310 # Another possibility is badly escaped entities.
311 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
312 $content=~s/\&(?!amp)(\w+);/&$1;/g;
313 $content=Encode::decode_utf8($content);
314 $f=eval{XML::Feed->parse(\$content)};
317 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
319 debug($feed->{message});
323 $feed->{message}=XML::Feed->errstr;
325 debug($feed->{message});
329 foreach my $entry ($f->entries) {
332 copyright => $f->copyright,
333 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
334 link => $entry->link,
335 content => defined $entry->content->body ? $entry->content->body : "",
336 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
337 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
343 sub add_page (@) { #{{{
346 my $feed=$params{feed};
349 if (exists $guids{$params{guid}}) {
350 # updating an existing post
351 $guid=$guids{$params{guid}};
352 return if $guid->{expired};
356 $guid->{guid}=$params{guid};
357 $guids{$params{guid}}=$guid;
358 $mtime=$params{ctime};
362 # assign it an unused page
363 my $page=IkiWiki::titlepage($params{title});
364 # escape slashes and periods in title so it doesn't specify
365 # directory name or trigger ".." disallowing code.
366 $page=~s!([/.])!"__".ord($1)."__"!eg;
367 $page=$feed->{dir}."/".$page;
368 ($page)=$page=~/$config{wiki_file_regexp}/;
369 if (! defined $page || ! length $page) {
370 $page=$feed->{dir}."/item";
373 while (exists $IkiWiki::pagecase{lc $page.$c} ||
374 -e pagefile($page.$c)) {
378 # Make sure that the file name isn't too long.
379 # NB: This doesn't check for path length limits.
380 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
381 if (defined $max && length(htmlfn($page)) >= $max) {
383 $page=$feed->{dir}."/item";
384 while (exists $IkiWiki::pagecase{lc $page.$c} ||
385 -e pagefile($page.$c)) {
391 debug(sprintf(gettext("creating new page %s"), $page));
393 $guid->{feed}=$feed->{name};
395 # To write or not to write? Need to avoid writing unchanged pages
396 # to avoid unneccessary rebuilding. The mtime from rss cannot be
397 # trusted; let's use a digest.
398 eval q{use Digest::MD5 'md5_hex'};
401 my $digest=md5_hex(Encode::encode_utf8($params{content}));
402 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
403 $guid->{md5}=$digest;
406 my $template=template("aggregatepost.tmpl", blind_cache => 1);
407 $template->param(title => $params{title})
408 if defined $params{title} && length($params{title});
409 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
410 $template->param(name => $feed->{name});
411 $template->param(url => $feed->{url});
412 $template->param(copyright => $params{copyright})
413 if defined $params{copyright} && length $params{copyright};
414 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
415 if defined $params{link};
416 if (ref $feed->{tags}) {
417 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
419 writefile(htmlfn($guid->{page}), $config{srcdir},
422 # Set the mtime, this lets the build process get the right creation
423 # time on record for the new page.
424 utime $mtime, $mtime, pagefile($guid->{page})
425 if defined $mtime && $mtime <= time;
428 sub htmlescape ($) { #{{{
429 # escape accidental wikilinks and preprocessor stuff
431 $html=~s/(?<!\\)\[\[/\\\[\[/g;
435 sub urlabs ($$) { #{{{
439 URI->new_abs($url, $urlbase)->as_string;
442 sub htmlabs ($$) { #{{{
443 # Convert links in html from relative to absolute.
444 # Note that this is a heuristic, which is not specified by the rss
445 # spec and may not be right for all feeds. Also, see Debian
451 my $p = HTML::Parser->new(api_version => 3);
452 $p->handler(default => sub { $ret.=join("", @_) }, "text");
453 $p->handler(start => sub {
454 my ($tagname, $pos, $text) = @_;
455 if (ref $HTML::Tagset::linkElements{$tagname}) {
457 # use attribute sets from right to left
458 # to avoid invalidating the offsets
459 # when replacing the values
460 my($k_offset, $k_len, $v_offset, $v_len) =
462 my $attrname = lc(substr($text, $k_offset, $k_len));
463 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
464 next unless $v_offset; # 0 v_offset means no value
465 my $v = substr($text, $v_offset, $v_len);
466 $v =~ s/^([\'\"])(.*)\1$/$2/;
467 my $new_v=urlabs($v, $urlbase);
468 $new_v =~ s/\"/"/g; # since we quote with ""
469 substr($text, $v_offset, $v_len) = qq("$new_v");
473 }, "tagname, tokenpos, text");
480 sub remove_feeds () { #{{{
484 foreach my $id (keys %feeds) {
485 if ($feeds{$id}->{sourcepage} eq $page) {
486 $feeds{$id}->{remove}=1;
492 sub pagefile ($) { #{{{
495 return "$config{srcdir}/".htmlfn($page);
498 sub htmlfn ($) { #{{{
499 return shift().".".$config{htmlext};