ba40ee6bcb42f57f2f3929db25a5f0fa75aeeb34
[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::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                 # 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         eval q{use HTML::Entities};
210         error($@) if $@;
211         my $newfile="$config{wikistatedir}/aggregate.new";
212         my $cleanup = sub { unlink($newfile) };
213         open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
214         foreach my $data (values %feeds, values %guids) {
215                 my @line;
216                 foreach my $field (keys %$data) {
217                         if ($field eq "name" || $field eq "feed" ||
218                             $field eq "guid" || $field eq "message") {
219                                 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
220                         }
221                         elsif ($field eq "tags") {
222                                 push @line, "tag=$_" foreach @{$data->{tags}};
223                         }
224                         else {
225                                 push @line, "$field=".$data->{$field};
226                         }
227                 }
228                 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
229         }
230         close OUT || error("save $newfile: $!", $cleanup);
231         rename($newfile, "$config{wikistatedir}/aggregate") ||
232                 error("rename $newfile: $!", $cleanup);
233 } #}}}
234
235 sub garbage_collect () { #{{{
236         foreach my $name (keys %feeds) {
237                 # remove any feeds that were not seen while building the pages
238                 # that used to contain them
239                 if ($feeds{$name}->{unseen}) {
240                         delete $feeds{$name};
241                 }
242         }
243
244         foreach my $guid (values %guids) {
245                 # any guid whose feed is gone should be removed
246                 if (! exists $feeds{$guid->{feed}}) {
247                         unlink pagefile($guid->{page})
248                                 if exists $guid->{page};
249                         delete $guids{$guid->{guid}};
250                 }
251                 # handle expired guids
252                 elsif ($guid->{expired} && exists $guid->{page}) {
253                         unlink pagefile($guid->{page});
254                         delete $guid->{page};
255                         delete $guid->{md5};
256                 }
257         }
258 } #}}}
259
260 sub mergestate () { #{{{
261         # Load the current state in from disk, and merge into it
262         # values from the state in memory that might have changed
263         # during aggregation.
264         my %myfeeds=%feeds;
265         my %myguids=%guids;
266         clearstate();
267         loadstate();
268
269         # All that can change in feed state during aggregation is a few
270         # fields.
271         foreach my $name (keys %myfeeds) {
272                 if (exists $feeds{$name}) {
273                         foreach my $field (qw{message lastupdate numposts
274                                               newposts error}) {
275                                 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
276                         }
277                 }
278         }
279
280         # New guids can be created during aggregation.
281         # It's also possible that guids were removed from the on-disk state
282         # while the aggregation was in process. That would only happen if
283         # their feed was also removed, so any removed guids added back here
284         # will be garbage collected later.
285         foreach my $guid (keys %myguids) {
286                 if (! exists $guids{$guid}) {
287                         $guids{$guid}=$myguids{$guid};
288                 }
289         }
290 } #}}}
291
292 sub clearstate () { #{{{
293         %feeds=();
294         %guids=();
295         $state_loaded=0;
296 } #}}}
297
298 sub expire () { #{{{
299         foreach my $feed (values %feeds) {
300                 next unless $feed->{expireage} || $feed->{expirecount};
301                 my $count=0;
302                 my %seen;
303                 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
304                                   grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
305                                   values %guids) {
306                         if ($feed->{expireage}) {
307                                 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
308                                 if ($days_old > $feed->{expireage}) {
309                                         debug(sprintf(gettext("expiring %s (%s days old)"),
310                                                 $item->{page}, int($days_old)));
311                                         $item->{expired}=1;
312                                 }
313                         }
314                         elsif ($feed->{expirecount} &&
315                                $count >= $feed->{expirecount}) {
316                                 debug(sprintf(gettext("expiring %s"), $item->{page}));
317                                 $item->{expired}=1;
318                         }
319                         else {
320                                 if (! $seen{$item->{page}}) {
321                                         $seen{$item->{page}}=1;
322                                         $count++;
323                                 }
324                         }
325                 }
326         }
327 } #}}}
328
329 sub needsaggregate () { #{{{
330         return values %feeds if $config{rebuild};
331         return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
332 } #}}}
333
334 sub aggregate (@) { #{{{
335         eval q{use XML::Feed};
336         error($@) if $@;
337         eval q{use URI::Fetch};
338         error($@) if $@;
339         eval q{use HTML::Entities};
340         error($@) if $@;
341
342         foreach my $feed (@_) {
343                 $feed->{lastupdate}=time;
344                 $feed->{newposts}=0;
345                 $feed->{message}=sprintf(gettext("processed ok at %s"),
346                         displaytime($feed->{lastupdate}));
347                 $feed->{error}=0;
348
349                 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
350
351                 if (! length $feed->{feedurl}) {
352                         my @urls=XML::Feed->find_feeds($feed->{url});
353                         if (! @urls) {
354                                 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
355                                 $feed->{error}=1;
356                                 debug($feed->{message});
357                                 next;
358                         }
359                         $feed->{feedurl}=pop @urls;
360                 }
361                 my $res=URI::Fetch->fetch($feed->{feedurl});
362                 if (! $res) {
363                         $feed->{message}=URI::Fetch->errstr;
364                         $feed->{error}=1;
365                         debug($feed->{message});
366                         next;
367                 }
368                 if ($res->status == URI::Fetch::URI_GONE()) {
369                         $feed->{message}=gettext("feed not found");
370                         $feed->{error}=1;
371                         debug($feed->{message});
372                         next;
373                 }
374                 my $content=$res->content;
375                 my $f=eval{XML::Feed->parse(\$content)};
376                 if ($@) {
377                         # One common cause of XML::Feed crashing is a feed
378                         # that contains invalid UTF-8 sequences. Convert
379                         # feed to ascii to try to work around.
380                         $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
381                         $content=Encode::decode_utf8($content);
382                         $f=eval{XML::Feed->parse(\$content)};
383                 }
384                 if ($@) {
385                         # Another possibility is badly escaped entities.
386                         $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
387                         $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
388                         $content=Encode::decode_utf8($content);
389                         $f=eval{XML::Feed->parse(\$content)};
390                 }
391                 if ($@) {
392                         $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
393                         $feed->{error}=1;
394                         debug($feed->{message});
395                         next;
396                 }
397                 if (! $f) {
398                         $feed->{message}=XML::Feed->errstr;
399                         $feed->{error}=1;
400                         debug($feed->{message});
401                         next;
402                 }
403
404                 foreach my $entry ($f->entries) {
405                         add_page(
406                                 feed => $feed,
407                                 copyright => $f->copyright,
408                                 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
409                                 link => $entry->link,
410                                 content => defined $entry->content->body ? $entry->content->body : "",
411                                 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
412                                 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
413                         );
414                 }
415         }
416 } #}}}
417
418 sub add_page (@) { #{{{
419         my %params=@_;
420         
421         my $feed=$params{feed};
422         my $guid={};
423         my $mtime;
424         if (exists $guids{$params{guid}}) {
425                 # updating an existing post
426                 $guid=$guids{$params{guid}};
427                 return if $guid->{expired};
428         }
429         else {
430                 # new post
431                 $guid->{guid}=$params{guid};
432                 $guids{$params{guid}}=$guid;
433                 $mtime=$params{ctime};
434                 $feed->{numposts}++;
435                 $feed->{newposts}++;
436
437                 # assign it an unused page
438                 my $page=IkiWiki::titlepage($params{title});
439                 # escape slashes and periods in title so it doesn't specify
440                 # directory name or trigger ".." disallowing code.
441                 $page=~s!([/.])!"__".ord($1)."__"!eg;
442                 $page=$feed->{dir}."/".$page;
443                 ($page)=$page=~/$config{wiki_file_regexp}/;
444                 if (! defined $page || ! length $page) {
445                         $page=$feed->{dir}."/item";
446                 }
447                 my $c="";
448                 while (exists $IkiWiki::pagecase{lc $page.$c} ||
449                        -e pagefile($page.$c)) {
450                         $c++
451                 }
452
453                 # Make sure that the file name isn't too long. 
454                 # NB: This doesn't check for path length limits.
455                 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
456                 if (defined $max && length(htmlfn($page)) >= $max) {
457                         $c="";
458                         $page=$feed->{dir}."/item";
459                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
460                                -e pagefile($page.$c)) {
461                                 $c++
462                         }
463                 }
464
465                 $guid->{page}=$page;
466                 debug(sprintf(gettext("creating new page %s"), $page));
467         }
468         $guid->{feed}=$feed->{name};
469         
470         # To write or not to write? Need to avoid writing unchanged pages
471         # to avoid unneccessary rebuilding. The mtime from rss cannot be
472         # trusted; let's use a digest.
473         eval q{use Digest::MD5 'md5_hex'};
474         error($@) if $@;
475         require Encode;
476         my $digest=md5_hex(Encode::encode_utf8($params{content}));
477         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
478         $guid->{md5}=$digest;
479
480         # Create the page.
481         my $template=template("aggregatepost.tmpl", blind_cache => 1);
482         $template->param(title => $params{title})
483                 if defined $params{title} && length($params{title});
484         $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
485         $template->param(name => $feed->{name});
486         $template->param(url => $feed->{url});
487         $template->param(copyright => $params{copyright})
488                 if defined $params{copyright} && length $params{copyright};
489         $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
490                 if defined $params{link};
491         if (ref $feed->{tags}) {
492                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
493         }
494         writefile(htmlfn($guid->{page}), $config{srcdir},
495                 $template->output);
496
497         # Set the mtime, this lets the build process get the right creation
498         # time on record for the new page.
499         utime $mtime, $mtime, pagefile($guid->{page})
500                 if defined $mtime && $mtime <= time;
501 } #}}}
502
503 sub htmlescape ($) { #{{{
504         # escape accidental wikilinks and preprocessor stuff
505         my $html=shift;
506         $html=~s/(?<!\\)\[\[/\\\[\[/g;
507         return $html;
508 } #}}}
509
510 sub urlabs ($$) { #{{{
511         my $url=shift;
512         my $urlbase=shift;
513
514         URI->new_abs($url, $urlbase)->as_string;
515 } #}}}
516
517 sub htmlabs ($$) { #{{{
518         # Convert links in html from relative to absolute.
519         # Note that this is a heuristic, which is not specified by the rss
520         # spec and may not be right for all feeds. Also, see Debian
521         # bug #381359.
522         my $html=shift;
523         my $urlbase=shift;
524
525         my $ret="";
526         my $p = HTML::Parser->new(api_version => 3);
527         $p->handler(default => sub { $ret.=join("", @_) }, "text");
528         $p->handler(start => sub {
529                 my ($tagname, $pos, $text) = @_;
530                 if (ref $HTML::Tagset::linkElements{$tagname}) {
531                         while (4 <= @$pos) {
532                                 # use attribute sets from right to left
533                                 # to avoid invalidating the offsets
534                                 # when replacing the values
535                                 my($k_offset, $k_len, $v_offset, $v_len) =
536                                         splice(@$pos, -4);
537                                 my $attrname = lc(substr($text, $k_offset, $k_len));
538                                 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
539                                 next unless $v_offset; # 0 v_offset means no value
540                                 my $v = substr($text, $v_offset, $v_len);
541                                 $v =~ s/^([\'\"])(.*)\1$/$2/;
542                                 my $new_v=urlabs($v, $urlbase);
543                                 $new_v =~ s/\"/&quot;/g; # since we quote with ""
544                                 substr($text, $v_offset, $v_len) = qq("$new_v");
545                         }
546                 }
547                 $ret.=$text;
548         }, "tagname, tokenpos, text");
549         $p->parse($html);
550         $p->eof;
551
552         return $ret;
553 } #}}}
554
555 sub pagefile ($) { #{{{
556         my $page=shift;
557
558         return "$config{srcdir}/".htmlfn($page);
559 } #}}}
560
561 sub htmlfn ($) { #{{{
562         return shift().".".$config{htmlext};
563 } #}}}
564
565 my $aggregatelock;
566
567 sub lockaggregate () { #{{{
568         # Take an exclusive lock to prevent multiple concurrent aggregators.
569         # Returns true if the lock was aquired.
570         if (! -d $config{wikistatedir}) {
571                 mkdir($config{wikistatedir});
572         }
573         open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
574                 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
575         if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
576                 close($aggregatelock) || error("failed closing aggregatelock: $!");
577                 return 0;
578         }
579         return 1;
580 } #}}}
581
582 sub unlockaggregate () { #{{{
583         return close($aggregatelock) if $aggregatelock;
584         return;
585 } #}}}
586
587 1