]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/aggregate.pm
unfuzzy
[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 %s"),
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                 }
314                 # Make sure that the file name isn't too long. 
315                 # NB: This doesn't check for path length limits.
316                 eval q{use POSIX};
317                 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
318                 if (defined $max && length(htmlpage($page)) >= $max) {
319                         $c="";
320                         $page="item";
321                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
322                                -e pagefile($page.$c)) {
323                                 $c++
324                         }
325                 }
327                 $guid->{page}=$page;
328                 debug(sprintf(gettext("creating new page %s"), $page));
329         }
330         $guid->{feed}=$feed->{name};
331         
332         # To write or not to write? Need to avoid writing unchanged pages
333         # to avoid unneccessary rebuilding. The mtime from rss cannot be
334         # trusted; let's use a digest.
335         eval q{use Digest::MD5 'md5_hex'};
336         error($@) if $@;
337         require Encode;
338         my $digest=md5_hex(Encode::encode_utf8($params{content}));
339         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
340         $guid->{md5}=$digest;
342         # Create the page.
343         my $template=template("aggregatepost.tmpl", blind_cache => 1);
344         $template->param(title => $params{title})
345                 if defined $params{title} && length($params{title});
346         $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
347         $template->param(name => $feed->{name});
348         $template->param(url => $feed->{url});
349         $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
350                 if defined $params{link};
351         if (ref $feed->{tags}) {
352                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
353         }
354         writefile(htmlpage($guid->{page}), $config{srcdir},
355                 $template->output);
357         # Set the mtime, this lets the build process get the right creation
358         # time on record for the new page.
359         utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
360 } #}}}
362 sub htmlescape ($) { #{{{
363         # escape accidental wikilinks and preprocessor stuff
364         my $html=shift;
365         $html=~s/(?<!\\)\[\[/\\\[\[/g;
366         return $html;
367 } #}}}
369 sub urlabs ($$) { #{{{
370         my $url=shift;
371         my $urlbase=shift;
373         URI->new_abs($url, $urlbase)->as_string;
374 } #}}}
376 sub htmlabs ($$) { #{{{
377         # Convert links in html from relative to absolute.
378         # Note that this is a heuristic, which is not specified by the rss
379         # spec and may not be right for all feeds. Also, see Debian
380         # bug #381359.
381         my $html=shift;
382         my $urlbase=shift;
384         my $ret="";
385         my $p = HTML::Parser->new(api_version => 3);
386         $p->handler(default => sub { $ret.=join("", @_) }, "text");
387         $p->handler(start => sub {
388                 my ($tagname, $pos, $text) = @_;
389                 if (ref $HTML::Tagset::linkElements{$tagname}) {
390                         while (4 <= @$pos) {
391                                 # use attribute sets from right to left
392                                 # to avoid invalidating the offsets
393                                 # when replacing the values
394                                 my($k_offset, $k_len, $v_offset, $v_len) =
395                                         splice(@$pos, -4);
396                                 my $attrname = lc(substr($text, $k_offset, $k_len));
397                                 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
398                                 next unless $v_offset; # 0 v_offset means no value
399                                 my $v = substr($text, $v_offset, $v_len);
400                                 $v =~ s/^([\'\"])(.*)\1$/$2/;
401                                 my $new_v=urlabs($v, $urlbase);
402                                 $new_v =~ s/\"/&quot;/g; # since we quote with ""
403                                 substr($text, $v_offset, $v_len) = qq("$new_v");
404                         }
405                 }
406                 $ret.=$text;
407         }, "tagname, tokenpos, text");
408         $p->parse($html);
409         $p->eof;
411         return $ret;
412 } #}}}
414 sub remove_feeds () { #{{{
415         my $page=shift;
417         my %removed;
418         foreach my $id (keys %feeds) {
419                 if ($feeds{$id}->{sourcepage} eq $page) {
420                         $feeds{$id}->{remove}=1;
421                         $removed{$id}=1;
422                 }
423         }
424 } #}}}
426 sub pagefile ($) { #{{{
427         my $page=shift;
429         return "$config{srcdir}/".htmlpage($page);
430 } #}}}