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