* Fix aggregator to not warn when a feed contains no body content at all.
[ikiwiki.git] / IkiWiki / Plugin / aggregate.pm
1 #!/usr/bin/perl
2 # Blog aggregation plugin.
3 package IkiWiki::Plugin::aggregate;
4
5 use warnings;
6 use strict;
7 use IkiWiki;
8 use HTML::Entities;
9 use HTML::Parser;
10 use HTML::Tagset;
11 use URI;
12 use open qw{:utf8 :std};
13
14 my %feeds;
15 my %guids;
16
17 sub import { #{{{
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);
24 } # }}}
25
26 sub getopt () { #{{{
27         eval q{use Getopt::Long};
28         error($@) if $@;
29         Getopt::Long::Configure('pass_through');
30         GetOptions("aggregate" => \$config{aggregate});
31 } #}}}
32
33 sub checkconfig () { #{{{
34         my $nolock=($config{post_commit} && ! IkiWiki::commit_hook_enabled());
35         IkiWiki::lockwiki() unless $nolock;
36         loadstate();
37         if ($config{aggregate} && ! $nolock) {
38                 IkiWiki::loadindex();
39                 aggregate();
40                 expire();
41                 savestate();
42         }
43         IkiWiki::unlockwiki() unless $nolock;
44 } #}}}
45
46 sub filter (@) { #{{{
47         my %params=@_;
48         my $page=$params{page};
49
50         # Mark all feeds originating on this page as removable;
51         # preprocess will unmark those that still exist.
52         remove_feeds($page);
53
54         return $params{content};
55 } # }}}
56
57 sub preprocess (@) { #{{{
58         my %params=@_;
59
60         foreach my $required (qw{name url}) {
61                 if (! exists $params{$required}) {
62                         return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
63                 }
64         }
65
66         my $feed={};
67         my $name=$params{name};
68         if (exists $feeds{$name}) {
69                 $feed=$feeds{$name};
70         }
71         else {
72                 $feeds{$name}=$feed;
73         }
74         $feed->{name}=$name;
75         $feed->{sourcepage}=$params{page};
76         $feed->{url}=$params{url};
77         my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
78         $dir=~s/^\/+//;
79         ($dir)=$dir=~/$config{wiki_file_regexp}/;
80         $feed->{dir}=$dir;
81         $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
82         $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
83         $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
84         $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
85         delete $feed->{remove};
86         delete $feed->{expired};
87         $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
88         $feed->{numposts}=0 unless defined $feed->{numposts};
89         $feed->{newposts}=0 unless defined $feed->{newposts};
90         $feed->{message}=gettext("new feed") unless defined $feed->{message};
91         $feed->{error}=0 unless defined $feed->{error};
92         $feed->{tags}=[];
93         while (@_) {
94                 my $key=shift;
95                 my $value=shift;
96                 if ($key eq 'tag') {
97                         push @{$feed->{tags}}, $value;
98                 }
99         }
100
101         return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
102                ($feed->{error} ? "<em>" : "").$feed->{message}.
103                ($feed->{error} ? "</em>" : "").
104                " (".$feed->{numposts}." ".gettext("posts").
105                ($feed->{newposts} ? "; ".$feed->{newposts}.
106                                     " ".gettext("new") : "").
107                ")";
108 } # }}}
109
110 sub delete (@) { #{{{
111         my @files=@_;
112
113         # Remove feed data for removed pages.
114         foreach my $file (@files) {
115                 my $page=pagename($file);
116                 remove_feeds($page);
117         }
118 } #}}}
119
120 sub loadstate () { #{{{
121         if (-e "$config{wikistatedir}/aggregate") {
122                 open (IN, "$config{wikistatedir}/aggregate" ||
123                         die "$config{wikistatedir}/aggregate: $!");
124                 while (<IN>) {
125                         $_=IkiWiki::possibly_foolish_untaint($_);
126                         chomp;
127                         my $data={};
128                         foreach my $i (split(/ /, $_)) {
129                                 my ($field, $val)=split(/=/, $i, 2);
130                                 if ($field eq "name" || $field eq "feed" ||
131                                     $field eq "guid" || $field eq "message") {
132                                         $data->{$field}=decode_entities($val, " \t\n");
133                                 }
134                                 elsif ($field eq "tag") {
135                                         push @{$data->{tags}}, $val;
136                                 }
137                                 else {
138                                         $data->{$field}=$val;
139                                 }
140                         }
141                         
142                         if (exists $data->{name}) {
143                                 $feeds{$data->{name}}=$data;
144                         }
145                         elsif (exists $data->{guid}) {
146                                 $guids{$data->{guid}}=$data;
147                         }
148                 }
149
150                 close IN;
151         }
152 } #}}}
153
154 sub savestate () { #{{{
155         eval q{use HTML::Entities};
156         error($@) if $@;
157         my $newfile="$config{wikistatedir}/aggregate.new";
158         # TODO: This cleanup function could use improvement. Any newly
159         # aggregated files are left behind unrecorded, and should be deleted.
160         my $cleanup = sub { unlink($newfile) };
161         open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
162         foreach my $data (values %feeds, values %guids) {
163                 if ($data->{remove}) {
164                         if ($data->{name}) {
165                                 foreach my $guid (values %guids) {
166                                         if ($guid->{feed} eq $data->{name}) {
167                                                 $guid->{remove}=1;
168                                         }
169                                 }
170                         }
171                         else {
172                                 unlink pagefile($data->{page});
173                         }
174                         next;
175                 }
176                 elsif ($data->{expired} && exists $data->{page}) {
177                         unlink pagefile($data->{page});
178                         delete $data->{page};
179                         delete $data->{md5};
180                 }
181
182                 my @line;
183                 foreach my $field (keys %$data) {
184                         if ($field eq "name" || $field eq "feed" ||
185                             $field eq "guid" || $field eq "message") {
186                                 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
187                         }
188                         elsif ($field eq "tags") {
189                                 push @line, "tag=$_" foreach @{$data->{tags}};
190                         }
191                         else {
192                                 push @line, "$field=".$data->{$field};
193                         }
194                 }
195                 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
196         }
197         close OUT || error("save $newfile: $!", $cleanup);
198         rename($newfile, "$config{wikistatedir}/aggregate") ||
199                 error("rename $newfile: $!", $cleanup);
200 } #}}}
201
202 sub expire () { #{{{
203         foreach my $feed (values %feeds) {
204                 next unless $feed->{expireage} || $feed->{expirecount};
205                 my $count=0;
206                 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
207                                   grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
208                                   values %guids) {
209                         if ($feed->{expireage}) {
210                                 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
211                                 if ($days_old > $feed->{expireage}) {
212                                         debug(sprintf(gettext("expiring %s (%s days old)"),
213                                                 $item->{page}, $days_old));
214                                         $item->{expired}=1;
215                                 }
216                         }
217                         elsif ($feed->{expirecount} &&
218                                $count >= $feed->{expirecount}) {
219                                 debug(sprintf(gettext("expiring %s"), $item->{page}));
220                                 $item->{expired}=1;
221                         }
222                         else {
223                                 $count++;
224                         }
225                 }
226         }
227 } #}}}
228
229 sub aggregate () { #{{{
230         eval q{use XML::Feed};
231         error($@) if $@;
232         eval q{use URI::Fetch};
233         error($@) if $@;
234         eval q{use HTML::Entities};
235         error($@) if $@;
236
237         foreach my $feed (values %feeds) {
238                 next unless $config{rebuild} || 
239                         time - $feed->{lastupdate} >= $feed->{updateinterval};
240                 $feed->{lastupdate}=time;
241                 $feed->{newposts}=0;
242                 $feed->{message}=sprintf(gettext("processed ok at %s"),
243                         displaytime($feed->{lastupdate}));
244                 $feed->{error}=0;
245                 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
246
247                 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
248
249                 if (! length $feed->{feedurl}) {
250                         my @urls=XML::Feed->find_feeds($feed->{url});
251                         if (! @urls) {
252                                 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
253                                 $feed->{error}=1;
254                                 debug($feed->{message});
255                                 next;
256                         }
257                         $feed->{feedurl}=pop @urls;
258                 }
259                 my $res=URI::Fetch->fetch($feed->{feedurl});
260                 if (! $res) {
261                         $feed->{message}=URI::Fetch->errstr;
262                         $feed->{error}=1;
263                         debug($feed->{message});
264                         next;
265                 }
266                 if ($res->status == URI::Fetch::URI_GONE()) {
267                         $feed->{message}=gettext("feed not found");
268                         $feed->{error}=1;
269                         debug($feed->{message});
270                         next;
271                 }
272                 my $content=$res->content;
273                 my $f=eval{XML::Feed->parse(\$content)};
274                 if ($@) {
275                         # One common cause of XML::Feed crashing is a feed
276                         # that contains invalid UTF-8 sequences. Convert
277                         # feed to ascii to try to work around.
278                         $feed->{message}=sprintf(gettext("invalid UTF-8 stripped from feed"));
279                         $content=Encode::decode_utf8($content);
280                         $f=eval{XML::Feed->parse(\$content)};
281                 }
282                 if ($@) {
283                         $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
284                         $feed->{error}=1;
285                         debug($feed->{message});
286                         next;
287                 }
288                 if (! $f) {
289                         $feed->{message}=XML::Feed->errstr;
290                         $feed->{error}=1;
291                         debug($feed->{message});
292                         next;
293                 }
294
295                 foreach my $entry ($f->entries) {
296                         add_page(
297                                 feed => $feed,
298                                 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
299                                 link => $entry->link,
300                                 content => defined $entry->content->body ? $entry->content->body : "",
301                                 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
302                                 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
303                         );
304                 }
305         }
306 } #}}}
307
308 sub add_page (@) { #{{{
309         my %params=@_;
310         
311         my $feed=$params{feed};
312         my $guid={};
313         my $mtime;
314         if (exists $guids{$params{guid}}) {
315                 # updating an existing post
316                 $guid=$guids{$params{guid}};
317                 return if $guid->{expired};
318         }
319         else {
320                 # new post
321                 $guid->{guid}=$params{guid};
322                 $guids{$params{guid}}=$guid;
323                 $mtime=$params{ctime};
324                 $feed->{numposts}++;
325                 $feed->{newposts}++;
326
327                 # assign it an unused page
328                 my $page=IkiWiki::titlepage($params{title});
329                 # escape slashes and periods in title so it doesn't specify
330                 # directory name or trigger ".." disallowing code.
331                 $page=~s!([/.])!"__".ord($1)."__"!eg;
332                 $page=$feed->{dir}."/".$page;
333                 ($page)=$page=~/$config{wiki_file_regexp}/;
334                 if (! defined $page || ! length $page) {
335                         $page=$feed->{dir}."/item";
336                 }
337                 my $c="";
338                 while (exists $IkiWiki::pagecase{lc $page.$c} ||
339                        -e pagefile($page.$c)) {
340                         $c++
341                 }
342
343                 # Make sure that the file name isn't too long. 
344                 # NB: This doesn't check for path length limits.
345                 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
346                 if (defined $max && length(htmlfn($page)) >= $max) {
347                         $c="";
348                         $page=$feed->{dir}."/item";
349                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
350                                -e pagefile($page.$c)) {
351                                 $c++
352                         }
353                 }
354
355                 $guid->{page}=$page;
356                 debug(sprintf(gettext("creating new page %s"), $page));
357         }
358         $guid->{feed}=$feed->{name};
359         
360         # To write or not to write? Need to avoid writing unchanged pages
361         # to avoid unneccessary rebuilding. The mtime from rss cannot be
362         # trusted; let's use a digest.
363         eval q{use Digest::MD5 'md5_hex'};
364         error($@) if $@;
365         require Encode;
366         my $digest=md5_hex(Encode::encode_utf8($params{content}));
367         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
368         $guid->{md5}=$digest;
369
370         # Create the page.
371         my $template=template("aggregatepost.tmpl", blind_cache => 1);
372         $template->param(title => $params{title})
373                 if defined $params{title} && length($params{title});
374         $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
375         $template->param(name => $feed->{name});
376         $template->param(url => $feed->{url});
377         $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
378                 if defined $params{link};
379         if (ref $feed->{tags}) {
380                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
381         }
382         writefile(htmlfn($guid->{page}), $config{srcdir},
383                 $template->output);
384
385         # Set the mtime, this lets the build process get the right creation
386         # time on record for the new page.
387         utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
388 } #}}}
389
390 sub htmlescape ($) { #{{{
391         # escape accidental wikilinks and preprocessor stuff
392         my $html=shift;
393         $html=~s/(?<!\\)\[\[/\\\[\[/g;
394         return $html;
395 } #}}}
396
397 sub urlabs ($$) { #{{{
398         my $url=shift;
399         my $urlbase=shift;
400
401         URI->new_abs($url, $urlbase)->as_string;
402 } #}}}
403
404 sub htmlabs ($$) { #{{{
405         # Convert links in html from relative to absolute.
406         # Note that this is a heuristic, which is not specified by the rss
407         # spec and may not be right for all feeds. Also, see Debian
408         # bug #381359.
409         my $html=shift;
410         my $urlbase=shift;
411
412         my $ret="";
413         my $p = HTML::Parser->new(api_version => 3);
414         $p->handler(default => sub { $ret.=join("", @_) }, "text");
415         $p->handler(start => sub {
416                 my ($tagname, $pos, $text) = @_;
417                 if (ref $HTML::Tagset::linkElements{$tagname}) {
418                         while (4 <= @$pos) {
419                                 # use attribute sets from right to left
420                                 # to avoid invalidating the offsets
421                                 # when replacing the values
422                                 my($k_offset, $k_len, $v_offset, $v_len) =
423                                         splice(@$pos, -4);
424                                 my $attrname = lc(substr($text, $k_offset, $k_len));
425                                 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
426                                 next unless $v_offset; # 0 v_offset means no value
427                                 my $v = substr($text, $v_offset, $v_len);
428                                 $v =~ s/^([\'\"])(.*)\1$/$2/;
429                                 my $new_v=urlabs($v, $urlbase);
430                                 $new_v =~ s/\"/&quot;/g; # since we quote with ""
431                                 substr($text, $v_offset, $v_len) = qq("$new_v");
432                         }
433                 }
434                 $ret.=$text;
435         }, "tagname, tokenpos, text");
436         $p->parse($html);
437         $p->eof;
438
439         return $ret;
440 } #}}}
441
442 sub remove_feeds () { #{{{
443         my $page=shift;
444
445         my %removed;
446         foreach my $id (keys %feeds) {
447                 if ($feeds{$id}->{sourcepage} eq $page) {
448                         $feeds{$id}->{remove}=1;
449                         $removed{$id}=1;
450                 }
451         }
452 } #}}}
453
454 sub pagefile ($) { #{{{
455         my $page=shift;
456
457         return "$config{srcdir}/".htmlfn($page);
458 } #}}}
459
460 sub htmlfn ($) { #{{{
461         return shift().".html";
462 } #}}}
463
464 1