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