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