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