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