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 $page (keys %pagestate) {
58 if (grep { $_ eq $pagesources{$page} } @$needsbuild) {
59 # Mark all feeds originating on this page as removable;
60 # preprocess will unmark those that still exist.
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 # TODO: This cleanup function could use improvement. Any newly
172 # aggregated files are left behind unrecorded, and should be deleted.
173 my $cleanup = sub { unlink($newfile) };
174 open (OUT, ">$newfile") || error("open $newfile: $!", $cleanup);
175 foreach my $data (values %feeds, values %guids) {
176 if ($data->{remove}) {
178 foreach my $guid (values %guids) {
179 if ($guid->{feed} eq $data->{name}) {
185 unlink pagefile($data->{page});
189 elsif ($data->{expired} && exists $data->{page}) {
190 unlink pagefile($data->{page});
191 delete $data->{page};
196 foreach my $field (keys %$data) {
197 if ($field eq "name" || $field eq "feed" ||
198 $field eq "guid" || $field eq "message") {
199 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
201 elsif ($field eq "tags") {
202 push @line, "tag=$_" foreach @{$data->{tags}};
205 push @line, "$field=".$data->{$field};
208 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
210 close OUT || error("save $newfile: $!", $cleanup);
211 rename($newfile, "$config{wikistatedir}/aggregate") ||
212 error("rename $newfile: $!", $cleanup);
215 sub clearstate () { #{{{
222 foreach my $feed (values %feeds) {
223 next unless $feed->{expireage} || $feed->{expirecount};
226 foreach my $item (sort { $IkiWiki::pagectime{$b->{page}} <=> $IkiWiki::pagectime{$a->{page}} }
227 grep { exists $_->{page} && $_->{feed} eq $feed->{name} && $IkiWiki::pagectime{$_->{page}} }
229 if ($feed->{expireage}) {
230 my $days_old = (time - $IkiWiki::pagectime{$item->{page}}) / 60 / 60 / 24;
231 if ($days_old > $feed->{expireage}) {
232 debug(sprintf(gettext("expiring %s (%s days old)"),
233 $item->{page}, $days_old));
237 elsif ($feed->{expirecount} &&
238 $count >= $feed->{expirecount}) {
239 debug(sprintf(gettext("expiring %s"), $item->{page}));
243 if (! $seen{$item->{page}}) {
244 $seen{$item->{page}}=1;
252 sub aggregate () { #{{{
253 eval q{use XML::Feed};
255 eval q{use URI::Fetch};
257 eval q{use HTML::Entities};
260 foreach my $feed (values %feeds) {
261 next unless $config{rebuild} ||
262 time - $feed->{lastupdate} >= $feed->{updateinterval};
263 $feed->{lastupdate}=time;
265 $feed->{message}=sprintf(gettext("processed ok at %s"),
266 displaytime($feed->{lastupdate}));
268 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
270 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
272 if (! length $feed->{feedurl}) {
273 my @urls=XML::Feed->find_feeds($feed->{url});
275 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
277 debug($feed->{message});
280 $feed->{feedurl}=pop @urls;
282 my $res=URI::Fetch->fetch($feed->{feedurl});
284 $feed->{message}=URI::Fetch->errstr;
286 debug($feed->{message});
289 if ($res->status == URI::Fetch::URI_GONE()) {
290 $feed->{message}=gettext("feed not found");
292 debug($feed->{message});
295 my $content=$res->content;
296 my $f=eval{XML::Feed->parse(\$content)};
298 # One common cause of XML::Feed crashing is a feed
299 # that contains invalid UTF-8 sequences. Convert
300 # feed to ascii to try to work around.
301 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
302 $content=Encode::decode_utf8($content);
303 $f=eval{XML::Feed->parse(\$content)};
306 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
308 debug($feed->{message});
312 $feed->{message}=XML::Feed->errstr;
314 debug($feed->{message});
318 foreach my $entry ($f->entries) {
321 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
322 link => $entry->link,
323 content => defined $entry->content->body ? $entry->content->body : "",
324 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
325 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
331 sub add_page (@) { #{{{
334 my $feed=$params{feed};
337 if (exists $guids{$params{guid}}) {
338 # updating an existing post
339 $guid=$guids{$params{guid}};
340 return if $guid->{expired};
344 $guid->{guid}=$params{guid};
345 $guids{$params{guid}}=$guid;
346 $mtime=$params{ctime};
350 # assign it an unused page
351 my $page=IkiWiki::titlepage($params{title});
352 # escape slashes and periods in title so it doesn't specify
353 # directory name or trigger ".." disallowing code.
354 $page=~s!([/.])!"__".ord($1)."__"!eg;
355 $page=$feed->{dir}."/".$page;
356 ($page)=$page=~/$config{wiki_file_regexp}/;
357 if (! defined $page || ! length $page) {
358 $page=$feed->{dir}."/item";
361 while (exists $IkiWiki::pagecase{lc $page.$c} ||
362 -e pagefile($page.$c)) {
366 # Make sure that the file name isn't too long.
367 # NB: This doesn't check for path length limits.
368 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
369 if (defined $max && length(htmlfn($page)) >= $max) {
371 $page=$feed->{dir}."/item";
372 while (exists $IkiWiki::pagecase{lc $page.$c} ||
373 -e pagefile($page.$c)) {
379 debug(sprintf(gettext("creating new page %s"), $page));
381 $guid->{feed}=$feed->{name};
383 # To write or not to write? Need to avoid writing unchanged pages
384 # to avoid unneccessary rebuilding. The mtime from rss cannot be
385 # trusted; let's use a digest.
386 eval q{use Digest::MD5 'md5_hex'};
389 my $digest=md5_hex(Encode::encode_utf8($params{content}));
390 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
391 $guid->{md5}=$digest;
394 my $template=template("aggregatepost.tmpl", blind_cache => 1);
395 $template->param(title => $params{title})
396 if defined $params{title} && length($params{title});
397 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
398 $template->param(name => $feed->{name});
399 $template->param(url => $feed->{url});
400 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
401 if defined $params{link};
402 if (ref $feed->{tags}) {
403 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
405 writefile(htmlfn($guid->{page}), $config{srcdir},
408 # Set the mtime, this lets the build process get the right creation
409 # time on record for the new page.
410 utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
413 sub htmlescape ($) { #{{{
414 # escape accidental wikilinks and preprocessor stuff
416 $html=~s/(?<!\\)\[\[/\\\[\[/g;
420 sub urlabs ($$) { #{{{
424 URI->new_abs($url, $urlbase)->as_string;
427 sub htmlabs ($$) { #{{{
428 # Convert links in html from relative to absolute.
429 # Note that this is a heuristic, which is not specified by the rss
430 # spec and may not be right for all feeds. Also, see Debian
436 my $p = HTML::Parser->new(api_version => 3);
437 $p->handler(default => sub { $ret.=join("", @_) }, "text");
438 $p->handler(start => sub {
439 my ($tagname, $pos, $text) = @_;
440 if (ref $HTML::Tagset::linkElements{$tagname}) {
442 # use attribute sets from right to left
443 # to avoid invalidating the offsets
444 # when replacing the values
445 my($k_offset, $k_len, $v_offset, $v_len) =
447 my $attrname = lc(substr($text, $k_offset, $k_len));
448 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
449 next unless $v_offset; # 0 v_offset means no value
450 my $v = substr($text, $v_offset, $v_len);
451 $v =~ s/^([\'\"])(.*)\1$/$2/;
452 my $new_v=urlabs($v, $urlbase);
453 $new_v =~ s/\"/"/g; # since we quote with ""
454 substr($text, $v_offset, $v_len) = qq("$new_v");
458 }, "tagname, tokenpos, text");
465 sub remove_feeds () { #{{{
469 foreach my $id (keys %feeds) {
470 if ($feeds{$id}->{sourcepage} eq $page) {
471 $feeds{$id}->{remove}=1;
477 sub pagefile ($) { #{{{
480 return "$config{srcdir}/".htmlfn($page);
483 sub htmlfn ($) { #{{{
484 return shift().".".$config{htmlext};