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