delete inline data after it's used
[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 2.00;
8 use HTML::Parser;
9 use HTML::Tagset;
10 use HTML::Entities;
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                 # See if any feeds need aggregation.
37                 loadstate();
38                 my @feeds=needsaggregate();
39                 return unless @feeds;
40                 if (! lockaggregate()) {
41                         debug("an aggregation process is already running");
42                         return;
43                 }
44                 # force a later rebuild of source pages
45                 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
46                         foreach @feeds;
47
48                 # Fork a child process to handle the aggregation.
49                 # The parent process will then handle building the
50                 # result. This avoids messy code to clear state
51                 # accumulated while aggregating.
52                 defined(my $pid = fork) or error("Can't fork: $!");
53                 if (! $pid) {
54                         IkiWiki::loadindex();
55
56                         # Aggregation happens without the main wiki lock
57                         # being held. This allows editing pages etc while
58                         # aggregation is running.
59                         aggregate(@feeds);
60
61                         IkiWiki::lockwiki;
62                         # Merge changes, since aggregation state may have
63                         # changed on disk while the aggregation was happening.
64                         mergestate();
65                         expire();
66                         savestate();
67                         IkiWiki::unlockwiki;
68                         exit 0;
69                 }
70                 waitpid($pid,0);
71                 if ($?) {
72                         error "aggregation failed with code $?";
73                 }
74
75                 clearstate();
76                 unlockaggregate();
77         }
78 } #}}}
79
80 sub needsbuild (@) { #{{{
81         my $needsbuild=shift;
82         
83         loadstate();
84
85         foreach my $feed (values %feeds) {
86                 if (exists $pagesources{$feed->{sourcepage}} && 
87                     grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
88                         # Mark all feeds originating on this page as 
89                         # not yet seen; preprocess will unmark those that
90                         # still exist.
91                         markunseen($feed->{sourcepage});
92                 }
93         }
94 } # }}}
95
96 sub preprocess (@) { #{{{
97         my %params=@_;
98
99         foreach my $required (qw{name url}) {
100                 if (! exists $params{$required}) {
101                         return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
102                 }
103         }
104
105         my $feed={};
106         my $name=$params{name};
107         if (exists $feeds{$name}) {
108                 $feed=$feeds{$name};
109         }
110         else {
111                 $feeds{$name}=$feed;
112         }
113         $feed->{name}=$name;
114         $feed->{sourcepage}=$params{page};
115         $feed->{url}=$params{url};
116         my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
117         $dir=~s/^\/+//;
118         ($dir)=$dir=~/$config{wiki_file_regexp}/;
119         $feed->{dir}=$dir;
120         $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
121         $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
122         $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
123         $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
124         delete $feed->{unseen};
125         $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
126         $feed->{numposts}=0 unless defined $feed->{numposts};
127         $feed->{newposts}=0 unless defined $feed->{newposts};
128         $feed->{message}=gettext("new feed") unless defined $feed->{message};
129         $feed->{error}=0 unless defined $feed->{error};
130         $feed->{tags}=[];
131         while (@_) {
132                 my $key=shift;
133                 my $value=shift;
134                 if ($key eq 'tag') {
135                         push @{$feed->{tags}}, $value;
136                 }
137         }
138
139         return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
140                ($feed->{error} ? "<em>" : "").$feed->{message}.
141                ($feed->{error} ? "</em>" : "").
142                " (".$feed->{numposts}." ".gettext("posts").
143                ($feed->{newposts} ? "; ".$feed->{newposts}.
144                                     " ".gettext("new") : "").
145                ")";
146 } # }}}
147
148 sub delete (@) { #{{{
149         my @files=@_;
150
151         # Remove feed data for removed pages.
152         foreach my $file (@files) {
153                 my $page=pagename($file);
154                 markunseen($page);
155         }
156 } #}}}
157
158 sub markunseen ($) { #{{{
159         my $page=shift;
160
161         foreach my $id (keys %feeds) {
162                 if ($feeds{$id}->{sourcepage} eq $page) {
163                         $feeds{$id}->{unseen}=1;
164                 }
165         }
166 } #}}}
167
168 my $state_loaded=0;
169
170 sub loadstate () { #{{{
171         return if $state_loaded;
172         $state_loaded=1;
173         if (-e "$config{wikistatedir}/aggregate") {
174                 open(IN, "$config{wikistatedir}/aggregate") ||
175                         die "$config{wikistatedir}/aggregate: $!";
176                 while (<IN>) {
177                         $_=IkiWiki::possibly_foolish_untaint($_);
178                         chomp;
179                         my $data={};
180                         foreach my $i (split(/ /, $_)) {
181                                 my ($field, $val)=split(/=/, $i, 2);
182                                 if ($field eq "name" || $field eq "feed" ||
183                                     $field eq "guid" || $field eq "message") {
184                                         $data->{$field}=decode_entities($val, " \t\n");
185                                 }
186                                 elsif ($field eq "tag") {
187                                         push @{$data->{tags}}, $val;
188                                 }
189                                 else {
190                                         $data->{$field}=$val;
191                                 }
192                         }
193                         
194                         if (exists $data->{name}) {
195                                 $feeds{$data->{name}}=$data;
196                         }
197                         elsif (exists $data->{guid}) {
198                                 $guids{$data->{guid}}=$data;
199                         }
200                 }
201
202                 close IN;
203         }
204 } #}}}
205
206 sub savestate () { #{{{
207         return unless $state_loaded;
208         garbage_collect();
209         my $newfile="$config{wikistatedir}/aggregate.new";
210         my $cleanup = sub { unlink($newfile) };
211         open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
212         foreach my $data (values %feeds, values %guids) {
213                 my @line;
214                 foreach my $field (keys %$data) {
215                         if ($field eq "name" || $field eq "feed" ||
216                             $field eq "guid" || $field eq "message") {
217                                 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
218                         }
219                         elsif ($field eq "tags") {
220                                 push @line, "tag=$_" foreach @{$data->{tags}};
221                         }
222                         else {
223                                 push @line, "$field=".$data->{$field};
224                         }
225                 }
226                 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
227         }
228         close OUT || error("save $newfile: $!", $cleanup);
229         rename($newfile, "$config{wikistatedir}/aggregate") ||
230                 error("rename $newfile: $!", $cleanup);
231 } #}}}
232
233 sub garbage_collect () { #{{{
234         foreach my $name (keys %feeds) {
235                 # remove any feeds that were not seen while building the pages
236                 # that used to contain them
237                 if ($feeds{$name}->{unseen}) {
238                         delete $feeds{$name};
239                 }
240         }
241
242         foreach my $guid (values %guids) {
243                 # any guid whose feed is gone should be removed
244                 if (! exists $feeds{$guid->{feed}}) {
245                         unlink pagefile($guid->{page})
246                                 if exists $guid->{page};
247                         delete $guids{$guid->{guid}};
248                 }
249                 # handle expired guids
250                 elsif ($guid->{expired} && exists $guid->{page}) {
251                         unlink pagefile($guid->{page});
252                         delete $guid->{page};
253                         delete $guid->{md5};
254                 }
255         }
256 } #}}}
257
258 sub mergestate () { #{{{
259         # Load the current state in from disk, and merge into it
260         # values from the state in memory that might have changed
261         # during aggregation.
262         my %myfeeds=%feeds;
263         my %myguids=%guids;
264         clearstate();
265         loadstate();
266
267         # All that can change in feed state during aggregation is a few
268         # fields.
269         foreach my $name (keys %myfeeds) {
270                 if (exists $feeds{$name}) {
271                         foreach my $field (qw{message lastupdate numposts
272                                               newposts error}) {
273                                 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
274                         }
275                 }
276         }
277
278         # New guids can be created during aggregation.
279         # It's also possible that guids were removed from the on-disk state
280         # while the aggregation was in process. That would only happen if
281         # their feed was also removed, so any removed guids added back here
282         # will be garbage collected later.
283         foreach my $guid (keys %myguids) {
284                 if (! exists $guids{$guid}) {
285                         $guids{$guid}=$myguids{$guid};
286                 }
287         }
288 } #}}}
289
290 sub clearstate () { #{{{
291         %feeds=();
292         %guids=();
293         $state_loaded=0;
294 } #}}}
295
296 sub expire () { #{{{
297         foreach my $feed (values %feeds) {
298                 next unless $feed->{expireage} || $feed->{expirecount};
299                 my $count=0;
300                 my %seen;
301                 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
302                                   grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
303                                   values %guids) {
304                         if ($feed->{expireage}) {
305                                 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
306                                 if ($days_old > $feed->{expireage}) {
307                                         debug(sprintf(gettext("expiring %s (%s days old)"),
308                                                 $item->{page}, int($days_old)));
309                                         $item->{expired}=1;
310                                 }
311                         }
312                         elsif ($feed->{expirecount} &&
313                                $count >= $feed->{expirecount}) {
314                                 debug(sprintf(gettext("expiring %s"), $item->{page}));
315                                 $item->{expired}=1;
316                         }
317                         else {
318                                 if (! $seen{$item->{page}}) {
319                                         $seen{$item->{page}}=1;
320                                         $count++;
321                                 }
322                         }
323                 }
324         }
325 } #}}}
326
327 sub needsaggregate () { #{{{
328         return values %feeds if $config{rebuild};
329         return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
330 } #}}}
331
332 sub aggregate (@) { #{{{
333         eval q{use XML::Feed};
334         error($@) if $@;
335         eval q{use URI::Fetch};
336         error($@) if $@;
337
338         foreach my $feed (@_) {
339                 $feed->{lastupdate}=time;
340                 $feed->{newposts}=0;
341                 $feed->{message}=sprintf(gettext("processed ok at %s"),
342                         displaytime($feed->{lastupdate}));
343                 $feed->{error}=0;
344
345                 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
346
347                 if (! length $feed->{feedurl}) {
348                         my @urls=XML::Feed->find_feeds($feed->{url});
349                         if (! @urls) {
350                                 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
351                                 $feed->{error}=1;
352                                 debug($feed->{message});
353                                 next;
354                         }
355                         $feed->{feedurl}=pop @urls;
356                 }
357                 my $res=URI::Fetch->fetch($feed->{feedurl});
358                 if (! $res) {
359                         $feed->{message}=URI::Fetch->errstr;
360                         $feed->{error}=1;
361                         debug($feed->{message});
362                         next;
363                 }
364                 if ($res->status == URI::Fetch::URI_GONE()) {
365                         $feed->{message}=gettext("feed not found");
366                         $feed->{error}=1;
367                         debug($feed->{message});
368                         next;
369                 }
370                 my $content=$res->content;
371                 my $f=eval{XML::Feed->parse(\$content)};
372                 if ($@) {
373                         # One common cause of XML::Feed crashing is a feed
374                         # that contains invalid UTF-8 sequences. Convert
375                         # feed to ascii to try to work around.
376                         $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
377                         $content=Encode::decode_utf8($content);
378                         $f=eval{XML::Feed->parse(\$content)};
379                 }
380                 if ($@) {
381                         # Another possibility is badly escaped entities.
382                         $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
383                         $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
384                         $content=Encode::decode_utf8($content);
385                         $f=eval{XML::Feed->parse(\$content)};
386                 }
387                 if ($@) {
388                         $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
389                         $feed->{error}=1;
390                         debug($feed->{message});
391                         next;
392                 }
393                 if (! $f) {
394                         $feed->{message}=XML::Feed->errstr;
395                         $feed->{error}=1;
396                         debug($feed->{message});
397                         next;
398                 }
399
400                 foreach my $entry ($f->entries) {
401                         add_page(
402                                 feed => $feed,
403                                 copyright => $f->copyright,
404                                 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
405                                 link => $entry->link,
406                                 content => defined $entry->content->body ? $entry->content->body : "",
407                                 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
408                                 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
409                         );
410                 }
411         }
412 } #}}}
413
414 sub add_page (@) { #{{{
415         my %params=@_;
416         
417         my $feed=$params{feed};
418         my $guid={};
419         my $mtime;
420         if (exists $guids{$params{guid}}) {
421                 # updating an existing post
422                 $guid=$guids{$params{guid}};
423                 return if $guid->{expired};
424         }
425         else {
426                 # new post
427                 $guid->{guid}=$params{guid};
428                 $guids{$params{guid}}=$guid;
429                 $mtime=$params{ctime};
430                 $feed->{numposts}++;
431                 $feed->{newposts}++;
432
433                 # assign it an unused page
434                 my $page=IkiWiki::titlepage($params{title});
435                 # escape slashes and periods in title so it doesn't specify
436                 # directory name or trigger ".." disallowing code.
437                 $page=~s!([/.])!"__".ord($1)."__"!eg;
438                 $page=$feed->{dir}."/".$page;
439                 ($page)=$page=~/$config{wiki_file_regexp}/;
440                 if (! defined $page || ! length $page) {
441                         $page=$feed->{dir}."/item";
442                 }
443                 my $c="";
444                 while (exists $IkiWiki::pagecase{lc $page.$c} ||
445                        -e pagefile($page.$c)) {
446                         $c++
447                 }
448
449                 # Make sure that the file name isn't too long. 
450                 # NB: This doesn't check for path length limits.
451                 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
452                 if (defined $max && length(htmlfn($page)) >= $max) {
453                         $c="";
454                         $page=$feed->{dir}."/item";
455                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
456                                -e pagefile($page.$c)) {
457                                 $c++
458                         }
459                 }
460
461                 $guid->{page}=$page;
462                 debug(sprintf(gettext("creating new page %s"), $page));
463         }
464         $guid->{feed}=$feed->{name};
465         
466         # To write or not to write? Need to avoid writing unchanged pages
467         # to avoid unneccessary rebuilding. The mtime from rss cannot be
468         # trusted; let's use a digest.
469         eval q{use Digest::MD5 'md5_hex'};
470         error($@) if $@;
471         require Encode;
472         my $digest=md5_hex(Encode::encode_utf8($params{content}));
473         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
474         $guid->{md5}=$digest;
475
476         # Create the page.
477         my $template=template("aggregatepost.tmpl", blind_cache => 1);
478         $template->param(title => $params{title})
479                 if defined $params{title} && length($params{title});
480         $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
481         $template->param(name => $feed->{name});
482         $template->param(url => $feed->{url});
483         $template->param(copyright => $params{copyright})
484                 if defined $params{copyright} && length $params{copyright};
485         $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
486                 if defined $params{link};
487         if (ref $feed->{tags}) {
488                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
489         }
490         writefile(htmlfn($guid->{page}), $config{srcdir},
491                 $template->output);
492
493         # Set the mtime, this lets the build process get the right creation
494         # time on record for the new page.
495         utime $mtime, $mtime, pagefile($guid->{page})
496                 if defined $mtime && $mtime <= time;
497 } #}}}
498
499 sub htmlescape ($) { #{{{
500         # escape accidental wikilinks and preprocessor stuff
501         my $html=shift;
502         $html=~s/(?<!\\)\[\[/\\\[\[/g;
503         return $html;
504 } #}}}
505
506 sub urlabs ($$) { #{{{
507         my $url=shift;
508         my $urlbase=shift;
509
510         URI->new_abs($url, $urlbase)->as_string;
511 } #}}}
512
513 sub htmlabs ($$) { #{{{
514         # Convert links in html from relative to absolute.
515         # Note that this is a heuristic, which is not specified by the rss
516         # spec and may not be right for all feeds. Also, see Debian
517         # bug #381359.
518         my $html=shift;
519         my $urlbase=shift;
520
521         my $ret="";
522         my $p = HTML::Parser->new(api_version => 3);
523         $p->handler(default => sub { $ret.=join("", @_) }, "text");
524         $p->handler(start => sub {
525                 my ($tagname, $pos, $text) = @_;
526                 if (ref $HTML::Tagset::linkElements{$tagname}) {
527                         while (4 <= @$pos) {
528                                 # use attribute sets from right to left
529                                 # to avoid invalidating the offsets
530                                 # when replacing the values
531                                 my($k_offset, $k_len, $v_offset, $v_len) =
532                                         splice(@$pos, -4);
533                                 my $attrname = lc(substr($text, $k_offset, $k_len));
534                                 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
535                                 next unless $v_offset; # 0 v_offset means no value
536                                 my $v = substr($text, $v_offset, $v_len);
537                                 $v =~ s/^([\'\"])(.*)\1$/$2/;
538                                 my $new_v=urlabs($v, $urlbase);
539                                 $new_v =~ s/\"/&quot;/g; # since we quote with ""
540                                 substr($text, $v_offset, $v_len) = qq("$new_v");
541                         }
542                 }
543                 $ret.=$text;
544         }, "tagname, tokenpos, text");
545         $p->parse($html);
546         $p->eof;
547
548         return $ret;
549 } #}}}
550
551 sub pagefile ($) { #{{{
552         my $page=shift;
553
554         return "$config{srcdir}/".htmlfn($page);
555 } #}}}
556
557 sub htmlfn ($) { #{{{
558         return shift().".".$config{htmlext};
559 } #}}}
560
561 my $aggregatelock;
562
563 sub lockaggregate () { #{{{
564         # Take an exclusive lock to prevent multiple concurrent aggregators.
565         # Returns true if the lock was aquired.
566         if (! -d $config{wikistatedir}) {
567                 mkdir($config{wikistatedir});
568         }
569         open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
570                 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
571         if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
572                 close($aggregatelock) || error("failed closing aggregatelock: $!");
573                 return 0;
574         }
575         return 1;
576 } #}}}
577
578 sub unlockaggregate () { #{{{
579         return close($aggregatelock) if $aggregatelock;
580         return;
581 } #}}}
582
583 1