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