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