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