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