web commit by AlexandreDupas: Proposition for a plugin displaying bibtex files
[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         loadstate(); # if not already loaded
56
57         foreach my $feed (values %feeds) {
58                 if (grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
59                         # Mark all feeds originating on this page as removable;
60                         # preprocess will unmark those that still exist.
61                         remove_feeds($feed->{sourcepage});
62                 }
63         }
64 } # }}}
65
66 sub preprocess (@) { #{{{
67         my %params=@_;
68
69         foreach my $required (qw{name url}) {
70                 if (! exists $params{$required}) {
71                         return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
72                 }
73         }
74
75         my $feed={};
76         my $name=$params{name};
77         if (exists $feeds{$name}) {
78                 $feed=$feeds{$name};
79         }
80         else {
81                 $feeds{$name}=$feed;
82         }
83         $feed->{name}=$name;
84         $feed->{sourcepage}=$params{page};
85         $feed->{url}=$params{url};
86         my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
87         $dir=~s/^\/+//;
88         ($dir)=$dir=~/$config{wiki_file_regexp}/;
89         $feed->{dir}=$dir;
90         $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
91         $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
92         $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
93         $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
94         delete $feed->{remove};
95         delete $feed->{expired};
96         $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
97         $feed->{numposts}=0 unless defined $feed->{numposts};
98         $feed->{newposts}=0 unless defined $feed->{newposts};
99         $feed->{message}=gettext("new feed") unless defined $feed->{message};
100         $feed->{error}=0 unless defined $feed->{error};
101         $feed->{tags}=[];
102         while (@_) {
103                 my $key=shift;
104                 my $value=shift;
105                 if ($key eq 'tag') {
106                         push @{$feed->{tags}}, $value;
107                 }
108         }
109
110         return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
111                ($feed->{error} ? "<em>" : "").$feed->{message}.
112                ($feed->{error} ? "</em>" : "").
113                " (".$feed->{numposts}." ".gettext("posts").
114                ($feed->{newposts} ? "; ".$feed->{newposts}.
115                                     " ".gettext("new") : "").
116                ")";
117 } # }}}
118
119 sub delete (@) { #{{{
120         my @files=@_;
121
122         # Remove feed data for removed pages.
123         foreach my $file (@files) {
124                 my $page=pagename($file);
125                 remove_feeds($page);
126         }
127 } #}}}
128
129 my $state_loaded=0;
130 sub loadstate () { #{{{
131         return if $state_loaded;
132         if (-e "$config{wikistatedir}/aggregate") {
133                 open(IN, "$config{wikistatedir}/aggregate") ||
134                         die "$config{wikistatedir}/aggregate: $!";
135                 while (<IN>) {
136                         $_=IkiWiki::possibly_foolish_untaint($_);
137                         chomp;
138                         my $data={};
139                         foreach my $i (split(/ /, $_)) {
140                                 my ($field, $val)=split(/=/, $i, 2);
141                                 if ($field eq "name" || $field eq "feed" ||
142                                     $field eq "guid" || $field eq "message") {
143                                         $data->{$field}=decode_entities($val, " \t\n");
144                                 }
145                                 elsif ($field eq "tag") {
146                                         push @{$data->{tags}}, $val;
147                                 }
148                                 else {
149                                         $data->{$field}=$val;
150                                 }
151                         }
152                         
153                         if (exists $data->{name}) {
154                                 $feeds{$data->{name}}=$data;
155                         }
156                         elsif (exists $data->{guid}) {
157                                 $guids{$data->{guid}}=$data;
158                         }
159                 }
160
161                 close IN;
162                 
163                 $state_loaded=1;
164         }
165 } #}}}
166
167 sub savestate () { #{{{
168         eval q{use HTML::Entities};
169         error($@) if $@;
170         my $newfile="$config{wikistatedir}/aggregate.new";
171         my $cleanup = sub { unlink($newfile) };
172         open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
173         foreach my $data (values %feeds, values %guids) {
174                 if ($data->{remove}) {
175                         if ($data->{name}) {
176                                 foreach my $guid (values %guids) {
177                                         if ($guid->{feed} eq $data->{name}) {
178                                                 $guid->{remove}=1;
179                                         }
180                                 }
181                         }
182                         else {
183                                 unlink pagefile($data->{page})
184                                         if exists $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