2 # Blog aggregation plugin.
3 package IkiWiki::Plugin::aggregate;
12 use open qw{:utf8 :std};
18 hook(type => "getopt", id => "aggregate", call => \&getopt);
19 hook(type => "checkconfig", id => "aggregate", call => \&checkconfig);
20 hook(type => "filter", id => "aggregate", call => \&filter);
21 hook(type => "preprocess", id => "aggregate", call => \&preprocess);
22 hook(type => "delete", id => "aggregate", call => \&delete);
23 hook(type => "savestate", id => "aggregate", call => \&savestate);
27 eval q{use Getopt::Long};
29 Getopt::Long::Configure('pass_through');
30 GetOptions("aggregate" => \$config{aggregate});
33 sub checkconfig () { #{{{
34 my $nolock=($config{post_commit} && ! IkiWiki::commit_hook_enabled());
35 IkiWiki::lockwiki() unless $nolock;
37 if ($config{aggregate} && ! $nolock) {
43 IkiWiki::unlockwiki() unless $nolock;
48 my $page=$params{page};
50 # Mark all feeds originating on this page as removable;
51 # preprocess will unmark those that still exist.
54 return $params{content};
57 sub preprocess (@) { #{{{
60 foreach my $required (qw{name url}) {
61 if (! exists $params{$required}) {
62 return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
67 my $name=$params{name};
68 if (exists $feeds{$name}) {
75 $feed->{sourcepage}=$params{page};
76 $feed->{url}=$params{url};
77 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".IkiWiki::titlepage($params{name});
79 ($dir)=$dir=~/$config{wiki_file_regexp}/;
81 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
82 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
83 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
84 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
85 delete $feed->{remove};
86 delete $feed->{expired};
87 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
88 $feed->{numposts}=0 unless defined $feed->{numposts};
89 $feed->{newposts}=0 unless defined $feed->{newposts};
90 $feed->{message}=gettext("new feed") unless defined $feed->{message};
91 $feed->{error}=0 unless defined $feed->{error};
97 push @{$feed->{tags}}, $value;
101 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
102 ($feed->{error} ? "<em>" : "").$feed->{message}.
103 ($feed->{error} ? "</em>" : "").
104 " (".$feed->{numposts}." ".gettext("posts").
105 ($feed->{newposts} ? "; ".$feed->{newposts}.
106 " ".gettext("new") : "").
110 sub delete (@) { #{{{
113 # Remove feed data for removed pages.
114 foreach my $file (@files) {
115 my $page=pagename($file);
120 sub loadstate () { #{{{
121 if (-e "$config{wikistatedir}/aggregate") {
122 open (IN, "$config{wikistatedir}/aggregate" ||
123 die "$config{wikistatedir}/aggregate: $!");
125 $_=IkiWiki::possibly_foolish_untaint($_);
128 foreach my $i (split(/ /, $_)) {
129 my ($field, $val)=split(/=/, $i, 2);
130 if ($field eq "name" || $field eq "feed" ||
131 $field eq "guid" || $field eq "message") {
132 $data->{$field}=decode_entities($val, " \t\n");
134 elsif ($field eq "tag") {
135 push @{$data->{tags}}, $val;
138 $data->{$field}=$val;
142 if (exists $data->{name}) {
143 $feeds{$data->{name}}=$data;
145 elsif (exists $data->{guid}) {
146 $guids{$data->{guid}}=$data;
154 sub savestate () { #{{{
155 eval q{use HTML::Entities};
157 my $newfile="$config{wikistatedir}/aggregate.new";
158 # TODO: This cleanup function could use improvement. Any newly
159 # aggregated files are left behind unrecorded, and should be deleted.
160 my $cleanup = sub { unlink($newfile) };
161 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
162 foreach my $data (values %feeds, values %guids) {
163 if ($data->{remove}) {
165 foreach my $guid (values %guids) {
166 if ($guid->{feed} eq $data->{name}) {
172 unlink pagefile($data->{page});
176 elsif ($data->{expired} && exists $data->{page}) {
177 unlink pagefile($data->{page});
178 delete $data->{page};
183 foreach my $field (keys %$data) {
184 if ($field eq "name" || $field eq "feed" ||
185 $field eq "guid" || $field eq "message") {
186 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
188 elsif ($field eq "tags") {
189 push @line, "tag=$_" foreach @{$data->{tags}};
192 push @line, "$field=".$data->{$field};
195 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
197 close OUT || error("save $newfile: $!", $cleanup);
198 rename($newfile, "$config{wikistatedir}/aggregate") ||
199 error("rename $newfile: $!", $cleanup);
203 foreach my $feed (values %feeds) {
204 next unless $feed->{expireage} || $feed->{expirecount};
206 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
207 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
209 if ($feed->{expireage}) {
210 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
211 if ($days_old > $feed->{expireage}) {
212 debug(sprintf(gettext("expiring %s (%s days old)"),
213 $item->{page}, $days_old));
217 elsif ($feed->{expirecount} &&
218 $count >= $feed->{expirecount}) {
219 debug(sprintf(gettext("expiring %s"), $item->{page}));
229 sub aggregate () { #{{{
230 eval q{use XML::Feed};
232 eval q{use HTML::Entities};
235 foreach my $feed (values %feeds) {
236 next unless $config{rebuild} ||
237 time - $feed->{lastupdate} >= $feed->{updateinterval};
238 $feed->{lastupdate}=time;
240 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
242 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
244 if (! length $feed->{feedurl}) {
245 my @urls=XML::Feed->find_feeds($feed->{url});
247 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
249 debug($feed->{message});
252 $feed->{feedurl}=pop @urls;
254 my $f=eval{XML::Feed->parse(URI->new($feed->{feedurl}))};
256 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
258 debug($feed->{message});
262 $feed->{message}=XML::Feed->errstr;
264 debug($feed->{message});
268 foreach my $entry ($f->entries) {
271 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
272 link => $entry->link,
273 content => $entry->content->body,
274 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
275 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
279 $feed->{message}=sprintf(gettext("processed ok at %s"),
280 displaytime($feed->{lastupdate}));
285 sub add_page (@) { #{{{
288 my $feed=$params{feed};
291 if (exists $guids{$params{guid}}) {
292 # updating an existing post
293 $guid=$guids{$params{guid}};
294 return if $guid->{expired};
298 $guid->{guid}=$params{guid};
299 $guids{$params{guid}}=$guid;
300 $mtime=$params{ctime};
304 # assign it an unused page
305 my $page=IkiWiki::titlepage($params{title});
306 # escape slashes and periods in title so it doesn't specify
307 # directory name or trigger ".." disallowing code.
308 $page=~s!([/.])!"__".ord($1)."__"!eg;
309 $page=$feed->{dir}."/".$page;
310 ($page)=$page=~/$config{wiki_file_regexp}/;
311 if (! defined $page || ! length $page) {
312 $page=$feed->{dir}."/item";
315 while (exists $IkiWiki::pagecase{lc $page.$c} ||
316 -e pagefile($page.$c)) {
320 # Make sure that the file name isn't too long.
321 # NB: This doesn't check for path length limits.
323 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
324 if (defined $max && length(htmlfn($page)) >= $max) {
326 $page=$feed->{dir}."/item";
327 while (exists $IkiWiki::pagecase{lc $page.$c} ||
328 -e pagefile($page.$c)) {
334 debug(sprintf(gettext("creating new page %s"), $page));
336 $guid->{feed}=$feed->{name};
338 # To write or not to write? Need to avoid writing unchanged pages
339 # to avoid unneccessary rebuilding. The mtime from rss cannot be
340 # trusted; let's use a digest.
341 eval q{use Digest::MD5 'md5_hex'};
344 my $digest=md5_hex(Encode::encode_utf8($params{content}));
345 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
346 $guid->{md5}=$digest;
349 my $template=template("aggregatepost.tmpl", blind_cache => 1);
350 $template->param(title => $params{title})
351 if defined $params{title} && length($params{title});
352 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
353 $template->param(name => $feed->{name});
354 $template->param(url => $feed->{url});
355 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
356 if defined $params{link};
357 if (ref $feed->{tags}) {
358 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
360 writefile(htmlfn($guid->{page}), $config{srcdir},
363 # Set the mtime, this lets the build process get the right creation
364 # time on record for the new page.
365 utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
368 sub htmlescape ($) { #{{{
369 # escape accidental wikilinks and preprocessor stuff
371 $html=~s/(?<!\\)\[\[/\\\[\[/g;
375 sub urlabs ($$) { #{{{
379 URI->new_abs($url, $urlbase)->as_string;
382 sub htmlabs ($$) { #{{{
383 # Convert links in html from relative to absolute.
384 # Note that this is a heuristic, which is not specified by the rss
385 # spec and may not be right for all feeds. Also, see Debian
391 my $p = HTML::Parser->new(api_version => 3);
392 $p->handler(default => sub { $ret.=join("", @_) }, "text");
393 $p->handler(start => sub {
394 my ($tagname, $pos, $text) = @_;
395 if (ref $HTML::Tagset::linkElements{$tagname}) {
397 # use attribute sets from right to left
398 # to avoid invalidating the offsets
399 # when replacing the values
400 my($k_offset, $k_len, $v_offset, $v_len) =
402 my $attrname = lc(substr($text, $k_offset, $k_len));
403 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
404 next unless $v_offset; # 0 v_offset means no value
405 my $v = substr($text, $v_offset, $v_len);
406 $v =~ s/^([\'\"])(.*)\1$/$2/;
407 my $new_v=urlabs($v, $urlbase);
408 $new_v =~ s/\"/"/g; # since we quote with ""
409 substr($text, $v_offset, $v_len) = qq("$new_v");
413 }, "tagname, tokenpos, text");
420 sub remove_feeds () { #{{{
424 foreach my $id (keys %feeds) {
425 if ($feeds{$id}->{sourcepage} eq $page) {
426 $feeds{$id}->{remove}=1;
432 sub pagefile ($) { #{{{
435 return "$config{srcdir}/".htmlfn($page);
438 sub htmlfn ($) { #{{{
439 return shift().".html";