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