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