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