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 => "filter", id => "aggregate", call => \&filter);
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();
54 my $page=$params{page};
56 loadstate(); # if not already loaded
57 # Mark all feeds originating on this page as removable;
58 # preprocess will unmark those that still exist.
61 return $params{content};
64 sub preprocess (@) { #{{{
67 foreach my $required (qw{name url}) {
68 if (! exists $params{$required}) {
69 return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
74 my $name=$params{name};
75 if (exists $feeds{$name}) {
82 $feed->{sourcepage}=$params{page};
83 $feed->{url}=$params{url};
84 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
86 ($dir)=$dir=~/$config{wiki_file_regexp}/;
88 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
89 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
90 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
91 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
92 delete $feed->{remove};
93 delete $feed->{expired};
94 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
95 $feed->{numposts}=0 unless defined $feed->{numposts};
96 $feed->{newposts}=0 unless defined $feed->{newposts};
97 $feed->{message}=gettext("new feed") unless defined $feed->{message};
98 $feed->{error}=0 unless defined $feed->{error};
104 push @{$feed->{tags}}, $value;
108 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
109 ($feed->{error} ? "<em>" : "").$feed->{message}.
110 ($feed->{error} ? "</em>" : "").
111 " (".$feed->{numposts}." ".gettext("posts").
112 ($feed->{newposts} ? "; ".$feed->{newposts}.
113 " ".gettext("new") : "").
117 sub delete (@) { #{{{
120 # Remove feed data for removed pages.
121 foreach my $file (@files) {
122 my $page=pagename($file);
128 sub loadstate () { #{{{
129 return if $state_loaded;
130 if (-e "$config{wikistatedir}/aggregate") {
131 open(IN, "$config{wikistatedir}/aggregate") ||
132 die "$config{wikistatedir}/aggregate: $!";
134 $_=IkiWiki::possibly_foolish_untaint($_);
137 foreach my $i (split(/ /, $_)) {
138 my ($field, $val)=split(/=/, $i, 2);
139 if ($field eq "name" || $field eq "feed" ||
140 $field eq "guid" || $field eq "message") {
141 $data->{$field}=decode_entities($val, " \t\n");
143 elsif ($field eq "tag") {
144 push @{$data->{tags}}, $val;
147 $data->{$field}=$val;
151 if (exists $data->{name}) {
152 $feeds{$data->{name}}=$data;
154 elsif (exists $data->{guid}) {
155 $guids{$data->{guid}}=$data;
165 sub savestate () { #{{{
166 eval q{use HTML::Entities};
168 my $newfile="$config{wikistatedir}/aggregate.new";
169 # TODO: This cleanup function could use improvement. Any newly
170 # aggregated files are left behind unrecorded, and should be deleted.
171 my $cleanup = sub { unlink($newfile) };
172 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
173 foreach my $data (values %feeds, values %guids) {
174 if ($data->{remove}) {
176 foreach my $guid (values %guids) {
177 if ($guid->{feed} eq $data->{name}) {
183 unlink pagefile($data->{page});
187 elsif ($data->{expired} && exists $data->{page}) {
188 unlink pagefile($data->{page});
189 delete $data->{page};
194 foreach my $field (keys %$data) {
195 if ($field eq "name" || $field eq "feed" ||
196 $field eq "guid" || $field eq "message") {
197 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
199 elsif ($field eq "tags") {
200 push @line, "tag=$_" foreach @{$data->{tags}};
203 push @line, "$field=".$data->{$field};
206 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
208 close OUT || error("save $newfile: $!", $cleanup);
209 rename($newfile, "$config{wikistatedir}/aggregate") ||
210 error("rename $newfile: $!", $cleanup);
213 sub clearstate () { #{{{
220 foreach my $feed (values %feeds) {
221 next unless $feed->{expireage} || $feed->{expirecount};
224 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
225 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
227 if ($feed->{expireage}) {
228 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
229 if ($days_old > $feed->{expireage}) {
230 debug(sprintf(gettext("expiring %s (%s days old)"),
231 $item->{page}, $days_old));
235 elsif ($feed->{expirecount} &&
236 $count >= $feed->{expirecount}) {
237 debug(sprintf(gettext("expiring %s"), $item->{page}));
241 if (! $seen{$item->{page}}) {
242 $seen{$item->{page}}=1;
250 sub aggregate () { #{{{
251 eval q{use XML::Feed};
253 eval q{use URI::Fetch};
255 eval q{use HTML::Entities};
258 foreach my $feed (values %feeds) {
259 next unless $config{rebuild} ||
260 time - $feed->{lastupdate} >= $feed->{updateinterval};
261 $feed->{lastupdate}=time;
263 $feed->{message}=sprintf(gettext("processed ok at %s"),
264 displaytime($feed->{lastupdate}));
266 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
268 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
270 if (! length $feed->{feedurl}) {
271 my @urls=XML::Feed->find_feeds($feed->{url});
273 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
275 debug($feed->{message});
278 $feed->{feedurl}=pop @urls;
280 my $res=URI::Fetch->fetch($feed->{feedurl});
282 $feed->{message}=URI::Fetch->errstr;
284 debug($feed->{message});
287 if ($res->status == URI::Fetch::URI_GONE()) {
288 $feed->{message}=gettext("feed not found");
290 debug($feed->{message});
293 my $content=$res->content;
294 my $f=eval{XML::Feed->parse(\$content)};
296 # One common cause of XML::Feed crashing is a feed
297 # that contains invalid UTF-8 sequences. Convert
298 # feed to ascii to try to work around.
299 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
300 $content=Encode::decode_utf8($content);
301 $f=eval{XML::Feed->parse(\$content)};
304 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
306 debug($feed->{message});
310 $feed->{message}=XML::Feed->errstr;
312 debug($feed->{message});
316 foreach my $entry ($f->entries) {
319 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
320 link => $entry->link,
321 content => defined $entry->content->body ? $entry->content->body : "",
322 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
323 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
329 sub add_page (@) { #{{{
332 my $feed=$params{feed};
335 if (exists $guids{$params{guid}}) {
336 # updating an existing post
337 $guid=$guids{$params{guid}};
338 return if $guid->{expired};
342 $guid->{guid}=$params{guid};
343 $guids{$params{guid}}=$guid;
344 $mtime=$params{ctime};
348 # assign it an unused page
349 my $page=IkiWiki::titlepage($params{title});
350 # escape slashes and periods in title so it doesn't specify
351 # directory name or trigger ".." disallowing code.
352 $page=~s!([/.])!"__".ord($1)."__"!eg;
353 $page=$feed->{dir}."/".$page;
354 ($page)=$page=~/$config{wiki_file_regexp}/;
355 if (! defined $page || ! length $page) {
356 $page=$feed->{dir}."/item";
359 while (exists $IkiWiki::pagecase{lc $page.$c} ||
360 -e pagefile($page.$c)) {
364 # Make sure that the file name isn't too long.
365 # NB: This doesn't check for path length limits.
366 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
367 if (defined $max && length(htmlfn($page)) >= $max) {
369 $page=$feed->{dir}."/item";
370 while (exists $IkiWiki::pagecase{lc $page.$c} ||
371 -e pagefile($page.$c)) {
377 debug(sprintf(gettext("creating new page %s"), $page));
379 $guid->{feed}=$feed->{name};
381 # To write or not to write? Need to avoid writing unchanged pages
382 # to avoid unneccessary rebuilding. The mtime from rss cannot be
383 # trusted; let's use a digest.
384 eval q{use Digest::MD5 'md5_hex'};
387 my $digest=md5_hex(Encode::encode_utf8($params{content}));
388 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
389 $guid->{md5}=$digest;
392 my $template=template("aggregatepost.tmpl", blind_cache => 1);
393 $template->param(title => $params{title})
394 if defined $params{title} && length($params{title});
395 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
396 $template->param(name => $feed->{name});
397 $template->param(url => $feed->{url});
398 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
399 if defined $params{link};
400 if (ref $feed->{tags}) {
401 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
403 writefile(htmlfn($guid->{page}), $config{srcdir},
406 # Set the mtime, this lets the build process get the right creation
407 # time on record for the new page.
408 utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
411 sub htmlescape ($) { #{{{
412 # escape accidental wikilinks and preprocessor stuff
414 $html=~s/(?<!\\)\[\[/\\\[\[/g;
418 sub urlabs ($$) { #{{{
422 URI->new_abs($url, $urlbase)->as_string;
425 sub htmlabs ($$) { #{{{
426 # Convert links in html from relative to absolute.
427 # Note that this is a heuristic, which is not specified by the rss
428 # spec and may not be right for all feeds. Also, see Debian
434 my $p = HTML::Parser->new(api_version => 3);
435 $p->handler(default => sub { $ret.=join("", @_) }, "text");
436 $p->handler(start => sub {
437 my ($tagname, $pos, $text) = @_;
438 if (ref $HTML::Tagset::linkElements{$tagname}) {
440 # use attribute sets from right to left
441 # to avoid invalidating the offsets
442 # when replacing the values
443 my($k_offset, $k_len, $v_offset, $v_len) =
445 my $attrname = lc(substr($text, $k_offset, $k_len));
446 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
447 next unless $v_offset; # 0 v_offset means no value
448 my $v = substr($text, $v_offset, $v_len);
449 $v =~ s/^([\'\"])(.*)\1$/$2/;
450 my $new_v=urlabs($v, $urlbase);
451 $new_v =~ s/\"/"/g; # since we quote with ""
452 substr($text, $v_offset, $v_len) = qq("$new_v");
456 }, "tagname, tokenpos, text");
463 sub remove_feeds () { #{{{
467 foreach my $id (keys %feeds) {
468 if ($feeds{$id}->{sourcepage} eq $page) {
469 $feeds{$id}->{remove}=1;
475 sub pagefile ($) { #{{{
478 return "$config{srcdir}/".htmlfn($page);
481 sub htmlfn ($) { #{{{
482 return shift().".".$config{htmlext};