]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/aggregate.pm
(no commit message)
[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 URI;
12 use open qw{:utf8 :std};
14 my %feeds;
15 my %guids;
17 sub import {
18         hook(type => "getopt", id => "aggregate", call => \&getopt);
19         hook(type => "getsetup", id => "aggregate", call => \&getsetup);
20         hook(type => "checkconfig", id => "aggregate", call => \&checkconfig);
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         if ($config{aggregate} && ! ($config{post_commit} && 
69                                      IkiWiki::commit_hook_enabled())) {
70                 launchaggregation();
71         }
72 }
74 sub cgi ($) {
75         my $cgi=shift;
77         if (defined $cgi->param('do') &&
78             $cgi->param("do") eq "aggregate_webtrigger") {
79                 $|=1;
80                 print "Content-Type: text/plain\n\n";
81                 $config{cgi}=0;
82                 $config{verbose}=1;
83                 $config{syslog}=0;
84                 print gettext("Aggregation triggered via web.")."\n\n";
85                 if (launchaggregation()) {
86                         IkiWiki::lockwiki();
87                         IkiWiki::loadindex();
88                         require IkiWiki::Render;
89                         IkiWiki::refresh();
90                         IkiWiki::saveindex();
91                 }
92                 else {
93                         print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
94                 }
95                 exit 0;
96         }
97 }
99 sub launchaggregation () {
100         # See if any feeds need aggregation.
101         loadstate();
102         my @feeds=needsaggregate();
103         return unless @feeds;
104         if (! lockaggregate()) {
105                 debug("an aggregation process is already running");
106                 return;
107         }
108         # force a later rebuild of source pages
109         $IkiWiki::forcerebuild{$_->{sourcepage}}=1
110                 foreach @feeds;
112         # Fork a child process to handle the aggregation.
113         # The parent process will then handle building the
114         # result. This avoids messy code to clear state
115         # accumulated while aggregating.
116         defined(my $pid = fork) or error("Can't fork: $!");
117         if (! $pid) {
118                 IkiWiki::loadindex();
119                 # Aggregation happens without the main wiki lock
120                 # being held. This allows editing pages etc while
121                 # aggregation is running.
122                 aggregate(@feeds);
124                 IkiWiki::lockwiki;
125                 # Merge changes, since aggregation state may have
126                 # changed on disk while the aggregation was happening.
127                 mergestate();
128                 expire();
129                 savestate();
130                 IkiWiki::unlockwiki;
131                 exit 0;
132         }
133         waitpid($pid,0);
134         if ($?) {
135                 error "aggregation failed with code $?";
136         }
138         clearstate();
139         unlockaggregate();
141         return 1;
144 #  Pages with extension _aggregated have plain html markup, pass through.
145 sub htmlize (@) {
146         my %params=@_;
147         return $params{content};
150 # Used by ikiwiki-transition aggregateinternal.
151 sub migrate_to_internal {
152         if (! lockaggregate()) {
153                 error("an aggregation process is currently running");
154         }
156         IkiWiki::lockwiki();
157         loadstate();
158         $config{verbose}=1;
160         foreach my $data (values %guids) {
161                 next unless $data->{page};
162                 next if $data->{expired};
163                 
164                 $config{aggregateinternal} = 0;
165                 my $oldname = "$config{srcdir}/".htmlfn($data->{page});
166                 my $oldoutput = $config{destdir}."/".IkiWiki::htmlpage($data->{page});
167                 
168                 $config{aggregateinternal} = 1;
169                 my $newname = "$config{srcdir}/".htmlfn($data->{page});
170                 
171                 debug "moving $oldname -> $newname";
172                 if (-e $newname) {
173                         if (-e $oldname) {
174                                 error("$newname already exists");
175                         }
176                         else {
177                                 debug("already renamed to $newname?");
178                         }
179                 }
180                 elsif (-e $oldname) {
181                         rename($oldname, $newname) || error("$!");
182                 }
183                 else {
184                         debug("$oldname not found");
185                 }
186                 if (-e $oldoutput) {
187                         require IkiWiki::Render;
188                         debug("removing output file $oldoutput");
189                         IkiWiki::prune($oldoutput);
190                 }
191         }
192         
193         savestate();
194         IkiWiki::unlockwiki;
195         
196         unlockaggregate();
199 sub needsbuild (@) {
200         my $needsbuild=shift;
201         
202         loadstate();
204         foreach my $feed (values %feeds) {
205                 if (exists $pagesources{$feed->{sourcepage}} && 
206                     grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
207                         # Mark all feeds originating on this page as 
208                         # not yet seen; preprocess will unmark those that
209                         # still exist.
210                         markunseen($feed->{sourcepage});
211                 }
212         }
214         return $needsbuild;
217 sub preprocess (@) {
218         my %params=@_;
220         foreach my $required (qw{name url}) {
221                 if (! exists $params{$required}) {
222                         error sprintf(gettext("missing %s parameter"), $required)
223                 }
224         }
226         my $feed={};
227         my $name=$params{name};
228         if (exists $feeds{$name}) {
229                 $feed=$feeds{$name};
230         }
231         else {
232                 $feeds{$name}=$feed;
233         }
234         $feed->{name}=$name;
235         $feed->{sourcepage}=$params{page};
236         $feed->{url}=$params{url};
237         my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
238         $dir=~s/^\/+//;
239         ($dir)=$dir=~/$config{wiki_file_regexp}/;
240         $feed->{dir}=$dir;
241         $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
242         $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
243         $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
244         $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
245         if (exists $params{template}) {
246                 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
247         }
248         else {
249                 $params{template} = "aggregatepost"
250         }
251         $feed->{template}=$params{template} . ".tmpl";
252         delete $feed->{unseen};
253         $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
254         $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
255         $feed->{numposts}=0 unless defined $feed->{numposts};
256         $feed->{newposts}=0 unless defined $feed->{newposts};
257         $feed->{message}=gettext("new feed") unless defined $feed->{message};
258         $feed->{error}=0 unless defined $feed->{error};
259         $feed->{tags}=[];
260         while (@_) {
261                 my $key=shift;
262                 my $value=shift;
263                 if ($key eq 'tag') {
264                         push @{$feed->{tags}}, $value;
265                 }
266         }
268         return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
269                ($feed->{error} ? "<em>" : "").$feed->{message}.
270                ($feed->{error} ? "</em>" : "").
271                " (".$feed->{numposts}." ".gettext("posts").
272                ($feed->{newposts} ? "; ".$feed->{newposts}.
273                                     " ".gettext("new") : "").
274                ")";
277 sub delete (@) {
278         my @files=@_;
280         # Remove feed data for removed pages.
281         foreach my $file (@files) {
282                 my $page=pagename($file);
283                 markunseen($page);
284         }
287 sub markunseen ($) {
288         my $page=shift;
290         foreach my $id (keys %feeds) {
291                 if ($feeds{$id}->{sourcepage} eq $page) {
292                         $feeds{$id}->{unseen}=1;
293                 }
294         }
297 my $state_loaded=0;
299 sub loadstate () {
300         return if $state_loaded;
301         $state_loaded=1;
302         if (-e "$config{wikistatedir}/aggregate") {
303                 open(IN, "<", "$config{wikistatedir}/aggregate") ||
304                         die "$config{wikistatedir}/aggregate: $!";
305                 while (<IN>) {
306                         $_=IkiWiki::possibly_foolish_untaint($_);
307                         chomp;
308                         my $data={};
309                         foreach my $i (split(/ /, $_)) {
310                                 my ($field, $val)=split(/=/, $i, 2);
311                                 if ($field eq "name" || $field eq "feed" ||
312                                     $field eq "guid" || $field eq "message") {
313                                         $data->{$field}=decode_entities($val, " \t\n");
314                                 }
315                                 elsif ($field eq "tag") {
316                                         push @{$data->{tags}}, $val;
317                                 }
318                                 else {
319                                         $data->{$field}=$val;
320                                 }
321                         }
322                         
323                         if (exists $data->{name}) {
324                                 $feeds{$data->{name}}=$data;
325                         }
326                         elsif (exists $data->{guid}) {
327                                 $guids{$data->{guid}}=$data;
328                         }
329                 }
331                 close IN;
332         }
335 sub savestate () {
336         return unless $state_loaded;
337         garbage_collect();
338         my $newfile="$config{wikistatedir}/aggregate.new";
339         my $cleanup = sub { unlink($newfile) };
340         open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
341         foreach my $data (values %feeds, values %guids) {
342                 my @line;
343                 foreach my $field (keys %$data) {
344                         if ($field eq "name" || $field eq "feed" ||
345                             $field eq "guid" || $field eq "message") {
346                                 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
347                         }
348                         elsif ($field eq "tags") {
349                                 push @line, "tag=$_" foreach @{$data->{tags}};
350                         }
351                         else {
352                                 push @line, "$field=".$data->{$field}
353                                         if defined $data->{$field};
354                         }
355                 }
356                 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
357         }
358         close OUT || error("save $newfile: $!", $cleanup);
359         rename($newfile, "$config{wikistatedir}/aggregate") ||
360                 error("rename $newfile: $!", $cleanup);
362         my $timestamp=undef;
363         foreach my $feed (keys %feeds) {
364                 my $t=$feeds{$feed}->{lastupdate}+$feeds{$feed}->{updateinterval};
365                 if (! defined $timestamp || $timestamp > $t) {
366                         $timestamp=$t;
367                 }
368         }
369         $newfile=~s/\.new$/time/;
370         open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
371         if (defined $timestamp) {
372                 print OUT $timestamp."\n";
373         }
374         close OUT || error("save $newfile: $!", $cleanup);
377 sub garbage_collect () {
378         foreach my $name (keys %feeds) {
379                 # remove any feeds that were not seen while building the pages
380                 # that used to contain them
381                 if ($feeds{$name}->{unseen}) {
382                         delete $feeds{$name};
383                 }
384         }
386         foreach my $guid (values %guids) {
387                 # any guid whose feed is gone should be removed
388                 if (! exists $feeds{$guid->{feed}}) {
389                         unlink "$config{srcdir}/".htmlfn($guid->{page})
390                                 if exists $guid->{page};
391                         delete $guids{$guid->{guid}};
392                 }
393                 # handle expired guids
394                 elsif ($guid->{expired} && exists $guid->{page}) {
395                         unlink "$config{srcdir}/".htmlfn($guid->{page});
396                         delete $guid->{page};
397                         delete $guid->{md5};
398                 }
399         }
402 sub mergestate () {
403         # Load the current state in from disk, and merge into it
404         # values from the state in memory that might have changed
405         # during aggregation.
406         my %myfeeds=%feeds;
407         my %myguids=%guids;
408         clearstate();
409         loadstate();
411         # All that can change in feed state during aggregation is a few
412         # fields.
413         foreach my $name (keys %myfeeds) {
414                 if (exists $feeds{$name}) {
415                         foreach my $field (qw{message lastupdate lasttry
416                                               numposts newposts error}) {
417                                 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
418                         }
419                 }
420         }
422         # New guids can be created during aggregation.
423         # Guids have a few fields that may be updated during aggregation.
424         # It's also possible that guids were removed from the on-disk state
425         # while the aggregation was in process. That would only happen if
426         # their feed was also removed, so any removed guids added back here
427         # will be garbage collected later.
428         foreach my $guid (keys %myguids) {
429                 if (! exists $guids{$guid}) {
430                         $guids{$guid}=$myguids{$guid};
431                 }
432                 else {
433                         foreach my $field (qw{md5}) {
434                                 $guids{$guid}->{$field}=$myguids{$guid}->{$field};
435                         }
436                 }
437         }
440 sub clearstate () {
441         %feeds=();
442         %guids=();
443         $state_loaded=0;
446 sub expire () {
447         foreach my $feed (values %feeds) {
448                 next unless $feed->{expireage} || $feed->{expirecount};
449                 my $count=0;
450                 my %seen;
451                 foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
452                                   grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
453                                   values %guids) {
454                         if ($feed->{expireage}) {
455                                 my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
456                                 if ($days_old > $feed->{expireage}) {
457                                         debug(sprintf(gettext("expiring %s (%s days old)"),
458                                                 $item->{page}, int($days_old)));
459                                         $item->{expired}=1;
460                                 }
461                         }
462                         elsif ($feed->{expirecount} &&
463                                $count >= $feed->{expirecount}) {
464                                 debug(sprintf(gettext("expiring %s"), $item->{page}));
465                                 $item->{expired}=1;
466                         }
467                         else {
468                                 if (! $seen{$item->{page}}) {
469                                         $seen{$item->{page}}=1;
470                                         $count++;
471                                 }
472                         }
473                 }
474         }
477 sub needsaggregate () {
478         return values %feeds if $config{rebuild};
479         return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
482 sub aggregate (@) {
483         eval q{use XML::Feed};
484         error($@) if $@;
485         eval q{use URI::Fetch};
486         error($@) if $@;
488         foreach my $feed (@_) {
489                 $feed->{lasttry}=time;
490                 $feed->{newposts}=0;
491                 $feed->{message}=sprintf(gettext("last checked %s"),
492                         displaytime($feed->{lasttry}));
493                 $feed->{error}=0;
495                 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
497                 if (! length $feed->{feedurl}) {
498                         my @urls=XML::Feed->find_feeds($feed->{url});
499                         if (! @urls) {
500                                 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
501                                 $feed->{error}=1;
502                                 debug($feed->{message});
503                                 next;
504                         }
505                         $feed->{feedurl}=pop @urls;
506                 }
507                 my $res=URI::Fetch->fetch($feed->{feedurl});
508                 if (! $res) {
509                         $feed->{message}=URI::Fetch->errstr;
510                         $feed->{error}=1;
511                         debug($feed->{message});
512                         next;
513                 }
515                 # lastupdate is only set if we were able to contact the server
516                 $feed->{lastupdate}=$feed->{lasttry};
518                 if ($res->status == URI::Fetch::URI_GONE()) {
519                         $feed->{message}=gettext("feed not found");
520                         $feed->{error}=1;
521                         debug($feed->{message});
522                         next;
523                 }
524                 my $content=$res->content;
525                 my $f=eval{XML::Feed->parse(\$content)};
526                 if ($@) {
527                         # One common cause of XML::Feed crashing is a feed
528                         # that contains invalid UTF-8 sequences. Convert
529                         # feed to ascii to try to work around.
530                         $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
531                         $f=eval {
532                                 $content=Encode::decode_utf8($content, 0);
533                                 XML::Feed->parse(\$content)
534                         };
535                 }
536                 if ($@) {
537                         # Another possibility is badly escaped entities.
538                         $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
539                         $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
540                         $f=eval {
541                                 $content=Encode::decode_utf8($content, 0);
542                                 XML::Feed->parse(\$content)
543                         };
544                 }
545                 if ($@) {
546                         $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
547                         $feed->{error}=1;
548                         debug($feed->{message});
549                         next;
550                 }
551                 if (! $f) {
552                         $feed->{message}=XML::Feed->errstr;
553                         $feed->{error}=1;
554                         debug($feed->{message});
555                         next;
556                 }
558                 foreach my $entry ($f->entries) {
559                         # XML::Feed doesn't work around XML::Atom's bizarre
560                         # API, so we will. Real unicode strings? Yes please.
561                         # See [[bugs/Aggregated_Atom_feeds_are_double-encoded]]
562                         local $XML::Atom::ForceUnicode = 1;
564                         my $c=$entry->content;
565                         # atom feeds may have no content, only a summary
566                         if (! defined $c && ref $entry->summary) {
567                                 $c=$entry->summary;
568                         }
570                         add_page(
571                                 feed => $feed,
572                                 copyright => $f->copyright,
573                                 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
574                                 link => $entry->link,
575                                 content => (defined $c && defined $c->body) ? $c->body : "",
576                                 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
577                                 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
578                                 base => (defined $c && $c->can("base")) ? $c->base : undef,
579                         );
580                 }
581         }
584 sub add_page (@) {
585         my %params=@_;
586         
587         my $feed=$params{feed};
588         my $guid={};
589         my $mtime;
590         if (exists $guids{$params{guid}}) {
591                 # updating an existing post
592                 $guid=$guids{$params{guid}};
593                 return if $guid->{expired};
594         }
595         else {
596                 # new post
597                 $guid->{guid}=$params{guid};
598                 $guids{$params{guid}}=$guid;
599                 $mtime=$params{ctime};
600                 $feed->{numposts}++;
601                 $feed->{newposts}++;
603                 # assign it an unused page
604                 my $page=titlepage($params{title});
605                 # escape slashes and periods in title so it doesn't specify
606                 # directory name or trigger ".." disallowing code.
607                 $page=~s!([/.])!"__".ord($1)."__"!eg;
608                 $page=$feed->{dir}."/".$page;
609                 ($page)=$page=~/$config{wiki_file_regexp}/;
610                 if (! defined $page || ! length $page) {
611                         $page=$feed->{dir}."/item";
612                 }
613                 my $c="";
614                 while (exists $IkiWiki::pagecase{lc $page.$c} ||
615                        -e "$config{srcdir}/".htmlfn($page.$c)) {
616                         $c++
617                 }
619                 # Make sure that the file name isn't too long. 
620                 # NB: This doesn't check for path length limits.
621                 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
622                 if (defined $max && length(htmlfn($page)) >= $max) {
623                         $c="";
624                         $page=$feed->{dir}."/item";
625                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
626                                -e "$config{srcdir}/".htmlfn($page.$c)) {
627                                 $c++
628                         }
629                 }
631                 $guid->{page}=$page;
632                 debug(sprintf(gettext("creating new page %s"), $page));
633         }
634         $guid->{feed}=$feed->{name};
635         
636         # To write or not to write? Need to avoid writing unchanged pages
637         # to avoid unneccessary rebuilding. The mtime from rss cannot be
638         # trusted; let's use a digest.
639         eval q{use Digest::MD5 'md5_hex'};
640         error($@) if $@;
641         require Encode;
642         my $digest=md5_hex(Encode::encode_utf8($params{content}));
643         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
644         $guid->{md5}=$digest;
646         # Create the page.
647         my $template;
648         eval {
649                 $template=template($feed->{template}, blind_cache => 1);
650         };
651         if ($@) {
652                 print STDERR gettext("failed to process template:")." $@";
653                 return;
654         }
655         $template->param(title => $params{title})
656                 if defined $params{title} && length($params{title});
657         $template->param(content => wikiescape(htmlabs($params{content},
658                 defined $params{base} ? $params{base} : $feed->{feedurl})));
659         $template->param(name => $feed->{name});
660         $template->param(url => $feed->{url});
661         $template->param(copyright => $params{copyright})
662                 if defined $params{copyright} && length $params{copyright};
663         $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
664                 if defined $params{link};
665         if (ref $feed->{tags}) {
666                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
667         }
668         writefile(htmlfn($guid->{page}), $config{srcdir},
669                 $template->output);
671         if (defined $mtime && $mtime <= time) {
672                 # Set the mtime, this lets the build process get the right
673                 # creation time on record for the new page.
674                 utime $mtime, $mtime, "$config{srcdir}/".htmlfn($guid->{page});
675                 # Store it in pagectime for expiry code to use also.
676                 $IkiWiki::pagectime{$guid->{page}}=$mtime
677                         unless exists $IkiWiki::pagectime{$guid->{page}};
678         }
679         else {
680                 # Dummy value for expiry code.
681                 $IkiWiki::pagectime{$guid->{page}}=time
682                         unless exists $IkiWiki::pagectime{$guid->{page}};
683         }
686 sub wikiescape ($) {
687         # escape accidental wikilinks and preprocessor stuff
688         return encode_entities(shift, '\[\]');
691 sub urlabs ($$) {
692         my $url=shift;
693         my $urlbase=shift;
695         URI->new_abs($url, $urlbase)->as_string;
698 sub htmlabs ($$) {
699         # Convert links in html from relative to absolute.
700         # Note that this is a heuristic, which is not specified by the rss
701         # spec and may not be right for all feeds. Also, see Debian
702         # bug #381359.
703         my $html=shift;
704         my $urlbase=shift;
706         my $ret="";
707         my $p = HTML::Parser->new(api_version => 3);
708         $p->handler(default => sub { $ret.=join("", @_) }, "text");
709         $p->handler(start => sub {
710                 my ($tagname, $pos, $text) = @_;
711                 if (ref $HTML::Tagset::linkElements{$tagname}) {
712                         while (4 <= @$pos) {
713                                 # use attribute sets from right to left
714                                 # to avoid invalidating the offsets
715                                 # when replacing the values
716                                 my($k_offset, $k_len, $v_offset, $v_len) =
717                                         splice(@$pos, -4);
718                                 my $attrname = lc(substr($text, $k_offset, $k_len));
719                                 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
720                                 next unless $v_offset; # 0 v_offset means no value
721                                 my $v = substr($text, $v_offset, $v_len);
722                                 $v =~ s/^([\'\"])(.*)\1$/$2/;
723                                 my $new_v=urlabs($v, $urlbase);
724                                 $new_v =~ s/\"/&quot;/g; # since we quote with ""
725                                 substr($text, $v_offset, $v_len) = qq("$new_v");
726                         }
727                 }
728                 $ret.=$text;
729         }, "tagname, tokenpos, text");
730         $p->parse($html);
731         $p->eof;
733         return $ret;
736 sub htmlfn ($) {
737         return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
740 my $aggregatelock;
742 sub lockaggregate () {
743         # Take an exclusive lock to prevent multiple concurrent aggregators.
744         # Returns true if the lock was aquired.
745         if (! -d $config{wikistatedir}) {
746                 mkdir($config{wikistatedir});
747         }
748         open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
749                 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
750         if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
751                 close($aggregatelock) || error("failed closing aggregatelock: $!");
752                 return 0;
753         }
754         return 1;
757 sub unlockaggregate () {
758         return close($aggregatelock) if $aggregatelock;
759         return;