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 URI::Fetch};
234 eval q{use HTML::Entities};
237 foreach my $feed (values %feeds) {
238 next unless $config{rebuild} ||
239 time - $feed->{lastupdate} >= $feed->{updateinterval};
240 $feed->{lastupdate}=time;
242 $feed->{message}=sprintf(gettext("processed ok at %s"),
243 displaytime($feed->{lastupdate}));
245 $IkiWiki::forcerebuild{$feed->{sourcepage}}=1;
247 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
249 if (! length $feed->{feedurl}) {
250 my @urls=XML::Feed->find_feeds($feed->{url});
252 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
254 debug($feed->{message});
257 $feed->{feedurl}=pop @urls;
259 my $res=URI::Fetch->fetch($feed->{feedurl});
261 $feed->{message}=URI::Fetch->errstr;
263 debug($feed->{message});
266 if ($res->status == URI::Fetch::URI_GONE()) {
267 $feed->{message}=gettext("feed not found");
269 debug($feed->{message});
272 my $content=$res->content;
273 my $f=eval{XML::Feed->parse(\$content)};
275 # One common cause of XML::Feed crashing is a feed
276 # that contains invalid UTF-8 sequences. Convert
277 # feed to ascii to try to work around.
278 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
279 $content=Encode::decode_utf8($content);
280 $f=eval{XML::Feed->parse(\$content)};
283 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
285 debug($feed->{message});
289 $feed->{message}=XML::Feed->errstr;
291 debug($feed->{message});
295 foreach my $entry ($f->entries) {
298 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
299 link => $entry->link,
300 content => defined $entry->content->body ? $entry->content->body : "",
301 guid => defined $entry->id ? $entry->id : time."_".$feed->name,
302 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
308 sub add_page (@) { #{{{
311 my $feed=$params{feed};
314 if (exists $guids{$params{guid}}) {
315 # updating an existing post
316 $guid=$guids{$params{guid}};
317 return if $guid->{expired};
321 $guid->{guid}=$params{guid};
322 $guids{$params{guid}}=$guid;
323 $mtime=$params{ctime};
327 # assign it an unused page
328 my $page=IkiWiki::titlepage($params{title});
329 # escape slashes and periods in title so it doesn't specify
330 # directory name or trigger ".." disallowing code.
331 $page=~s!([/.])!"__".ord($1)."__"!eg;
332 $page=$feed->{dir}."/".$page;
333 ($page)=$page=~/$config{wiki_file_regexp}/;
334 if (! defined $page || ! length $page) {
335 $page=$feed->{dir}."/item";
338 while (exists $IkiWiki::pagecase{lc $page.$c} ||
339 -e pagefile($page.$c)) {
343 # Make sure that the file name isn't too long.
344 # NB: This doesn't check for path length limits.
345 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
346 if (defined $max && length(htmlfn($page)) >= $max) {
348 $page=$feed->{dir}."/item";
349 while (exists $IkiWiki::pagecase{lc $page.$c} ||
350 -e pagefile($page.$c)) {
356 debug(sprintf(gettext("creating new page %s"), $page));
358 $guid->{feed}=$feed->{name};
360 # To write or not to write? Need to avoid writing unchanged pages
361 # to avoid unneccessary rebuilding. The mtime from rss cannot be
362 # trusted; let's use a digest.
363 eval q{use Digest::MD5 'md5_hex'};
366 my $digest=md5_hex(Encode::encode_utf8($params{content}));
367 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
368 $guid->{md5}=$digest;
371 my $template=template("aggregatepost.tmpl", blind_cache => 1);
372 $template->param(title => $params{title})
373 if defined $params{title} && length($params{title});
374 $template->param(content => htmlescape(htmlabs($params{content}, $feed->{feedurl})));
375 $template->param(name => $feed->{name});
376 $template->param(url => $feed->{url});
377 $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
378 if defined $params{link};
379 if (ref $feed->{tags}) {
380 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
382 writefile(htmlfn($guid->{page}), $config{srcdir},
385 # Set the mtime, this lets the build process get the right creation
386 # time on record for the new page.
387 utime $mtime, $mtime, pagefile($guid->{page}) if defined $mtime;
390 sub htmlescape ($) { #{{{
391 # escape accidental wikilinks and preprocessor stuff
393 $html=~s/(?<!\\)\[\[/\\\[\[/g;
397 sub urlabs ($$) { #{{{
401 URI->new_abs($url, $urlbase)->as_string;
404 sub htmlabs ($$) { #{{{
405 # Convert links in html from relative to absolute.
406 # Note that this is a heuristic, which is not specified by the rss
407 # spec and may not be right for all feeds. Also, see Debian
413 my $p = HTML::Parser->new(api_version => 3);
414 $p->handler(default => sub { $ret.=join("", @_) }, "text");
415 $p->handler(start => sub {
416 my ($tagname, $pos, $text) = @_;
417 if (ref $HTML::Tagset::linkElements{$tagname}) {
419 # use attribute sets from right to left
420 # to avoid invalidating the offsets
421 # when replacing the values
422 my($k_offset, $k_len, $v_offset, $v_len) =
424 my $attrname = lc(substr($text, $k_offset, $k_len));
425 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
426 next unless $v_offset; # 0 v_offset means no value
427 my $v = substr($text, $v_offset, $v_len);
428 $v =~ s/^([\'\"])(.*)\1$/$2/;
429 my $new_v=urlabs($v, $urlbase);
430 $new_v =~ s/\"/"/g; # since we quote with ""
431 substr($text, $v_offset, $v_len) = qq("$new_v");
435 }, "tagname, tokenpos, text");
442 sub remove_feeds () { #{{{
446 foreach my $id (keys %feeds) {
447 if ($feeds{$id}->{sourcepage} eq $page) {
448 $feeds{$id}->{remove}=1;
454 sub pagefile ($) { #{{{
457 return "$config{srcdir}/".htmlfn($page);
460 sub htmlfn ($) { #{{{
461 return shift().".html";