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