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