]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Plugin/aggregate.pm
5024975ac8603223191b9a36525c6a650d6bec77
[ikiwiki.git] / IkiWiki / Plugin / aggregate.pm
1 #!/usr/bin/perl
2 # Blog aggregation plugin.
3 package IkiWiki::Plugin::aggregate;
4
5 use warnings;
6 use strict;
7 use IkiWiki 2.00;
8 use HTML::Entities;
9 use HTML::Parser;
10 use HTML::Tagset;
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 => "filter", id => "aggregate", call => \&filter);
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 } # }}}
25
26 sub getopt () { #{{{
27         eval q{use Getopt::Long};
28         error($@) if $@;
29         Getopt::Long::Configure('pass_through');
30         GetOptions("aggregate" => \$config{aggregate});
31 } #}}}
32
33 sub checkconfig () { #{{{
34         if ($config{aggregate} && ! ($config{post_commit} && 
35                                      IkiWiki::commit_hook_enabled())) {
36                 # don't wait for the lock
37                 IkiWiki::lockwiki(0) || exit 1;
38         
39                 loadstate();
40                 IkiWiki::loadindex();
41                 aggregate();
42                 expire();
43                 savestate();
44                 clearstate();
45
46                 IkiWiki::unlockwiki();
47         }
48 } #}}}
49
50 sub filter (@) { #{{{
51         my %params=@_;
52         my $page=$params{page};
53
54         loadstate(); # if not already loaded
55         # Mark all feeds originating on this page as removable;
56         # preprocess will unmark those that still exist.
57         remove_feeds($page);
58
59         return $params{content};
60 } # }}}
61
62 sub preprocess (@) { #{{{
63         my %params=@_;
64
65         foreach my $required (qw{name url}) {
66                 if (! exists $params{$required}) {
67                         return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
68                 }
69         }
70
71         my $feed={};
72         my $name=$params{name};
73         if (exists $feeds{$name}) {
74                 $feed=$feeds{$name};
75         }
76         else {
77                 $feeds{$name}=$feed;
78         }
79         $feed->{name}=$name;
80         $feed->{sourcepage}=$params{page};
81         $feed->{url}=$params{url};
82         my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
83         $dir=~s/^\/+//;
84         ($dir)=$dir=~/$config{wiki_file_regexp}/;
85         $feed->{dir}=$dir;
86         $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
87         $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
88         $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
89         $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
90         delete $feed->{remove};
91         delete $feed->{expired};
92         $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
93         $feed->{numposts}=0 unless defined $feed->{numposts};
94         $feed->{newposts}=0 unless defined $feed->{newposts};
95         $feed->{message}=gettext("new feed") unless defined $feed->{message};
96         $feed->{error}=0 unless defined $feed->{error};
97         $feed->{tags}=[];
98         while (@_) {
99                 my $key=shift;
100                 my $value=shift;
101                 if ($key eq 'tag') {
102                         push @{$feed->{tags}}, $value;
103                 }
104         }
105
106         return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
107                ($feed->{error} ? "<em>" : "").$feed->{message}.
108                ($feed->{error} ? "</em>" : "").
109                " (".$feed->{numposts}." ".gettext("posts").
110                ($feed->{newposts} ? "; ".$feed->{newposts}.
111                                     " ".gettext("new") : "").
112                ")";
113 } # }}}
114
115 sub delete (@) { #{{{
116         my @files=@_;
117
118         # Remove feed data for removed pages.
119         foreach my $file (@files) {
120                 my $page=pagename($file);
121                 remove_feeds($page);
122         }
123 } #}}}
124
125 my $state_loaded=0;
126 sub loadstate () { #{{{
127         return if $state_loaded;
128         if (-e "$config{wikistatedir}/aggregate") {
129                 open (IN, "$config{wikistatedir}/aggregate" ||
130                         die "$config{wikistatedir}/aggregate: $!");
131                 while (<IN>) {
132                         $_=IkiWiki::possibly_foolish_untaint($_);
133                         chomp;
134                         my $data={};
135                         foreach my $i (split(/ /, $_)) {
136                                 my ($field, $val)=split(/=/, $i, 2);
137                                 if ($field eq "name" || $field eq "feed" ||
138                                     $field eq "guid" || $field eq "message") {
139                                         $data->{$field}=decode_entities($val, " \t\n");
140                                 }
141                                 elsif ($field eq "tag") {
142                                         push @{$data->{tags}}, $val;
143                                 }
144                                 else {
145                                         $data->{$field}=$val;
146                                 }
147                         }
148                         
149                         if (exists $data->{name}) {
150                                 $feeds{$data->{name}}=$data;
151                         }
152                         elsif (exists $data->{guid}) {
153                                 $guids{$data->{guid}}=$data;
154                         }
155                 }
156
157                 close IN;
158                 
159                 $state_loaded=1;
160         }
161 } #}}}
162
163 sub savestate () { #{{{
164         eval q{use HTML::Entities};
165         error($@) if $@;
166         my $newfile="$config{wikistatedir}/aggregate.new";
167         # TODO: This cleanup function could use improvement. Any newly
168         # aggregated files are left behind unrecorded, and should be deleted.
169         my $cleanup = sub { unlink($newfile) };
170         open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
171         foreach my $data (values %feeds, values %guids) {
172                 if ($data->{remove}) {
173                         if ($data->{name}) {
174                                 foreach my $guid (values %guids) {
175                                         if ($guid->{feed} eq $data->{name}) {
176                                                 $guid->{remove}=1;
177                                         }
178                                 }
179                         }
180                         else {
181                                 unlink pagefile($data->{page});
182                         }
183                         next;
184                 }
185                 elsif ($data->{expired} && exists $data->{page}) {
186                         unlink pagefile($data->{page});
187                         delete $data->{page};
188                         delete $data->{md5};
189                 }
190
191                 my @line;
192                 foreach my $field (keys %$data) {
193                         if ($field eq "name" || $field eq "feed" ||
194                             $field eq "guid" || $field eq "message") {
195                                 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
196                         }
197                         elsif ($field eq "tags") {
198                                 push @line, "tag=$_" foreach @{$data->{tags}};
199                         }
200                         else {
201                                 push @line, "$field=".$data->{$field};
202                         }
203                 }
204                 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
205         }
206         close OUT || error("save $newfile: $!", $cleanup);
207         rename($newfile, "$config{wikistatedir}/aggregate") ||
208                 error("rename $newfile: $!", $cleanup);
209 } #}}}
210
211 sub clearstate () { #{{{
212         %feeds=();
213         %guids=();
214         $state_loaded=0;
215 } #}}}
216
217 sub expire () { #{{{
218         foreach my $feed (values %feeds) {
219                 next unless $feed->{expireage} || $feed->{expirecount};
220                 my $count=0;
221                 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
222                                   grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
223                                   values %guids) {
224                         if ($feed->{expireage}) {
225                                 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
226                                 if ($days_old > $feed->{expireage}) {
227                                         debug(sprintf(gettext("expiring %s (%s days old)"),
228                                                 $item->{page}, $days_old));
229                                         $item->{expired}=1;
230                                 }
231                         }
232                         elsif ($feed->{expirecount} &&
233                                $count >= $feed->{expirecount}) {
234                                 debug(sprintf(gettext("expiring %s"), $item->{page}));
235                                 $item->{expired}=1;
236                         }
237                         else {
238                                 $count++;
239                         }
240                 }
241         }
242 } #}}}
243
244 sub aggregate () { #{{{
245         eval q{use XML::Feed};
246         error($@) if $@;
247         eval q{use URI::Fetch};
248         error($@) if $@;
249         eval q{use HTML::Entities};
250         error($@) if $@;
251
252         foreach my $feed (values %feeds) {
253                 next unless $config{rebuild} || 
254                         time - $feed->{lastupdate} >= $feed->{updateinterval};
255                 $feed->{lastupdate}=time;
256                 $feed->{newposts}=0;
257                 $feed->{message}=sprintf(gettext("processed ok at %s"),
258                         displaytime($feed->{lastupdate}));
259                 $feed->{error}=0;
260                 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
261
262                 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
263
264                 if (! length $feed->{feedurl}) {
265                         my @urls=XML::Feed->find_feeds($feed->{url});
266                         if (! @urls) {
267                                 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
268                                 $feed->{error}=1;
269                                 debug($feed->{message});
270                                 next;
271                         }
272                         $feed->{feedurl}=pop @urls;
273                 }
274                 my $res=URI::Fetch->fetch($feed->{feedurl});
275                 if (! $res) {
276                         $feed->{message}=URI::Fetch->errstr;
277                         $feed->{error}=1;
278                         debug($feed->{message});
279                         next;
280                 }
281                 if ($res->status == URI::Fetch::URI_GONE()) {
282                         $feed->{message}=gettext("feed not found");
283                         $feed->{error}=1;
284                         debug($feed->{message});
285                         next;
286                 }
287                 my $content=$res->content;
288                 my $f=eval{XML::Feed->parse(\$content)};
289                 if ($@) {
290                         # One common cause of XML::Feed crashing is a feed
291                         # that contains invalid UTF-8 sequences. Convert
292                         # feed to ascii to try to work around.
293                         $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
294                         $content=Encode::decode_utf8($content);
295                         $f=eval{XML::Feed->parse(\$content)};
296                 }
297                 if ($@) {
298                         $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
299                         $feed->{error}=1;
300                         debug($feed->{message});
301                         next;
302                 }
303                 if (! $f) {
304                         $feed->{message}=XML::Feed->errstr;
305                         $feed->{error}=1;
306                         debug($feed->{message});
307                         next;
308                 }
309
310                 foreach my $entry ($f->entries) {
311                         add_page(
312                                 feed => $feed,
313                                 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
314                                 link => $entry->link,
315                                 content => defined $entry->content->body ? $entry->content->body : "",
316                                 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
317                                 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
318                         );
319                 }
320         }
321 } #}}}
322
323 sub add_page (@) { #{{{
324         my %params=@_;
325         
326         my $feed=$params{feed};
327         my $guid={};
328         my $mtime;
329         if (exists $guids{$params{guid}}) {
330                 # updating an existing post
331                 $guid=$guids{$params{guid}};
332                 return if $guid->{expired};
333         }
334         else {
335                 # new post
336                 $guid->{guid}=$params{guid};
337                 $guids{$params{guid}}=$guid;
338                 $mtime=$params{ctime};
339                 $feed->{numposts}++;
340                 $feed->{newposts}++;
341
342                 # assign it an unused page
343                 my $page=IkiWiki::titlepage($params{title});
344                 # escape slashes and periods in title so it doesn't specify
345                 # directory name or trigger ".." disallowing code.
346                 $page=~s!([/.])!"__".ord($1)."__"!eg;
347                 $page=$feed->{dir}."/".$page;
348                 ($page)=$page=~/$config{wiki_file_regexp}/;
349                 if (! defined $page || ! length $page) {
350                         $page=$feed->{dir}."/item";
351                 }
352                 my $c="";
353                 while (exists $IkiWiki::pagecase{lc $page.$c} ||
354                        -e pagefile($page.$c)) {
355                         $c++
356                 }
357
358                 # Make sure that the file name isn't too long. 
359                 # NB: This doesn't check for path length limits.
360                 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
361                 if (defined $max && length(htmlfn($page)) >= $max) {
362                         $c="";
363                         $page=$feed->{dir}."/item";
364                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
365                                -e pagefile($page.$c)) {
366                                 $c++
367                         }
368                 }
369
370                 $guid->{page}=$page;
371                 debug(sprintf(gettext("creating new page %s"), $page));
372         }
373         $guid->{feed}=$feed->{name};
374         
375         # To write or not to write? Need to avoid writing unchanged pages
376         # to avoid unneccessary rebuilding. The mtime from rss cannot be
377         # trusted; let's use a digest.
378         eval q{use Digest::MD5 'md5_hex'};
379         error($@) if $@;
380         require Encode;
381         my $digest=md5_hex(Encode::encode_utf8($params{content}));
382         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
383         $guid->{md5}=$digest;
384
385         # Create the page.
386         my $template=template("aggregatepost.tmpl", blind_cache => 1);
387         $template->param(title => $params{title})
388                 if defined $params{title} && length($params{title});
389         $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
390         $template->param(name => $feed->{name});
391         $template->param(url => $feed->{url});
392         $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
393                 if defined $params{link};
394         if (ref $feed->{tags}) {
395                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
396         }
397         writefile(htmlfn($guid->{page}), $config{srcdir},
398                 $template->output);
399
400         # Set the mtime, this lets the build process get the right creation
401         # time on record for the new page.
402         utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
403 } #}}}
404
405 sub htmlescape ($) { #{{{
406         # escape accidental wikilinks and preprocessor stuff
407         my $html=shift;
408         $html=~s/(?<!\\)\[\[/\\\[\[/g;
409         return $html;
410 } #}}}
411
412 sub urlabs ($$) { #{{{
413         my $url=shift;
414         my $urlbase=shift;
415
416         URI->new_abs($url, $urlbase)->as_string;
417 } #}}}
418
419 sub htmlabs ($$) { #{{{
420         # Convert links in html from relative to absolute.
421         # Note that this is a heuristic, which is not specified by the rss
422         # spec and may not be right for all feeds. Also, see Debian
423         # bug #381359.
424         my $html=shift;
425         my $urlbase=shift;
426
427         my $ret="";
428         my $p = HTML::Parser->new(api_version => 3);
429         $p->handler(default => sub { $ret.=join("", @_) }, "text");
430         $p->handler(start => sub {
431                 my ($tagname, $pos, $text) = @_;
432                 if (ref $HTML::Tagset::linkElements{$tagname}) {
433                         while (4 <= @$pos) {
434                                 # use attribute sets from right to left
435                                 # to avoid invalidating the offsets
436                                 # when replacing the values
437                                 my($k_offset, $k_len, $v_offset, $v_len) =
438                                         splice(@$pos, -4);
439                                 my $attrname = lc(substr($text, $k_offset, $k_len));
440                                 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
441                                 next unless $v_offset; # 0 v_offset means no value
442                                 my $v = substr($text, $v_offset, $v_len);
443                                 $v =~ s/^([\'\"])(.*)\1$/$2/;
444                                 my $new_v=urlabs($v, $urlbase);
445                                 $new_v =~ s/\"/&quot;/g; # since we quote with ""
446                                 substr($text, $v_offset, $v_len) = qq("$new_v");
447                         }
448                 }
449                 $ret.=$text;
450         }, "tagname, tokenpos, text");
451         $p->parse($html);
452         $p->eof;
453
454         return $ret;
455 } #}}}
456
457 sub remove_feeds () { #{{{
458         my $page=shift;
459
460         my %removed;
461         foreach my $id (keys %feeds) {
462                 if ($feeds{$id}->{sourcepage} eq $page) {
463                         $feeds{$id}->{remove}=1;
464                         $removed{$id}=1;
465                 }
466         }
467 } #}}}
468
469 sub pagefile ($) { #{{{
470         my $page=shift;
471
472         return "$config{srcdir}/".htmlfn($page);
473 } #}}}
474
475 sub htmlfn ($) { #{{{
476         return shift().".html";
477 } #}}}
478
479 1