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