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