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