]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/aggregate.pm
* aggregate: Only save state if it was already loaded. This didn't used to
[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 2.00;
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 => "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 } # }}}
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         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();
48                 IkiWiki::unlockwiki();
49         }
50 } #}}}
52 sub needsbuild (@) { #{{{
53         my $needsbuild=shift;
54         
55         loadstate(); # if not already loaded
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 } # }}}
66 sub preprocess (@) { #{{{
67         my %params=@_;
69         foreach my $required (qw{name url}) {
70                 if (! exists $params{$required}) {
71                         return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
72                 }
73         }
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         }
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 } # }}}
119 sub delete (@) { #{{{
120         my @files=@_;
122         # Remove feed data for removed pages.
123         foreach my $file (@files) {
124                 my $page=pagename($file);
125                 remove_feeds($page);
126         }
127 } #}}}
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                 }
161                 close IN;
162                 
163                 $state_loaded=1;
164         }
165 } #}}}
167 sub savestate () { #{{{
168         return unless $state_loaded;
169         eval q{use HTML::Entities};
170         error($@) if $@;
171         my $newfile="$config{wikistatedir}/aggregate.new";
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                                         if exists $data->{page};
186                         }
187                         next;
188                 }
189                 elsif ($data->{expired} && exists $data->{page}) {
190                         unlink pagefile($data->{page});
191                         delete $data->{page};
192                         delete $data->{md5};
193                 }
195                 my @line;
196                 foreach my $field (keys %$data) {
197                         if ($field eq "name" || $field eq "feed" ||
198                             $field eq "guid" || $field eq "message") {
199                                 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
200                         }
201                         elsif ($field eq "tags") {
202                                 push @line, "tag=$_" foreach @{$data->{tags}};
203                         }
204                         else {
205                                 push @line, "$field=".$data->{$field};
206                         }
207                 }
208                 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
209         }
210         close OUT || error("save $newfile: $!", $cleanup);
211         rename($newfile, "$config{wikistatedir}/aggregate") ||
212                 error("rename $newfile: $!", $cleanup);
213 } #}}}
215 sub clearstate () { #{{{
216         %feeds=();
217         %guids=();
218         $state_loaded=0;
219 } #}}}
221 sub expire () { #{{{
222         foreach my $feed (values %feeds) {
223                 next unless $feed->{expireage} || $feed->{expirecount};
224                 my $count=0;
225                 my %seen;
226                 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
227                                   grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
228                                   values %guids) {
229                         if ($feed->{expireage}) {
230                                 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
231                                 if ($days_old > $feed->{expireage}) {
232                                         debug(sprintf(gettext("expiring %s (%s days old)"),
233                                                 $item->{page}, int($days_old)));
234                                         $item->{expired}=1;
235                                 }
236                         }
237                         elsif ($feed->{expirecount} &&
238                                $count >= $feed->{expirecount}) {
239                                 debug(sprintf(gettext("expiring %s"), $item->{page}));
240                                 $item->{expired}=1;
241                         }
242                         else {
243                                 if (! $seen{$item->{page}}) {
244                                         $seen{$item->{page}}=1;
245                                         $count++;
246                                 }
247                         }
248                 }
249         }
250 } #}}}
252 sub aggregate () { #{{{
253         eval q{use XML::Feed};
254         error($@) if $@;
255         eval q{use URI::Fetch};
256         error($@) if $@;
257         eval q{use HTML::Entities};
258         error($@) if $@;
260         foreach my $feed (values %feeds) {
261                 next unless $config{rebuild} || 
262                         time - $feed->{lastupdate} >= $feed->{updateinterval};
263                 $feed->{lastupdate}=time;
264                 $feed->{newposts}=0;
265                 $feed->{message}=sprintf(gettext("processed ok at %s"),
266                         displaytime($feed->{lastupdate}));
267                 $feed->{error}=0;
268                 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
270                 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
272                 if (! length $feed->{feedurl}) {
273                         my @urls=XML::Feed->find_feeds($feed->{url});
274                         if (! @urls) {
275                                 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
276                                 $feed->{error}=1;
277                                 debug($feed->{message});
278                                 next;
279                         }
280                         $feed->{feedurl}=pop @urls;
281                 }
282                 my $res=URI::Fetch->fetch($feed->{feedurl});
283                 if (! $res) {
284                         $feed->{message}=URI::Fetch->errstr;
285                         $feed->{error}=1;
286                         debug($feed->{message});
287                         next;
288                 }
289                 if ($res->status == URI::Fetch::URI_GONE()) {
290                         $feed->{message}=gettext("feed not found");
291                         $feed->{error}=1;
292                         debug($feed->{message});
293                         next;
294                 }
295                 my $content=$res->content;
296                 my $f=eval{XML::Feed->parse(\$content)};
297                 if ($@) {
298                         # One common cause of XML::Feed crashing is a feed
299                         # that contains invalid UTF-8 sequences. Convert
300                         # feed to ascii to try to work around.
301                         $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
302                         $content=Encode::decode_utf8($content);
303                         $f=eval{XML::Feed->parse(\$content)};
304                 }
305                 if ($@) {
306                         $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
307                         $feed->{error}=1;
308                         debug($feed->{message});
309                         next;
310                 }
311                 if (! $f) {
312                         $feed->{message}=XML::Feed->errstr;
313                         $feed->{error}=1;
314                         debug($feed->{message});
315                         next;
316                 }
318                 foreach my $entry ($f->entries) {
319                         add_page(
320                                 feed => $feed,
321                                 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
322                                 link => $entry->link,
323                                 content => defined $entry->content->body ? $entry->content->body : "",
324                                 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
325                                 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
326                         );
327                 }
328         }
329 } #}}}
331 sub add_page (@) { #{{{
332         my %params=@_;
333         
334         my $feed=$params{feed};
335         my $guid={};
336         my $mtime;
337         if (exists $guids{$params{guid}}) {
338                 # updating an existing post
339                 $guid=$guids{$params{guid}};
340                 return if $guid->{expired};
341         }
342         else {
343                 # new post
344                 $guid->{guid}=$params{guid};
345                 $guids{$params{guid}}=$guid;
346                 $mtime=$params{ctime};
347                 $feed->{numposts}++;
348                 $feed->{newposts}++;
350                 # assign it an unused page
351                 my $page=IkiWiki::titlepage($params{title});
352                 # escape slashes and periods in title so it doesn't specify
353                 # directory name or trigger ".." disallowing code.
354                 $page=~s!([/.])!"__".ord($1)."__"!eg;
355                 $page=$feed->{dir}."/".$page;
356                 ($page)=$page=~/$config{wiki_file_regexp}/;
357                 if (! defined $page || ! length $page) {
358                         $page=$feed->{dir}."/item";
359                 }
360                 my $c="";
361                 while (exists $IkiWiki::pagecase{lc $page.$c} ||
362                        -e pagefile($page.$c)) {
363                         $c++
364                 }
366                 # Make sure that the file name isn't too long. 
367                 # NB: This doesn't check for path length limits.
368                 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
369                 if (defined $max && length(htmlfn($page)) >= $max) {
370                         $c="";
371                         $page=$feed->{dir}."/item";
372                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
373                                -e pagefile($page.$c)) {
374                                 $c++
375                         }
376                 }
378                 $guid->{page}=$page;
379                 debug(sprintf(gettext("creating new page %s"), $page));
380         }
381         $guid->{feed}=$feed->{name};
382         
383         # To write or not to write? Need to avoid writing unchanged pages
384         # to avoid unneccessary rebuilding. The mtime from rss cannot be
385         # trusted; let's use a digest.
386         eval q{use Digest::MD5 'md5_hex'};
387         error($@) if $@;
388         require Encode;
389         my $digest=md5_hex(Encode::encode_utf8($params{content}));
390         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
391         $guid->{md5}=$digest;
393         # Create the page.
394         my $template=template("aggregatepost.tmpl", blind_cache => 1);
395         $template->param(title => $params{title})
396                 if defined $params{title} && length($params{title});
397         $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
398         $template->param(name => $feed->{name});
399         $template->param(url => $feed->{url});
400         $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
401                 if defined $params{link};
402         if (ref $feed->{tags}) {
403                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
404         }
405         writefile(htmlfn($guid->{page}), $config{srcdir},
406                 $template->output);
408         # Set the mtime, this lets the build process get the right creation
409         # time on record for the new page.
410         utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
411 } #}}}
413 sub htmlescape ($) { #{{{
414         # escape accidental wikilinks and preprocessor stuff
415         my $html=shift;
416         $html=~s/(?<!\\)\[\[/\\\[\[/g;
417         return $html;
418 } #}}}
420 sub urlabs ($$) { #{{{
421         my $url=shift;
422         my $urlbase=shift;
424         URI->new_abs($url, $urlbase)->as_string;
425 } #}}}
427 sub htmlabs ($$) { #{{{
428         # Convert links in html from relative to absolute.
429         # Note that this is a heuristic, which is not specified by the rss
430         # spec and may not be right for all feeds. Also, see Debian
431         # bug #381359.
432         my $html=shift;
433         my $urlbase=shift;
435         my $ret="";
436         my $p = HTML::Parser->new(api_version => 3);
437         $p->handler(default => sub { $ret.=join("", @_) }, "text");
438         $p->handler(start => sub {
439                 my ($tagname, $pos, $text) = @_;
440                 if (ref $HTML::Tagset::linkElements{$tagname}) {
441                         while (4 <= @$pos) {
442                                 # use attribute sets from right to left
443                                 # to avoid invalidating the offsets
444                                 # when replacing the values
445                                 my($k_offset, $k_len, $v_offset, $v_len) =
446                                         splice(@$pos, -4);
447                                 my $attrname = lc(substr($text, $k_offset, $k_len));
448                                 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
449                                 next unless $v_offset; # 0 v_offset means no value
450                                 my $v = substr($text, $v_offset, $v_len);
451                                 $v =~ s/^([\'\"])(.*)\1$/$2/;
452                                 my $new_v=urlabs($v, $urlbase);
453                                 $new_v =~ s/\"/&quot;/g; # since we quote with ""
454                                 substr($text, $v_offset, $v_len) = qq("$new_v");
455                         }
456                 }
457                 $ret.=$text;
458         }, "tagname, tokenpos, text");
459         $p->parse($html);
460         $p->eof;
462         return $ret;
463 } #}}}
465 sub remove_feeds () { #{{{
466         my $page=shift;
468         my %removed;
469         foreach my $id (keys %feeds) {
470                 if ($feeds{$id}->{sourcepage} eq $page) {
471                         $feeds{$id}->{remove}=1;
472                         $removed{$id}=1;
473                 }
474         }
475 } #}}}
477 sub pagefile ($) { #{{{
478         my $page=shift;
480         return "$config{srcdir}/".htmlfn($page);
481 } #}}}
483 sub htmlfn ($) { #{{{
484         return shift().".".$config{htmlext};
485 } #}}}