fix
[ikiwiki] / 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
9 my %feeds;
10 my %guids;
11
12 sub import { #{{{
13         IkiWiki::hook(type => "getopt", id => "aggregate", 
14                 call => \&getopt);
15         IkiWiki::hook(type => "checkconfig", id => "aggregate",
16                 call => \&checkconfig);
17         IkiWiki::hook(type => "filter", id => "aggregate", 
18                 call => \&filter);
19         IkiWiki::hook(type => "preprocess", id => "aggregate",
20                 call => \&preprocess);
21         IkiWiki::hook(type => "delete", id => "aggregate",
22                 call => \&delete);
23         IkiWiki::hook(type => "savestate", id => "aggregate",
24                 call => \&savestate);
25 } # }}}
26
27 sub getopt () { #{{{
28         eval q{use Getopt::Long};
29         Getopt::Long::Configure('pass_through');
30         GetOptions("aggregate" => \$IkiWiki::config{aggregate});
31 } #}}}
32
33 sub checkconfig () { #{{{
34         loadstate();
35         if ($IkiWiki::config{aggregate}) {
36                 IkiWiki::loadindex();
37                 aggregate();
38                 savestate();
39         }
40 } #}}}
41
42 sub filter (@) { #{{{
43         my %params=@_;
44         my $page=$params{page};
45
46         # Mark all feeds originating on this page as removable;
47         # preprocess will unmark those that still exist.
48         remove_feeds($page);
49
50         return $params{content};
51 } # }}}
52
53 sub preprocess (@) { #{{{
54         my %params=@_;
55
56         foreach my $required (qw{name url}) {
57                 if (! exists $params{$required}) {
58                         return "[[aggregate plugin missing $required parameter]]";
59                 }
60         }
61
62         my $feed={};
63         my $name=$params{name};
64         if (exists $feeds{$name}) {
65                 $feed=$feeds{$name};
66         }
67         else {
68                 $feeds{$name}=$feed;
69         }
70         $feed->{name}=$name;
71         $feed->{sourcepage}=$params{page};
72         $feed->{url}=$params{url};
73         my $dir=exists $params{dir} ? $params{dir} : IkiWiki::titlepage($params{name});
74         $dir=~s/^\/+//;
75         ($dir)=$dir=~/$IkiWiki::config{wiki_file_regexp}/;
76         $feed->{dir}=$dir;
77         $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
78         $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
79         $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
80         $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
81         delete $feed->{remove};
82         $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
83         $feed->{numposts}=0 unless defined $feed->{numposts};
84         $feed->{newposts}=0 unless defined $feed->{newposts};
85         $feed->{message}="new feed" unless defined $feed->{message};
86         $feed->{tags}=[];
87         while (@_) {
88                 my $key=shift;
89                 my $value=shift;
90                 if ($key eq 'tag') {
91                         push @{$feed->{tags}}, $value;
92                 }
93         }
94
95         return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
96                "<i>".$feed->{message}."</i> (".$feed->{numposts}.
97                " stored posts; ".$feed->{newposts}." new)<br />";
98 } # }}}
99
100 sub delete (@) { #{{{
101         my @files=@_;
102
103         # Remove feed data for removed pages.
104         foreach my $file (@files) {
105                 my $page=IkiWiki::pagename($file);
106                 remove_feeds($page);
107         }
108 } #}}}
109
110 sub loadstate () { #{{{
111         eval q{use HTML::Entities};
112         die $@ if $@;
113         if (-e "$IkiWiki::config{wikistatedir}/aggregate") {
114                 open (IN, "$IkiWiki::config{wikistatedir}/aggregate" ||
115                         die "$IkiWiki::config{wikistatedir}/aggregate: $!");
116                 while (<IN>) {
117                         $_=IkiWiki::possibly_foolish_untaint($_);
118                         chomp;
119                         my $data={};
120                         foreach my $i (split(/ /, $_)) {
121                                 my ($field, $val)=split(/=/, $i, 2);
122                                 if ($field eq "name" || $field eq "feed" ||
123                                     $field eq "guid" || $field eq "message") {
124                                         $data->{$field}=decode_entities($val, " \t\n");
125                                 }
126                                 elsif ($field eq "tag") {
127                                         push @{$data->{tags}}, $val;
128                                 }
129                                 else {
130                                         $data->{$field}=$val;
131                                 }
132                         }
133                         
134                         if (exists $data->{name}) {
135                                 $feeds{$data->{name}}=$data;
136                         }
137                         elsif (exists $data->{guid}) {
138                                 $guids{$data->{guid}}=$data;
139                         }
140                 }
141
142                 close IN;
143         }
144 } #}}}
145
146 sub savestate () { #{{{
147         eval q{use HTML::Entities};
148         die $@ if $@;
149         open (OUT, ">$IkiWiki::config{wikistatedir}/aggregate" ||
150                 die "$IkiWiki::config{wikistatedir}/aggregate: $!");
151         foreach my $data (values %feeds, values %guids) {
152                 if ($data->{remove}) {
153                         if ($data->{name}) {
154                                 foreach my $guid (values %guids) {
155                                         if ($guid->{feed} eq $data->{name}) {
156                                                 $guid->{remove}=1;
157                                         }
158                                 }
159                         }
160                         else {
161                                 unlink pagefile($data->{page});
162                         }
163                         next;
164                 }
165
166                 my @line;
167                 foreach my $field (keys %$data) {
168                         if ($field eq "name" || $field eq "feed" ||
169                             $field eq "guid" || $field eq "message") {
170                                 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
171                         }
172                         elsif ($field eq "tags") {
173                                 push @line, "tag=$_" foreach @{$data->{tags}};
174                         }
175                         else {
176                                 push @line, "$field=".$data->{$field};
177                         }
178                 }
179                 print OUT join(" ", @line)."\n";
180         }
181         close OUT;
182 } #}}}
183
184 sub aggregate () { #{{{
185         eval q{use XML::Feed};
186         die $@ if $@;
187         eval q{use HTML::Entities};
188         die $@ if $@;
189
190         foreach my $feed (values %feeds) {
191                 next unless time - $feed->{lastupdate} >= $feed->{updateinterval};
192                 $feed->{lastupdate}=time;
193                 $feed->{newposts}=0;
194                 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
195
196                 IkiWiki::debug("checking feed ".$feed->{name}." ...");
197
198                 if (! length $feed->{feedurl}) {
199                         my @urls=XML::Feed->find_feeds($feed->{url});
200                         if (! @urls) {
201                                 $feed->{message}="could not find feed at ".$feed->{feedurl};
202                                 IkiWiki::debug($feed->{message});
203                                 next;
204                         }
205                         $feed->{feedurl}=pop @urls;
206                 }
207                 my $f=eval{XML::Feed->parse(URI->new($feed->{feedurl}))};
208                 if ($@) {
209                         $feed->{message}="feed crashed XML::Feed! $@";
210                         IkiWiki::debug($feed->{message});
211                         next;
212                 }
213                 if (! $f) {
214                         $feed->{message}=XML::Feed->errstr;
215                         IkiWiki::debug($feed->{message});
216                         next;
217                 }
218
219                 foreach my $entry ($f->entries) {
220                         add_page(
221                                 feed => $feed,
222                                 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
223                                 link => $entry->link,
224                                 content => $entry->content->body,
225                                 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
226                                 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
227                         );
228                 }
229
230                 $feed->{message}="processed ok";
231         }
232
233         # TODO: expiry
234 } #}}}
235
236 sub add_page (@) { #{{{
237         my %params=@_;
238         
239         my $feed=$params{feed};
240         my $guid={};
241         my $mtime;
242         if (exists $guids{$params{guid}}) {
243                 # updating an existing post
244                 $guid=$guids{$params{guid}};
245         }
246         else {
247                 # new post
248                 $guid->{guid}=$params{guid};
249                 $guids{$params{guid}}=$guid;
250                 $mtime=$params{ctime};
251                 $feed->{numposts}++;
252                 $feed->{newposts}++;
253
254                 # assign it an unused page
255                 my $page=$feed->{dir}."/".IkiWiki::titlepage($params{title});
256                 $page=lc($page);
257                 ($page)=$page=~/$IkiWiki::config{wiki_file_regexp}/;
258                 if (! defined $page || ! length $page) {
259                         $page=$feed->{dir}."/item";
260                 }
261                 $page=~s/\.\.//g; # avoid ".." directory tricks
262                 my $c="";
263                 while (exists $IkiWiki::pagesources{$page.$c} ||
264                        -e pagefile($page.$c)) {
265                         $c++
266                 }
267                 $guid->{page}=$page;
268                 IkiWiki::debug("creating new page $page");
269         }
270         $guid->{feed}=$feed->{name};
271         
272         # To write or not to write? Need to avoid writing unchanged pages
273         # to avoid unneccessary rebuilding. The mtime from rss cannot be
274         # trusted; let's use a digest.
275         eval q{use Digest::MD5 'md5_hex'};
276         require Encode;
277         my $digest=md5_hex(Encode::encode_utf8($params{content}));
278         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest;
279         $guid->{md5}=$digest;
280
281         # Create the page.
282         my $template=IkiWiki::template("aggregatepost.tmpl", blind_cache => 1);
283         my $content=$params{content};
284         $params{content}=~s/(?<!\\)\[\[/\\\[\[/g; # escape accidental wikilinks
285                                                   # and preprocessor stuff
286         $template->param(content => $params{content});
287         $template->param(url => $feed->{url});
288         $template->param(name => $feed->{name});
289         $template->param(link => $params{link}) if defined $params{link};
290         if (ref $feed->{tags}) {
291                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
292         }
293         IkiWiki::writefile($guid->{page}.".html", $IkiWiki::config{srcdir},
294                 $template->output);
295
296         # Set the mtime, this lets the build process get the right creation
297         # time on record for the new page.
298         utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
299 } #}}}
300
301 sub remove_feeds () { #{{{
302         my $page=shift;
303
304         my %removed;
305         foreach my $id (keys %feeds) {
306                 if ($feeds{$id}->{sourcepage} eq $page) {
307                         $feeds{$id}->{remove}=1;
308                         $removed{$id}=1;
309                 }
310         }
311 } #}}}
312
313 sub pagefile ($) { #{{{
314         my $page=shift;
315
316         return "$IkiWiki::config{srcdir}/$page.html";
317 } #}}}
318
319 1