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 => "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);
27 eval q{use Getopt::Long};
29 Getopt::Long::Configure('pass_through');
30 GetOptions("aggregate" => \$config{aggregate});
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");
48 IkiWiki::unlockwiki();
52 sub needsbuild (@) { #{{{
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});
66 sub preprocess (@) { #{{{
69 foreach my $required (qw{name url}) {
70 if (! exists $params{$required}) {
71 return "[[aggregate ".sprintf(gettext("missing %s parameter"), $required)."]]";
76 my $name=$params{name};
77 if (exists $feeds{$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});
88 ($dir)=$dir=~/$config{wiki_file_regexp}/;
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};
106 push @{$feed->{tags}}, $value;
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") : "").
119 sub delete (@) { #{{{
122 # Remove feed data for removed pages.
123 foreach my $file (@files) {
124 my $page=pagename($file);
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: $!";
136 $_=IkiWiki::possibly_foolish_untaint($_);
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");
145 elsif ($field eq "tag") {
146 push @{$data->{tags}}, $val;
149 $data->{$field}=$val;
153 if (exists $data->{name}) {
154 $feeds{$data->{name}}=$data;
156 elsif (exists $data->{guid}) {
157 $guids{$data->{guid}}=$data;
167 sub savestate () { #{{{
168 eval q{use HTML::Entities};
170 my $newfile="$config{wikistatedir}/aggregate.new";
171 my $cleanup = sub { unlink($newfile) };
172 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
173 foreach my $data (values %feeds, values %guids) {
174 if ($data->{remove}) {
176 foreach my $guid (values %guids) {
177 if ($guid->{feed} eq $data->{name}) {
183 unlink pagefile($data->{page})
184 if exists $data->{page};
188 elsif ($data->{expired} && exists $data->{page}) {
189 unlink pagefile($data->{page});
190 delete $data->{page};
195 foreach my $field (keys %$data) {
196 if ($field eq "name" || $field eq "feed" ||
197 $field eq "guid" || $field eq "message") {
198 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
200 elsif ($field eq "tags") {
201 push @line, "tag=$_" foreach @{$data->{tags}};
204 push @line, "$field=".$data->{$field};
207 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
209 close OUT || error("save $newfile: $!", $cleanup);
210 rename($newfile, "$config{wikistatedir}/aggregate") ||
211 error("rename $newfile: $!", $cleanup);
214 sub clearstate () { #{{{
221 foreach my $feed (values %feeds) {
222 next unless $feed->{expireage} || $feed->{expirecount};
225 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
226 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
228 if ($feed->{expireage}) {
229 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
230 if ($days_old > $feed->{expireage}) {
231 debug(sprintf(gettext("expiring %s (%s days old)"),
232 $item->{page}, $days_old));
236 elsif ($feed->{expirecount} &&
237 $count >= $feed->{expirecount}) {
238 debug(sprintf(gettext("expiring %s"), $item->{page}));
242 if (! $seen{$item->{page}}) {
243 $seen{$item->{page}}=1;
251 sub aggregate () { #{{{
252 eval q{use XML::Feed};
254 eval q{use URI::Fetch};
256 eval q{use HTML::Entities};
259 foreach my $feed (values %feeds) {
260 next unless $config{rebuild} ||
261 time - $feed->{lastupdate} >= $feed->{updateinterval};
262 $feed->{lastupdate}=time;
264 $feed->{message}=sprintf(gettext("processed ok at %s"),
265 displaytime($feed->{lastupdate}));
267 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
269 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
271 if (! length $feed->{feedurl}) {
272 my @urls=XML::Feed->find_feeds($feed->{url});
274 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
276 debug($feed->{message});
279 $feed->{feedurl}=pop @urls;
281 my $res=URI::Fetch->fetch($feed->{feedurl});
283 $feed->{message}=URI::Fetch->errstr;
285 debug($feed->{message});
288 if ($res->status == URI::Fetch::URI_GONE()) {
289 $feed->{message}=gettext("feed not found");
291 debug($feed->{message});
294 my $content=$res->content;
295 my $f=eval{XML::Feed->parse(\$content)};
297 # One common cause of XML::Feed crashing is a feed
298 # that contains invalid UTF-8 sequences. Convert
299 # feed to ascii to try to work around.
300 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
301 $content=Encode::decode_utf8($content);
302 $f=eval{XML::Feed->parse(\$content)};
305 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
307 debug($feed->{message});
311 $feed->{message}=XML::Feed->errstr;
313 debug($feed->{message});
317 foreach my $entry ($f->entries) {
320 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
321 link => $entry->link,
322 content => defined $entry->content->body ? $entry->content->body : "",
323 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
324 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
330 sub add_page (@) { #{{{
333 my $feed=$params{feed};
336 if (exists $guids{$params{guid}}) {
337 # updating an existing post
338 $guid=$guids{$params{guid}};
339 return if $guid->{expired};
343 $guid->{guid}=$params{guid};
344 $guids{$params{guid}}=$guid;
345 $mtime=$params{ctime};
349 # assign it an unused page
350 my $page=IkiWiki::titlepage($params{title});
351 # escape slashes and periods in title so it doesn't specify
352 # directory name or trigger ".." disallowing code.
353 $page=~s!([/.])!"__".ord($1)."__"!eg;
354 $page=$feed->{dir}."/".$page;
355 ($page)=$page=~/$config{wiki_file_regexp}/;
356 if (! defined $page || ! length $page) {
357 $page=$feed->{dir}."/item";
360 while (exists $IkiWiki::pagecase{lc $page.$c} ||
361 -e pagefile($page.$c)) {
365 # Make sure that the file name isn't too long.
366 # NB: This doesn't check for path length limits.
367 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
368 if (defined $max && length(htmlfn($page)) >= $max) {
370 $page=$feed->{dir}."/item";
371 while (exists $IkiWiki::pagecase{lc $page.$c} ||
372 -e pagefile($page.$c)) {
378 debug(sprintf(gettext("creating new page %s"), $page));
380 $guid->{feed}=$feed->{name};
382 # To write or not to write? Need to avoid writing unchanged pages
383 # to avoid unneccessary rebuilding. The mtime from rss cannot be
384 # trusted; let's use a digest.
385 eval q{use Digest::MD5 'md5_hex'};
388 my $digest=md5_hex(Encode::encode_utf8($params{content}));
389 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
390 $guid->{md5}=$digest;
393 my $template=template("aggregatepost.tmpl", blind_cache => 1);
394 $template->param(title => $params{title})
395 if defined $params{title} && length($params{title});
396 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
397 $template->param(name => $feed->{name});
398 $template->param(url => $feed->{url});
399 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
400 if defined $params{link};
401 if (ref $feed->{tags}) {
402 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
404 writefile(htmlfn($guid->{page}), $config{srcdir},
407 # Set the mtime, this lets the build process get the right creation
408 # time on record for the new page.
409 utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
412 sub htmlescape ($) { #{{{
413 # escape accidental wikilinks and preprocessor stuff
415 $html=~s/(?<!\\)\[\[/\\\[\[/g;
419 sub urlabs ($$) { #{{{
423 URI->new_abs($url, $urlbase)->as_string;
426 sub htmlabs ($$) { #{{{
427 # Convert links in html from relative to absolute.
428 # Note that this is a heuristic, which is not specified by the rss
429 # spec and may not be right for all feeds. Also, see Debian
435 my $p = HTML::Parser->new(api_version => 3);
436 $p->handler(default => sub { $ret.=join("", @_) }, "text");
437 $p->handler(start => sub {
438 my ($tagname, $pos, $text) = @_;
439 if (ref $HTML::Tagset::linkElements{$tagname}) {
441 # use attribute sets from right to left
442 # to avoid invalidating the offsets
443 # when replacing the values
444 my($k_offset, $k_len, $v_offset, $v_len) =
446 my $attrname = lc(substr($text, $k_offset, $k_len));
447 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
448 next unless $v_offset; # 0 v_offset means no value
449 my $v = substr($text, $v_offset, $v_len);
450 $v =~ s/^([\'\"])(.*)\1$/$2/;
451 my $new_v=urlabs($v, $urlbase);
452 $new_v =~ s/\"/"/g; # since we quote with ""
453 substr($text, $v_offset, $v_len) = qq("$new_v");
457 }, "tagname, tokenpos, text");
464 sub remove_feeds () { #{{{
468 foreach my $id (keys %feeds) {
469 if ($feeds{$id}->{sourcepage} eq $page) {
470 $feeds{$id}->{remove}=1;
476 sub pagefile ($) { #{{{
479 return "$config{srcdir}/".htmlfn($page);
482 sub htmlfn ($) { #{{{
483 return shift().".".$config{htmlext};