]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/aggregate.pm
Merge branch 'master' of ssh://git.ikiwiki.info/srv/git/ikiwiki.info
[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         }
215 sub preprocess (@) {
216         my %params=@_;
218         foreach my $required (qw{name url}) {
219                 if (! exists $params{$required}) {
220                         error sprintf(gettext("missing %s parameter"), $required)
221                 }
222         }
224         my $feed={};
225         my $name=$params{name};
226         if (exists $feeds{$name}) {
227                 $feed=$feeds{$name};
228         }
229         else {
230                 $feeds{$name}=$feed;
231         }
232         $feed->{name}=$name;
233         $feed->{sourcepage}=$params{page};
234         $feed->{url}=$params{url};
235         my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
236         $dir=~s/^\/+//;
237         ($dir)=$dir=~/$config{wiki_file_regexp}/;
238         $feed->{dir}=$dir;
239         $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
240         $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
241         $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
242         $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
243         if (exists $params{template}) {
244                 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
245         }
246         else {
247                 $params{template} = "aggregatepost"
248         }
249         $feed->{template}=$params{template} . ".tmpl";
250         delete $feed->{unseen};
251         $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
252         $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
253         $feed->{numposts}=0 unless defined $feed->{numposts};
254         $feed->{newposts}=0 unless defined $feed->{newposts};
255         $feed->{message}=gettext("new feed") unless defined $feed->{message};
256         $feed->{error}=0 unless defined $feed->{error};
257         $feed->{tags}=[];
258         while (@_) {
259                 my $key=shift;
260                 my $value=shift;
261                 if ($key eq 'tag') {
262                         push @{$feed->{tags}}, $value;
263                 }
264         }
266         return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
267                ($feed->{error} ? "<em>" : "").$feed->{message}.
268                ($feed->{error} ? "</em>" : "").
269                " (".$feed->{numposts}." ".gettext("posts").
270                ($feed->{newposts} ? "; ".$feed->{newposts}.
271                                     " ".gettext("new") : "").
272                ")";
275 sub delete (@) {
276         my @files=@_;
278         # Remove feed data for removed pages.
279         foreach my $file (@files) {
280                 my $page=pagename($file);
281                 markunseen($page);
282         }
285 sub markunseen ($) {
286         my $page=shift;
288         foreach my $id (keys %feeds) {
289                 if ($feeds{$id}->{sourcepage} eq $page) {
290                         $feeds{$id}->{unseen}=1;
291                 }
292         }
295 my $state_loaded=0;
297 sub loadstate () {
298         return if $state_loaded;
299         $state_loaded=1;
300         if (-e "$config{wikistatedir}/aggregate") {
301                 open(IN, "<", "$config{wikistatedir}/aggregate") ||
302                         die "$config{wikistatedir}/aggregate: $!";
303                 while (<IN>) {
304                         $_=IkiWiki::possibly_foolish_untaint($_);
305                         chomp;
306                         my $data={};
307                         foreach my $i (split(/ /, $_)) {
308                                 my ($field, $val)=split(/=/, $i, 2);
309                                 if ($field eq "name" || $field eq "feed" ||
310                                     $field eq "guid" || $field eq "message") {
311                                         $data->{$field}=decode_entities($val, " \t\n");
312                                 }
313                                 elsif ($field eq "tag") {
314                                         push @{$data->{tags}}, $val;
315                                 }
316                                 else {
317                                         $data->{$field}=$val;
318                                 }
319                         }
320                         
321                         if (exists $data->{name}) {
322                                 $feeds{$data->{name}}=$data;
323                         }
324                         elsif (exists $data->{guid}) {
325                                 $guids{$data->{guid}}=$data;
326                         }
327                 }
329                 close IN;
330         }
333 sub savestate () {
334         return unless $state_loaded;
335         garbage_collect();
336         my $newfile="$config{wikistatedir}/aggregate.new";
337         my $cleanup = sub { unlink($newfile) };
338         open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
339         foreach my $data (values %feeds, values %guids) {
340                 my @line;
341                 foreach my $field (keys %$data) {
342                         if ($field eq "name" || $field eq "feed" ||
343                             $field eq "guid" || $field eq "message") {
344                                 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
345                         }
346                         elsif ($field eq "tags") {
347                                 push @line, "tag=$_" foreach @{$data->{tags}};
348                         }
349                         else {
350                                 push @line, "$field=".$data->{$field}
351                                         if defined $data->{$field};
352                         }
353                 }
354                 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
355         }
356         close OUT || error("save $newfile: $!", $cleanup);
357         rename($newfile, "$config{wikistatedir}/aggregate") ||
358                 error("rename $newfile: $!", $cleanup);
360         my $timestamp=undef;
361         foreach my $feed (keys %feeds) {
362                 my $t=$feeds{$feed}->{lastupdate}+$feeds{$feed}->{updateinterval};
363                 if (! defined $timestamp || $timestamp > $t) {
364                         $timestamp=$t;
365                 }
366         }
367         $newfile=~s/\.new$/time/;
368         open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
369         if (defined $timestamp) {
370                 print OUT $timestamp."\n";
371         }
372         close OUT || error("save $newfile: $!", $cleanup);
375 sub garbage_collect () {
376         foreach my $name (keys %feeds) {
377                 # remove any feeds that were not seen while building the pages
378                 # that used to contain them
379                 if ($feeds{$name}->{unseen}) {
380                         delete $feeds{$name};
381                 }
382         }
384         foreach my $guid (values %guids) {
385                 # any guid whose feed is gone should be removed
386                 if (! exists $feeds{$guid->{feed}}) {
387                         unlink "$config{srcdir}/".htmlfn($guid->{page})
388                                 if exists $guid->{page};
389                         delete $guids{$guid->{guid}};
390                 }
391                 # handle expired guids
392                 elsif ($guid->{expired} && exists $guid->{page}) {
393                         unlink "$config{srcdir}/".htmlfn($guid->{page});
394                         delete $guid->{page};
395                         delete $guid->{md5};
396                 }
397         }
400 sub mergestate () {
401         # Load the current state in from disk, and merge into it
402         # values from the state in memory that might have changed
403         # during aggregation.
404         my %myfeeds=%feeds;
405         my %myguids=%guids;
406         clearstate();
407         loadstate();
409         # All that can change in feed state during aggregation is a few
410         # fields.
411         foreach my $name (keys %myfeeds) {
412                 if (exists $feeds{$name}) {
413                         foreach my $field (qw{message lastupdate lasttry
414                                               numposts newposts error}) {
415                                 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
416                         }
417                 }
418         }
420         # New guids can be created during aggregation.
421         # Guids have a few fields that may be updated during aggregation.
422         # It's also possible that guids were removed from the on-disk state
423         # while the aggregation was in process. That would only happen if
424         # their feed was also removed, so any removed guids added back here
425         # will be garbage collected later.
426         foreach my $guid (keys %myguids) {
427                 if (! exists $guids{$guid}) {
428                         $guids{$guid}=$myguids{$guid};
429                 }
430                 else {
431                         foreach my $field (qw{md5}) {
432                                 $guids{$guid}->{$field}=$myguids{$guid}->{$field};
433                         }
434                 }
435         }
438 sub clearstate () {
439         %feeds=();
440         %guids=();
441         $state_loaded=0;
444 sub expire () {
445         foreach my $feed (values %feeds) {
446                 next unless $feed->{expireage} || $feed->{expirecount};
447                 my $count=0;
448                 my %seen;
449                 foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
450                                   grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
451                                   values %guids) {
452                         if ($feed->{expireage}) {
453                                 my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
454                                 if ($days_old > $feed->{expireage}) {
455                                         debug(sprintf(gettext("expiring %s (%s days old)"),
456                                                 $item->{page}, int($days_old)));
457                                         $item->{expired}=1;
458                                 }
459                         }
460                         elsif ($feed->{expirecount} &&
461                                $count >= $feed->{expirecount}) {
462                                 debug(sprintf(gettext("expiring %s"), $item->{page}));
463                                 $item->{expired}=1;
464                         }
465                         else {
466                                 if (! $seen{$item->{page}}) {
467                                         $seen{$item->{page}}=1;
468                                         $count++;
469                                 }
470                         }
471                 }
472         }
475 sub needsaggregate () {
476         return values %feeds if $config{rebuild};
477         return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
480 sub aggregate (@) {
481         eval q{use XML::Feed};
482         error($@) if $@;
483         eval q{use URI::Fetch};
484         error($@) if $@;
486         foreach my $feed (@_) {
487                 $feed->{lasttry}=time;
488                 $feed->{newposts}=0;
489                 $feed->{message}=sprintf(gettext("last checked %s"),
490                         displaytime($feed->{lasttry}));
491                 $feed->{error}=0;
493                 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
495                 if (! length $feed->{feedurl}) {
496                         my @urls=XML::Feed->find_feeds($feed->{url});
497                         if (! @urls) {
498                                 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
499                                 $feed->{error}=1;
500                                 debug($feed->{message});
501                                 next;
502                         }
503                         $feed->{feedurl}=pop @urls;
504                 }
505                 my $res=URI::Fetch->fetch($feed->{feedurl});
506                 if (! $res) {
507                         $feed->{message}=URI::Fetch->errstr;
508                         $feed->{error}=1;
509                         debug($feed->{message});
510                         next;
511                 }
513                 # lastupdate is only set if we were able to contact the server
514                 $feed->{lastupdate}=$feed->{lasttry};
516                 if ($res->status == URI::Fetch::URI_GONE()) {
517                         $feed->{message}=gettext("feed not found");
518                         $feed->{error}=1;
519                         debug($feed->{message});
520                         next;
521                 }
522                 my $content=$res->content;
523                 my $f=eval{XML::Feed->parse(\$content)};
524                 if ($@) {
525                         # One common cause of XML::Feed crashing is a feed
526                         # that contains invalid UTF-8 sequences. Convert
527                         # feed to ascii to try to work around.
528                         $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
529                         $f=eval {
530                                 $content=Encode::decode_utf8($content, 0);
531                                 XML::Feed->parse(\$content)
532                         };
533                 }
534                 if ($@) {
535                         # Another possibility is badly escaped entities.
536                         $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
537                         $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
538                         $f=eval {
539                                 $content=Encode::decode_utf8($content, 0);
540                                 XML::Feed->parse(\$content)
541                         };
542                 }
543                 if ($@) {
544                         $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
545                         $feed->{error}=1;
546                         debug($feed->{message});
547                         next;
548                 }
549                 if (! $f) {
550                         $feed->{message}=XML::Feed->errstr;
551                         $feed->{error}=1;
552                         debug($feed->{message});
553                         next;
554                 }
556                 foreach my $entry ($f->entries) {
557                         # XML::Feed doesn't work around XML::Atom's bizarre
558                         # API, so we will. Real unicode strings? Yes please.
559                         # See [[bugs/Aggregated_Atom_feeds_are_double-encoded]]
560                         local $XML::Atom::ForceUnicode = 1;
562                         my $c=$entry->content;
563                         # atom feeds may have no content, only a summary
564                         if (! defined $c && ref $entry->summary) {
565                                 $c=$entry->summary;
566                         }
568                         add_page(
569                                 feed => $feed,
570                                 copyright => $f->copyright,
571                                 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
572                                 link => $entry->link,
573                                 content => (defined $c && defined $c->body) ? $c->body : "",
574                                 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
575                                 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
576                                 base => (defined $c && $c->can("base")) ? $c->base : undef,
577                         );
578                 }
579         }
582 sub add_page (@) {
583         my %params=@_;
584         
585         my $feed=$params{feed};
586         my $guid={};
587         my $mtime;
588         if (exists $guids{$params{guid}}) {
589                 # updating an existing post
590                 $guid=$guids{$params{guid}};
591                 return if $guid->{expired};
592         }
593         else {
594                 # new post
595                 $guid->{guid}=$params{guid};
596                 $guids{$params{guid}}=$guid;
597                 $mtime=$params{ctime};
598                 $feed->{numposts}++;
599                 $feed->{newposts}++;
601                 # assign it an unused page
602                 my $page=titlepage($params{title});
603                 # escape slashes and periods in title so it doesn't specify
604                 # directory name or trigger ".." disallowing code.
605                 $page=~s!([/.])!"__".ord($1)."__"!eg;
606                 $page=$feed->{dir}."/".$page;
607                 ($page)=$page=~/$config{wiki_file_regexp}/;
608                 if (! defined $page || ! length $page) {
609                         $page=$feed->{dir}."/item";
610                 }
611                 my $c="";
612                 while (exists $IkiWiki::pagecase{lc $page.$c} ||
613                        -e "$config{srcdir}/".htmlfn($page.$c)) {
614                         $c++
615                 }
617                 # Make sure that the file name isn't too long. 
618                 # NB: This doesn't check for path length limits.
619                 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
620                 if (defined $max && length(htmlfn($page)) >= $max) {
621                         $c="";
622                         $page=$feed->{dir}."/item";
623                         while (exists $IkiWiki::pagecase{lc $page.$c} ||
624                                -e "$config{srcdir}/".htmlfn($page.$c)) {
625                                 $c++
626                         }
627                 }
629                 $guid->{page}=$page;
630                 debug(sprintf(gettext("creating new page %s"), $page));
631         }
632         $guid->{feed}=$feed->{name};
633         
634         # To write or not to write? Need to avoid writing unchanged pages
635         # to avoid unneccessary rebuilding. The mtime from rss cannot be
636         # trusted; let's use a digest.
637         eval q{use Digest::MD5 'md5_hex'};
638         error($@) if $@;
639         require Encode;
640         my $digest=md5_hex(Encode::encode_utf8($params{content}));
641         return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
642         $guid->{md5}=$digest;
644         # Create the page.
645         my $template=template($feed->{template}, blind_cache => 1);
646         $template->param(title => $params{title})
647                 if defined $params{title} && length($params{title});
648         $template->param(content => wikiescape(htmlabs($params{content},
649                 defined $params{base} ? $params{base} : $feed->{feedurl})));
650         $template->param(name => $feed->{name});
651         $template->param(url => $feed->{url});
652         $template->param(copyright => $params{copyright})
653                 if defined $params{copyright} && length $params{copyright};
654         $template->param(permalink => urlabs($params{link}, $feed->{feedurl}))
655                 if defined $params{link};
656         if (ref $feed->{tags}) {
657                 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
658         }
659         writefile(htmlfn($guid->{page}), $config{srcdir},
660                 $template->output);
662         if (defined $mtime && $mtime <= time) {
663                 # Set the mtime, this lets the build process get the right
664                 # creation time on record for the new page.
665                 utime $mtime, $mtime, "$config{srcdir}/".htmlfn($guid->{page});
666                 # Store it in pagectime for expiry code to use also.
667                 $IkiWiki::pagectime{$guid->{page}}=$mtime
668                         unless exists $IkiWiki::pagectime{$guid->{page}};
669         }
670         else {
671                 # Dummy value for expiry code.
672                 $IkiWiki::pagectime{$guid->{page}}=time
673                         unless exists $IkiWiki::pagectime{$guid->{page}};
674         }
677 sub wikiescape ($) {
678         # escape accidental wikilinks and preprocessor stuff
679         return encode_entities(shift, '\[\]');
682 sub urlabs ($$) {
683         my $url=shift;
684         my $urlbase=shift;
686         URI->new_abs($url, $urlbase)->as_string;
689 sub htmlabs ($$) {
690         # Convert links in html from relative to absolute.
691         # Note that this is a heuristic, which is not specified by the rss
692         # spec and may not be right for all feeds. Also, see Debian
693         # bug #381359.
694         my $html=shift;
695         my $urlbase=shift;
697         my $ret="";
698         my $p = HTML::Parser->new(api_version => 3);
699         $p->handler(default => sub { $ret.=join("", @_) }, "text");
700         $p->handler(start => sub {
701                 my ($tagname, $pos, $text) = @_;
702                 if (ref $HTML::Tagset::linkElements{$tagname}) {
703                         while (4 <= @$pos) {
704                                 # use attribute sets from right to left
705                                 # to avoid invalidating the offsets
706                                 # when replacing the values
707                                 my($k_offset, $k_len, $v_offset, $v_len) =
708                                         splice(@$pos, -4);
709                                 my $attrname = lc(substr($text, $k_offset, $k_len));
710                                 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
711                                 next unless $v_offset; # 0 v_offset means no value
712                                 my $v = substr($text, $v_offset, $v_len);
713                                 $v =~ s/^([\'\"])(.*)\1$/$2/;
714                                 my $new_v=urlabs($v, $urlbase);
715                                 $new_v =~ s/\"/&quot;/g; # since we quote with ""
716                                 substr($text, $v_offset, $v_len) = qq("$new_v");
717                         }
718                 }
719                 $ret.=$text;
720         }, "tagname, tokenpos, text");
721         $p->parse($html);
722         $p->eof;
724         return $ret;
727 sub htmlfn ($) {
728         return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
731 my $aggregatelock;
733 sub lockaggregate () {
734         # Take an exclusive lock to prevent multiple concurrent aggregators.
735         # Returns true if the lock was aquired.
736         if (! -d $config{wikistatedir}) {
737                 mkdir($config{wikistatedir});
738         }
739         open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
740                 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
741         if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
742                 close($aggregatelock) || error("failed closing aggregatelock: $!");
743                 return 0;
744         }
745         return 1;
748 sub unlockaggregate () {
749         return close($aggregatelock) if $aggregatelock;
750         return;