]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/aggregate.pm
Added a comment
[git.ikiwiki.info.git] / IkiWiki / Plugin / aggregate.pm
1 #!/usr/bin/perl
2 # Feed aggregation plugin.
3 package IkiWiki::Plugin::aggregate;
5 use warnings;
6 use strict;
7 use IkiWiki 3.00;
8 use HTML::Parser;
9 use HTML::Tagset;
10 use HTML::Entities;
11 use open qw{:utf8 :std};
13 my %feeds;
14 my %guids;
16 sub import {
17         hook(type => "getopt", id => "aggregate", call => \&getopt);
18         hook(type => "getsetup", id => "aggregate", call => \&getsetup);
19         hook(type => "checkconfig", id => "aggregate", call => \&checkconfig,
20                 last => 1);
21         hook(type => "needsbuild", id => "aggregate", call => \&needsbuild);
22         hook(type => "preprocess", id => "aggregate", call => \&preprocess);
23         hook(type => "delete", id => "aggregate", call => \&delete);
24         hook(type => "savestate", id => "aggregate", call => \&savestate);
25         hook(type => "htmlize", id => "_aggregated", call => \&htmlize);
26         if (exists $config{aggregate_webtrigger} && $config{aggregate_webtrigger}) {
27                 hook(type => "cgi", id => "aggregate", call => \&cgi);
28         }
29 }
31 sub getopt () {
32         eval q{use Getopt::Long};
33         error($@) if $@;
34         Getopt::Long::Configure('pass_through');
35         GetOptions(
36                 "aggregate" => \$config{aggregate},
37                 "aggregateinternal!" => \$config{aggregateinternal},
38         );
39 }
41 sub getsetup () {
42         return
43                 plugin => {
44                         safe => 1,
45                         rebuild => undef,
46                 },
47                 aggregateinternal => {
48                         type => "boolean",
49                         example => 1,
50                         description => "enable aggregation to internal pages?",
51                         safe => 0, # enabling needs manual transition
52                         rebuild => 0,
53                 },
54                 aggregate_webtrigger => {
55                         type => "boolean",
56                         example => 0,
57                         description => "allow aggregation to be triggered via the web?",
58                         safe => 1,
59                         rebuild => 0,
60                 },
61 }
63 sub checkconfig () {
64         if (! defined $config{aggregateinternal}) {
65                 $config{aggregateinternal}=1;
66         }
68         # This is done here rather than in a refresh hook because it
69         # needs to run before the wiki is locked.
70         if ($config{aggregate} && ! ($config{post_commit} && 
71                                      IkiWiki::commit_hook_enabled())) {
72                 launchaggregation();
73         }
74 }
76 sub cgi ($) {
77         my $cgi=shift;
79         if (defined $cgi->param('do') &&
80             $cgi->param("do") eq "aggregate_webtrigger") {
81                 $|=1;
82                 print "Content-Type: text/plain\n\n";
83                 $config{cgi}=0;
84                 $config{verbose}=1;
85                 $config{syslog}=0;
86                 print gettext("Aggregation triggered via web.")."\n\n";
87                 if (launchaggregation()) {
88                         IkiWiki::lockwiki();
89                         IkiWiki::loadindex();
90                         require IkiWiki::Render;
91                         IkiWiki::refresh();
92                         IkiWiki::saveindex();
93                 }
94                 else {
95                         print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
96                 }
97                 exit 0;
98         }
99 }
101 sub launchaggregation () {
102         # See if any feeds need aggregation.
103         loadstate();
104         my @feeds=needsaggregate();
105         return unless @feeds;
106         if (! lockaggregate()) {
107                 error("an aggregation process is already running");
108         }
109         # force a later rebuild of source pages
110         $IkiWiki::forcerebuild{$_->{sourcepage}}=1
111                 foreach @feeds;
113         # Fork a child process to handle the aggregation.
114         # The parent process will then handle building the
115         # result. This avoids messy code to clear state
116         # accumulated while aggregating.
117         defined(my $pid = fork) or error("Can't fork: $!");
118         if (! $pid) {
119                 IkiWiki::loadindex();
120                 # Aggregation happens without the main wiki lock
121                 # being held. This allows editing pages etc while
122                 # aggregation is running.
123                 aggregate(@feeds);
125                 IkiWiki::lockwiki;
126                 # Merge changes, since aggregation state may have
127                 # changed on disk while the aggregation was happening.
128                 mergestate();
129                 expire();
130                 savestate();
131                 IkiWiki::unlockwiki;
132                 exit 0;
133         }
134         waitpid($pid,0);
135         if ($?) {
136                 error "aggregation failed with code $?";
137         }
139         clearstate();
140         unlockaggregate();
142         return 1;
145 #  Pages with extension _aggregated have plain html markup, pass through.
146 sub htmlize (@) {
147         my %params=@_;
148         return $params{content};
151 # Used by ikiwiki-transition aggregateinternal.
152 sub migrate_to_internal {
153         if (! lockaggregate()) {
154                 error("an aggregation process is currently running");
155         }
157         IkiWiki::lockwiki();
158         loadstate();
159         $config{verbose}=1;
161         foreach my $data (values %guids) {
162                 next unless $data->{page};
163                 next if $data->{expired};
164                 
165                 $config{aggregateinternal} = 0;
166                 my $oldname = "$config{srcdir}/".htmlfn($data->{page});
167                 if (! -e $oldname) {
168                         $oldname = $IkiWiki::Plugin::transient::transientdir."/".htmlfn($data->{page});
169                 }
171                 my $oldoutput = $config{destdir}."/".IkiWiki::htmlpage($data->{page});
172                 
173                 $config{aggregateinternal} = 1;
174                 my $newname = $IkiWiki::Plugin::transient::transientdir."/".htmlfn($data->{page});
175                 
176                 debug "moving $oldname -> $newname";
177                 if (-e $newname) {
178                         if (-e $oldname) {
179                                 error("$newname already exists");
180                         }
181                         else {
182                                 debug("already renamed to $newname?");
183                         }
184                 }
185                 elsif (-e $oldname) {
186                         rename($oldname, $newname) || error("$!");
187                 }
188                 else {
189                         debug("$oldname not found");
190                 }
191                 if (-e $oldoutput) {
192                         require IkiWiki::Render;
193                         debug("removing output file $oldoutput");
194                         IkiWiki::prune($oldoutput, $config{destdir});
195                 }
196         }
197         
198         savestate();
199         IkiWiki::unlockwiki;
200         
201         unlockaggregate();
204 sub needsbuild (@) {
205         my $needsbuild=shift;
206         
207         loadstate();
209         foreach my $feed (values %feeds) {
210                 if (exists $pagesources{$feed->{sourcepage}} && 
211                     grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
212                         # Mark all feeds originating on this page as 
213                         # not yet seen; preprocess will unmark those that
214                         # still exist.
215                         markunseen($feed->{sourcepage});
216                 }
217         }
219         return $needsbuild;
222 sub preprocess (@) {
223         my %params=@_;
225         foreach my $required (qw{name url}) {
226                 if (! exists $params{$required}) {
227                         error sprintf(gettext("missing %s parameter"), $required)
228                 }
229         }
231         my $feed={};
232         my $name=$params{name};
233         if (exists $feeds{$name}) {
234                 $feed=$feeds{$name};
235         }
236         else {
237                 $feeds{$name}=$feed;
238         }
239         $feed->{name}=$name;
240         $feed->{sourcepage}=$params{page};
241         $feed->{url}=$params{url};
242         my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
243         $dir=~s/^\/+//;
244         ($dir)=$dir=~/$config{wiki_file_regexp}/;
245         $feed->{dir}=$dir;
246         $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
247         $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
248         $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
249         $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
250         if (exists $params{template}) {
251                 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
252         }
253         else {
254                 $params{template} = "aggregatepost"
255         }
256         $feed->{template}=$params{template} . ".tmpl";
257         delete $feed->{unseen};
258         $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
259         $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
260         $feed->{numposts}=0 unless defined $feed->{numposts};
261         $feed->{newposts}=0 unless defined $feed->{newposts};
262         $feed->{message}=gettext("new feed") unless defined $feed->{message};
263         $feed->{error}=0 unless defined $feed->{error};
264         $feed->{tags}=[];
265         while (@_) {
266                 my $key=shift;
267                 my $value=shift;
268                 if ($key eq 'tag') {
269                         push @{$feed->{tags}}, $value;
270                 }
271         }
273         return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
274                ($feed->{error} ? "<em>" : "").$feed->{message}.
275                ($feed->{error} ? "</em>" : "").
276                " (".$feed->{numposts}." ".gettext("posts").
277                ($feed->{newposts} ? "; ".$feed->{newposts}.
278                                     " ".gettext("new") : "").
279                ")";
282 sub delete (@) {
283         my @files=@_;
285         # Remove feed data for removed pages.
286         foreach my $file (@files) {
287                 my $page=pagename($file);
288                 markunseen($page);
289         }
292 sub markunseen ($) {
293         my $page=shift;
295         foreach my $id (keys %feeds) {
296                 if ($feeds{$id}->{sourcepage} eq $page) {
297                         $feeds{$id}->{unseen}=1;
298                 }
299         }
302 my $state_loaded=0;
304 sub loadstate () {
305         return if $state_loaded;
306         $state_loaded=1;
307         if (-e "$config{wikistatedir}/aggregate") {
308                 open(IN, "<", "$config{wikistatedir}/aggregate") ||
309                         die "$config{wikistatedir}/aggregate: $!";
310                 while (<IN>) {
311                         $_=IkiWiki::possibly_foolish_untaint($_);
312                         chomp;
313                         my $data={};
314                         foreach my $i (split(/ /, $_)) {
315                                 my ($field, $val)=split(/=/, $i, 2);
316                                 if ($field eq "name" || $field eq "feed" ||
317                                     $field eq "guid" || $field eq "message") {
318                                         $data->{$field}=decode_entities($val, " \t\n");
319                                 }
320                                 elsif ($field eq "tag") {
321                                         push @{$data->{tags}}, $val;
322                                 }
323                                 else {
324                                         $data->{$field}=$val;
325                                 }
326                         }
327                         
328                         if (exists $data->{name}) {
329                                 $feeds{$data->{name}}=$data;
330                         }
331                         elsif (exists $data->{guid}) {
332                                 $guids{$data->{guid}}=$data;
333                         }
334                 }
336                 close IN;
337         }
340 sub savestate () {
341         return unless $state_loaded;
342         garbage_collect();
343         my $newfile="$config{wikistatedir}/aggregate.new";
344         my $cleanup = sub { unlink($newfile) };
345         open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
346         foreach my $data (values %feeds, values %guids) {
347                 my @line;
348                 foreach my $field (keys %$data) {
349                         if ($field eq "name" || $field eq "feed" ||
350                             $field eq "guid" || $field eq "message") {
351                                 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
352                         }
353                         elsif ($field eq "tags") {
354                                 push @line, "tag=$_" foreach @{$data->{tags}};
355                         }
356                         else {
357                                 push @line, "$field=".$data->{$field}
358                                         if defined $data->{$field};
359                         }
360                 }
361                 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
362         }
363         close OUT || error("save $newfile: $!", $cleanup);
364         rename($newfile, "$config{wikistatedir}/aggregate") ||
365                 error("rename $newfile: $!", $cleanup);
367         my $timestamp=undef;
368         foreach my $feed (keys %feeds) {
369                 my $t=$feeds{$feed}->{lastupdate}+$feeds{$feed}->{updateinterval};
370                 if (! defined $timestamp || $timestamp > $t) {
371                         $timestamp=$t;
372                 }
373         }
374         $newfile=~s/\.new$/time/;
375         open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
376         if (defined $timestamp) {
377                 print OUT $timestamp."\n";
378         }
379         close OUT || error("save $newfile: $!", $cleanup);
382 sub garbage_collect () {
383         foreach my $name (keys %feeds) {
384                 # remove any feeds that were not seen while building the pages
385                 # that used to contain them
386                 if ($feeds{$name}->{unseen}) {
387                         delete $feeds{$name};
388                 }
389         }
391         foreach my $guid (values %guids) {
392                 # any guid whose feed is gone should be removed
393                 if (! exists $feeds{$guid->{feed}}) {
394                         if (exists $guid->{page}) {
395                                 unlink $IkiWiki::Plugin::transient::transientdir."/".htmlfn($guid->{page})
396                                         || unlink "$config{srcdir}/".htmlfn($guid->{page});
397                         }
398                         delete $guids{$guid->{guid}};
399                 }
400                 # handle expired guids
401                 elsif ($guid->{expired} && exists $guid->{page}) {
402                         unlink "$config{srcdir}/".htmlfn($guid->{page});
403                         unlink $IkiWiki::Plugin::transient::transientdir."/".htmlfn($guid->{page});
404                         delete $guid->{page};
405                         delete $guid->{md5};
406                 }
407         }
410 sub mergestate () {
411         # Load the current state in from disk, and merge into it
412         # values from the state in memory that might have changed
413         # during aggregation.
414         my %myfeeds=%feeds;
415         my %myguids=%guids;
416         clearstate();
417         loadstate();
419         # All that can change in feed state during aggregation is a few
420         # fields.
421         foreach my $name (keys %myfeeds) {
422                 if (exists $feeds{$name}) {
423                         foreach my $field (qw{message lastupdate lasttry
424                                               numposts newposts error}) {
425                                 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
426                         }
427                 }
428         }
430         # New guids can be created during aggregation.
431         # Guids have a few fields that may be updated during aggregation.
432         # It's also possible that guids were removed from the on-disk state
433         # while the aggregation was in process. That would only happen if
434         # their feed was also removed, so any removed guids added back here
435         # will be garbage collected later.
436         foreach my $guid (keys %myguids) {
437                 if (! exists $guids{$guid}) {
438                         $guids{$guid}=$myguids{$guid};
439                 }
440                 else {
441                         foreach my $field (qw{md5}) {
442                                 $guids{$guid}->{$field}=$myguids{$guid}->{$field};
443                         }
444                 }
445         }
448 sub clearstate () {
449         %feeds=();
450         %guids=();
451         $state_loaded=0;
454 sub expire () {
455         foreach my $feed (values %feeds) {
456                 next unless $feed->{expireage} || $feed->{expirecount};
457                 my $count=0;
458                 my %seen;
459                 foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
460                                   grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
461                                   values %guids) {
462                         if ($feed->{expireage}) {
463                                 my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
464                                 if ($days_old > $feed->{expireage}) {
465                                         debug(sprintf(gettext("expiring %s (%s days old)"),
466                                                 $item->{page}, int($days_old)));
467                                         $item->{expired}=1;
468                                 }
469                         }
470                         elsif ($feed->{expirecount} &&
471                                $count >= $feed->{expirecount}) {
472                                 debug(sprintf(gettext("expiring %s"), $item->{page}));
473                                 $item->{expired}=1;
474                         }
475                         else {
476                                 if (! $seen{$item->{page}}) {
477                                         $seen{$item->{page}}=1;
478                                         $count++;
479                                 }
480                         }
481                 }
482         }
485 sub needsaggregate () {
486         return values %feeds if $config{rebuild};
487         return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
490 sub aggregate (@) {
491         eval q{use Net::INET6Glue::INET_is_INET6}; # may not be available
492         eval q{use XML::Feed};
493         error($@) if $@;
494         eval q{use URI::Fetch};
495         error($@) if $@;
497         foreach my $feed (@_) {
498                 $feed->{lasttry}=time;
499                 $feed->{newposts}=0;
500                 $feed->{message}=sprintf(gettext("last checked %s"),
501                         displaytime($feed->{lasttry}));
502                 $feed->{error}=0;
504                 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
506                 if (! length $feed->{feedurl}) {
507                         my @urls=XML::Feed->find_feeds($feed->{url});
508                         if (! @urls) {
509                                 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
510                                 $feed->{error}=1;
511                                 debug($feed->{message});
512                                 next;
513                         }
514                         $feed->{feedurl}=pop @urls;
515                 }
516                 # Using the for_url parameter makes sure we crash if used
517                 # with an older IkiWiki.pm that didn't automatically try
518                 # to use LWPx::ParanoidAgent.
519                 my $ua=useragent(for_url => $feed->{feedurl});
520                 my $res=URI::Fetch->fetch($feed->{feedurl}, UserAgent=>$ua);
521                 if (! $res) {
522                         $feed->{message}=URI::Fetch->errstr;
523                         $feed->{error}=1;
524                         debug($feed->{message});
525                         next;
526                 }
528                 # lastupdate is only set if we were able to contact the server
529                 $feed->{lastupdate}=$feed->{lasttry};
531                 if ($res->status == URI::Fetch::URI_GONE()) {
532                         $feed->{message}=gettext("feed not found");
533                         $feed->{error}=1;
534                         debug($feed->{message});
535                         next;
536                 }
537                 my $content=$res->content;
538                 my $f=eval{XML::Feed->parse(\$content)};
539                 if ($@) {
540                         # One common cause of XML::Feed crashing is a feed
541                         # that contains invalid UTF-8 sequences. Convert
542                         # feed to ascii to try to work around.
543                         $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
544                         $f=eval {
545                                 $content=Encode::decode_utf8($content, 0);
546                                 XML::Feed->parse(\$content)
547                         };
548                 }
549                 if ($@) {
550                         # Another possibility is badly escaped entities.
551                         $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
552                         $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
553                         $f=eval {
554                                 $content=Encode::decode_utf8($content, 0);
555                                 XML::Feed->parse(\$content)
556                         };
557                 }
558                 if ($@) {
559                         # gettext can clobber $@
560                         my $error = $@;
561                         $feed->{message}=gettext("feed crashed XML::Feed!")." ($error)";
562                         $feed->{error}=1;
563                         debug($feed->{message});
564                         next;
565                 }
566                 if (! $f) {
567                         $feed->{message}=XML::Feed->errstr;
568                         $feed->{error}=1;
569                         debug($feed->{message});
570                         next;
571                 }
573                 foreach my $entry ($f->entries) {
574                         # XML::Feed doesn't work around XML::Atom's bizarre
575                         # API, so we will. Real unicode strings? Yes please.
576                         # See [[bugs/Aggregated_Atom_feeds_are_double-encoded]]
577                         no warnings 'once';
578                         local $XML::Atom::ForceUnicode = 1;
579                         use warnings;
581                         my $c=$entry->content;
582                         # atom feeds may have no content, only a summary
583                         if (! defined $c && ref $entry->summary) {
584                                 $c=$entry->summary;
585                         }
587                         add_page(
588                                 feed => $feed,
589                                 copyright => $f->copyright,
590                                 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
591                                 author => defined $entry->author ? decode_entities($entry->author) : "",
592                                 link => $entry->link,
593                                 enclosureurl => defined $entry->enclosure ? $entry->enclosure->url : "",
594                                 enclosureimage => (defined $entry->enclosure && $entry->enclosure->type =~ m/image\//) ? "1" : "",
595                                 enclosureaudio => (defined $entry->enclosure && $entry->enclosure->type =~ m/audio\//) ? "1" : "",
596                                 enclosurevideo => (defined $entry->enclosure && $entry->enclosure->type =~ m/video\//) ? "1" : "",
597                                 content => (defined $c && defined $c->body) ? $c->body : "",
598                                 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
599                                 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
600                                 base => (defined $c && $c->can("base")) ? $c->base : undef,
601                         );
602                 }
603         }
606 sub add_page (@) {
607         my %params=@_;
608         
609         my $feed=$params{feed};
610         my $guid={};
611         my $mtime;
612         if (exists $guids{$params{guid}}) {
613                 # updating an existing post
614                 $guid=$guids{$params{guid}};
615                 return if $guid->{expired};
616                 write_page($feed, $guid, $mtime, \%params);
617         }
618         else {
619                 # new post
620                 $guid->{guid}=$params{guid};
621                 $guids{$params{guid}}=$guid;
622                 $mtime=$params{ctime};
623                 $feed->{numposts}++;
624                 $feed->{newposts}++;
626                 # assign it an unused page
627                 my $page=titlepage($params{title});
628                 # escape slashes and periods in title so it doesn't specify
629                 # directory name or trigger ".." disallowing code.
630                 $page=~s!([/.])!"__".ord($1)."__"!eg;
631                 if (! defined $page || ! length $page) {
632                         $page=$feed->{dir}."/item";
633                 }
634                 $page=$feed->{dir}."/".$page;
635                 ($page)=$page=~/$config{wiki_file_regexp}/;
636                 my $c="";
637                 while (exists $IkiWiki::pagecase{lc $page.$c} ||
638                        -e $IkiWiki::Plugin::transient::transientdir."/".htmlfn($page.$c) ||
639                        -e "$config{srcdir}/".htmlfn($page.$c)) {
640                         $c++
641                 }
642                 $page=$page.$c;
644                 $guid->{page}=$page;
645                 eval { write_page($feed, $guid, $mtime, \%params) };
646                 if ($@) {
647                         # assume failure was due to a too long filename
648                         $c="";
649                         $page=$feed->{dir}."/item";
650                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
651                               -e $IkiWiki::Plugin::transient::transientdir."/".htmlfn($page.$c) ||
652                               -e "$config{srcdir}/".htmlfn($page.$c)) {
653                                 $c++
654                         }
655                         $page=$page.$c;
657                         $guid->{page}=$page;
658                         write_page($feed, $guid, $mtime, \%params);
659                 }
661                 debug(sprintf(gettext("creating new page %s"), $page));
662         }
665 sub write_page ($$$$$) {
666         my $feed=shift;
667         my $guid=shift;
668         my $mtime=shift;
669         my %params=%{shift()};
671         $guid->{feed}=$feed->{name};
672         
673         # To write or not to write? Need to avoid writing unchanged pages
674         # to avoid unneccessary rebuilding. The mtime from rss cannot be
675         # trusted; let's use a digest.
676         eval q{use Digest::MD5 'md5_hex'};
677         error($@) if $@;
678         require Encode;
679         my $digest=md5_hex(Encode::encode_utf8($params{content}));
680         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
681         $guid->{md5}=$digest;
683         # Create the page.
684         my $template;
685         eval {
686                 $template=template($feed->{template}, blind_cache => 1);
687         };
688         if ($@) {
689                 # gettext can clobber $@
690                 my $error = $@;
691                 print STDERR gettext("failed to process template:")." $error";
692                 return;
693         }
694         $template->param(title => $params{title})
695                 if defined $params{title} && length($params{title});
696         $template->param(author => $params{author})
697                 if defined $params{author} && length($params{author}
698                         && $params{author} ne $feed->{name});
699         $template->param(content => wikiescape(htmlabs($params{content},
700                 defined $params{base} ? $params{base} : $feed->{feedurl})));
701         $template->param(name => $feed->{name});
702         $template->param(url => $feed->{url});
703         $template->param(copyright => $params{copyright})
704                 if defined $params{copyright} && length $params{copyright};
705         $template->param(permalink => IkiWiki::urlabs($params{link}, $feed->{feedurl}))
706                 if defined $params{link};
707         $template->param(enclosureurl => $params{enclosureurl})
708                 if defined $params{enclosureurl} && length $params{enclosureurl};
709         $template->param(enclosureimage => $params{enclosureimage})
710                 if defined $params{enclosureimage} && length $params{enclosureimage};
711         $template->param(enclosureaudio => $params{enclosureaudio})
712                 if defined $params{enclosureaudio} && length $params{enclosureaudio};
713         $template->param(enclosurevideo => $params{enclosurevideo})
714                 if defined $params{enclosurevideo} && length $params{enclosurevideo};
715         if (ref $feed->{tags}) {
716                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
717         }
718         writefile(htmlfn($guid->{page}),
719                 $IkiWiki::Plugin::transient::transientdir, $template->output);
721         if (defined $mtime && $mtime <= time) {
722                 # Set the mtime, this lets the build process get the right
723                 # creation time on record for the new page.
724                 utime $mtime, $mtime,
725                         $IkiWiki::Plugin::transient::transientdir."/".htmlfn($guid->{page});
726                 # Store it in pagectime for expiry code to use also.
727                 $IkiWiki::pagectime{$guid->{page}}=$mtime
728                         unless exists $IkiWiki::pagectime{$guid->{page}};
729         }
730         else {
731                 # Dummy value for expiry code.
732                 $IkiWiki::pagectime{$guid->{page}}=time
733                         unless exists $IkiWiki::pagectime{$guid->{page}};
734         }
737 sub wikiescape ($) {
738         # escape accidental wikilinks and preprocessor stuff
739         return encode_entities(shift, '\[\]');
742 sub htmlabs ($$) {
743         # Convert links in html from relative to absolute.
744         # Note that this is a heuristic, which is not specified by the rss
745         # spec and may not be right for all feeds. Also, see Debian
746         # bug #381359.
747         my $html=shift;
748         my $urlbase=shift;
750         my $ret="";
751         my $p = HTML::Parser->new(api_version => 3);
752         $p->handler(default => sub { $ret.=join("", @_) }, "text");
753         $p->handler(start => sub {
754                 my ($tagname, $pos, $text) = @_;
755                 if (ref $HTML::Tagset::linkElements{$tagname}) {
756                         while (4 <= @$pos) {
757                                 # use attribute sets from right to left
758                                 # to avoid invalidating the offsets
759                                 # when replacing the values
760                                 my($k_offset, $k_len, $v_offset, $v_len) =
761                                         splice(@$pos, -4);
762                                 my $attrname = lc(substr($text, $k_offset, $k_len));
763                                 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
764                                 next unless $v_offset; # 0 v_offset means no value
765                                 my $v = substr($text, $v_offset, $v_len);
766                                 $v =~ s/^([\'\"])(.*)\1$/$2/;
767                                 my $new_v=IkiWiki::urlabs($v, $urlbase);
768                                 $new_v =~ s/\"/&quot;/g; # since we quote with ""
769                                 substr($text, $v_offset, $v_len) = qq("$new_v");
770                         }
771                 }
772                 $ret.=$text;
773         }, "tagname, tokenpos, text");
774         $p->parse($html);
775         $p->eof;
777         return $ret;
780 sub htmlfn ($) {
781         return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
784 my $aggregatelock;
786 sub lockaggregate () {
787         # Take an exclusive lock to prevent multiple concurrent aggregators.
788         # Returns true if the lock was aquired.
789         if (! -d $config{wikistatedir}) {
790                 mkdir($config{wikistatedir});
791         }
792         open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
793                 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
794         if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
795                 close($aggregatelock) || error("failed closing aggregatelock: $!");
796                 return 0;
797         }
798         return 1;
801 sub unlockaggregate () {
802         return close($aggregatelock) if $aggregatelock;
803         return;