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