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