add missing test to avoid uninitialised value when a page with metadata is removed
[ikiwiki] / 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 2.00;
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 => "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);
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         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");
38                         exit 1;
39                 }
40                 
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
44                 # aggregating.
45                 defined(my $pid = fork) or error("Can't fork: $!");
46                 if (! $pid) {
47                         loadstate();
48                         IkiWiki::loadindex();
49                         aggregate();
50                         expire();
51                         savestate();
52                         exit 0;
53                 }
54                 waitpid($pid,0);
55                 if ($?) {
56                         error "aggregation failed with code $?";
57                 }
58                 
59                 IkiWiki::unlockwiki();
60         }
61 } #}}}
62
63 sub needsbuild (@) { #{{{
64         my $needsbuild=shift;
65         
66         loadstate(); # if not already loaded
67
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});
74                 }
75         }
76 } # }}}
77
78 sub preprocess (@) { #{{{
79         my %params=@_;
80
81         foreach my $required (qw{name url}) {
82                 if (! exists $params{$required}) {
83                         return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
84                 }
85         }
86
87         my $feed={};
88         my $name=$params{name};
89         if (exists $feeds{$name}) {
90                 $feed=$feeds{$name};
91         }
92         else {
93                 $feeds{$name}=$feed;
94         }
95         $feed->{name}=$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});
99         $dir=~s/^\/+//;
100         ($dir)=$dir=~/$config{wiki_file_regexp}/;
101         $feed->{dir}=$dir;
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};
113         $feed->{tags}=[];
114         while (@_) {
115                 my $key=shift;
116                 my $value=shift;
117                 if ($key eq 'tag') {
118                         push @{$feed->{tags}}, $value;
119                 }
120         }
121
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") : "").
128                ")";
129 } # }}}
130
131 sub delete (@) { #{{{
132         my @files=@_;
133
134         # Remove feed data for removed pages.
135         foreach my $file (@files) {
136                 my $page=pagename($file);
137                 remove_feeds($page);
138         }
139 } #}}}
140
141 my $state_loaded=0;
142 sub loadstate () { #{{{
143         return if $state_loaded;
144         $state_loaded=1;
145         if (-e "$config{wikistatedir}/aggregate") {
146                 open(IN, "$config{wikistatedir}/aggregate") ||
147                         die "$config{wikistatedir}/aggregate: $!";
148                 while (<IN>) {
149                         $_=IkiWiki::possibly_foolish_untaint($_);
150                         chomp;
151                         my $data={};
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");
157                                 }
158                                 elsif ($field eq "tag") {
159                                         push @{$data->{tags}}, $val;
160                                 }
161                                 else {
162                                         $data->{$field}=$val;
163                                 }
164                         }
165                         
166                         if (exists $data->{name}) {
167                                 $feeds{$data->{name}}=$data;
168                         }
169                         elsif (exists $data->{guid}) {
170                                 $guids{$data->{guid}}=$data;
171                         }
172                 }
173
174                 close IN;
175         }
176 } #}}}
177
178 sub savestate () { #{{{
179         return unless $state_loaded;
180         eval q{use HTML::Entities};
181         error($@) if $@;
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}) {
187                         if ($data->{name}) {
188                                 foreach my $guid (values %guids) {
189                                         if ($guid->{feed} eq $data->{name}) {
190                                                 $guid->{remove}=1;
191                                         }
192                                 }
193                         }
194                         else {
195                                 unlink pagefile($data->{page})
196                                         if exists $data->{page};
197                         }
198                         next;
199                 }
200                 elsif ($data->{expired} && exists $data->{page}) {
201                         unlink pagefile($data->{page});
202                         delete $data->{page};
203                         delete $data->{md5};
204                 }
205
206                 my @line;
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");
211                         }
212                         elsif ($field eq "tags") {
213                                 push @line, "tag=$_" foreach @{$data->{tags}};
214                         }
215                         else {
216                                 push @line, "$field=".$data->{$field};
217                         }
218                 }
219                 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
220         }
221         close OUT || error("save $newfile: $!", $cleanup);
222         rename($newfile, "$config{wikistatedir}/aggregate") ||
223                 error("rename $newfile: $!", $cleanup);
224 } #}}}
225
226 sub expire () { #{{{
227         foreach my $feed (values %feeds) {
228                 next unless $feed->{expireage} || $feed->{expirecount};
229                 my $count=0;
230                 my %seen;
231                 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
232                                   grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
233                                   values %guids) {
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)));
239                                         $item->{expired}=1;
240                                 }
241                         }
242                         elsif ($feed->{expirecount} &&
243                                $count >= $feed->{expirecount}) {
244                                 debug(sprintf(gettext("expiring %s"), $item->{page}));
245                                 $item->{expired}=1;
246                         }
247                         else {
248                                 if (! $seen{$item->{page}}) {
249                                         $seen{$item->{page}}=1;
250                                         $count++;
251                                 }
252                         }
253                 }
254         }
255 } #}}}
256
257 sub aggregate () { #{{{
258         eval q{use XML::Feed};
259         error($@) if $@;
260         eval q{use URI::Fetch};
261         error($@) if $@;
262         eval q{use HTML::Entities};
263         error($@) if $@;
264
265         foreach my $feed (values %feeds) {
266                 next unless $config{rebuild} || 
267                         time - $feed->{lastupdate} >= $feed->{updateinterval};
268                 $feed->{lastupdate}=time;
269                 $feed->{newposts}=0;
270                 $feed->{message}=sprintf(gettext("processed ok at %s"),
271                         displaytime($feed->{lastupdate}));
272                 $feed->{error}=0;
273                 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
274
275                 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
276
277                 if (! length $feed->{feedurl}) {
278                         my @urls=XML::Feed->find_feeds($feed->{url});
279                         if (! @urls) {
280                                 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
281                                 $feed->{error}=1;
282                                 debug($feed->{message});
283                                 next;
284                         }
285                         $feed->{feedurl}=pop @urls;
286                 }
287                 my $res=URI::Fetch->fetch($feed->{feedurl});
288                 if (! $res) {
289                         $feed->{message}=URI::Fetch->errstr;
290                         $feed->{error}=1;
291                         debug($feed->{message});
292                         next;
293                 }
294                 if ($res->status == URI::Fetch::URI_GONE()) {
295                         $feed->{message}=gettext("feed not found");
296                         $feed->{error}=1;
297                         debug($feed->{message});
298                         next;
299                 }
300                 my $content=$res->content;
301                 my $f=eval{XML::Feed->parse(\$content)};
302                 if ($@) {
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)};
309                 }
310                 if ($@) {
311                         # Another possibility is badly escaped entities.
312                         $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
313                         $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
314                         $content=Encode::decode_utf8($content);
315                         $f=eval{XML::Feed->parse(\$content)};
316                 }
317                 if ($@) {
318                         $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
319                         $feed->{error}=1;
320                         debug($feed->{message});
321                         next;
322                 }
323                 if (! $f) {
324                         $feed->{message}=XML::Feed->errstr;
325                         $feed->{error}=1;
326                         debug($feed->{message});
327                         next;
328                 }
329
330                 foreach my $entry ($f->entries) {
331                         add_page(
332                                 feed => $feed,
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,
339                         );
340                 }
341         }
342 } #}}}
343
344 sub add_page (@) { #{{{
345         my %params=@_;
346         
347         my $feed=$params{feed};
348         my $guid={};
349         my $mtime;
350         if (exists $guids{$params{guid}}) {
351                 # updating an existing post
352                 $guid=$guids{$params{guid}};
353                 return if $guid->{expired};
354         }
355         else {
356                 # new post
357                 $guid->{guid}=$params{guid};
358                 $guids{$params{guid}}=$guid;
359                 $mtime=$params{ctime};
360                 $feed->{numposts}++;
361                 $feed->{newposts}++;
362
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";
372                 }
373                 my $c="";
374                 while (exists $IkiWiki::pagecase{lc $page.$c} ||
375                        -e pagefile($page.$c)) {
376                         $c++
377                 }
378
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) {
383                         $c="";
384                         $page=$feed->{dir}."/item";
385                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
386                                -e pagefile($page.$c)) {
387                                 $c++
388                         }
389                 }
390
391                 $guid->{page}=$page;
392                 debug(sprintf(gettext("creating new page %s"), $page));
393         }
394         $guid->{feed}=$feed->{name};
395         
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'};
400         error($@) if $@;
401         require Encode;
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;
405
406         # Create the page.
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}}]);
419         }
420         writefile(htmlfn($guid->{page}), $config{srcdir},
421                 $template->output);
422
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;
427 } #}}}
428
429 sub htmlescape ($) { #{{{
430         # escape accidental wikilinks and preprocessor stuff
431         my $html=shift;
432         $html=~s/(?<!\\)\[\[/\\\[\[/g;
433         return $html;
434 } #}}}
435
436 sub urlabs ($$) { #{{{
437         my $url=shift;
438         my $urlbase=shift;
439
440         URI->new_abs($url, $urlbase)->as_string;
441 } #}}}
442
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
447         # bug #381359.
448         my $html=shift;
449         my $urlbase=shift;
450
451         my $ret="";
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}) {
457                         while (4 <= @$pos) {
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) =
462                                         splice(@$pos, -4);
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/\"/&quot;/g; # since we quote with ""
470                                 substr($text, $v_offset, $v_len) = qq("$new_v");
471                         }
472                 }
473                 $ret.=$text;
474         }, "tagname, tokenpos, text");
475         $p->parse($html);
476         $p->eof;
477
478         return $ret;
479 } #}}}
480
481 sub remove_feeds () { #{{{
482         my $page=shift;
483
484         my %removed;
485         foreach my $id (keys %feeds) {
486                 if ($feeds{$id}->{sourcepage} eq $page) {
487                         $feeds{$id}->{remove}=1;
488                         $removed{$id}=1;
489                 }
490         }
491 } #}}}
492
493 sub pagefile ($) { #{{{
494         my $page=shift;
495
496         return "$config{srcdir}/".htmlfn($page);
497 } #}}}
498
499 sub htmlfn ($) { #{{{
500         return shift().".".$config{htmlext};
501 } #}}}
502
503 1