Do not UTF8-escape "/" in Git's diffurl: cgit does not support this.
[ikiwiki.git] / IkiWiki / Render.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use IkiWiki;
8
9 my (%backlinks, %rendered);
10 our %brokenlinks;
11 my $links_calculated=0;
12
13 sub calculate_links () {
14         return if $links_calculated;
15         %backlinks=%brokenlinks=();
16         foreach my $page (keys %links) {
17                 foreach my $link (@{$links{$page}}) {
18                         my $bestlink=bestlink($page, $link);
19                         if (length $bestlink) {
20                                 $backlinks{$bestlink}{$page}=1
21                                         if $bestlink ne $page;
22                         }
23                         else {
24                                 push @{$brokenlinks{$link}}, $page;
25                         }
26                 }
27         }
28         $links_calculated=1;
29 }
30
31 sub backlink_pages ($) {
32         my $page=shift;
33
34         calculate_links();
35
36         return keys %{$backlinks{$page}};
37 }
38
39 sub backlinks ($) {
40         my $page=shift;
41
42         my @links;
43         foreach my $p (backlink_pages($page)) {
44                 my $href=urlto($p, $page);
45
46                 # Trim common dir prefixes from both pages.
47                 my $p_trimmed=$p;
48                 my $page_trimmed=$page;
49                 my $dir;
50                 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
51                         defined $dir &&
52                         $p_trimmed=~s/^\Q$dir\E// &&
53                         $page_trimmed=~s/^\Q$dir\E//;
54                                
55                 push @links, { url => $href, page => pagetitle($p_trimmed) };
56         }
57         return @links;
58 }
59
60 sub genpage ($$) {
61         my $page=shift;
62         my $content=shift;
63         
64         run_hooks(indexhtml => sub {
65                 shift->(page => $page, destpage => $page, content => $content);
66         });
67
68         my $templatefile;
69         run_hooks(templatefile => sub {
70                 return if defined $templatefile;
71                 my $file=shift->(page => $page);
72                 if (defined $file && defined template_file($file)) {
73                         $templatefile=$file;
74                 }
75         });
76         my $template;
77         if (defined $templatefile) {
78                 $template=template_depends($templatefile, $page,
79                         blind_cache => 1);
80         }
81         else {
82                 # no explicit depends as special case
83                 $template=template('page.tmpl', 
84                         blind_cache => 1);
85         }
86
87         my $actions=0;
88         if (length $config{cgiurl}) {
89                 if (IkiWiki->can("cgi_editpage")) {
90                         $template->param(editurl => cgiurl(do => "edit", page => $page));
91                         $actions++;
92                 }
93         }
94         if (defined $config{historyurl} && length $config{historyurl}) {
95                 my $u=$config{historyurl};
96                 my $p=uri_escape_utf8($pagesources{$page}, '^A-Za-z0-9\-\._~/');
97                 $u=~s/\[\[file\]\]/$p/g;
98                 $template->param(historyurl => $u);
99                 $actions++;
100         }
101         if ($config{discussion}) {
102                 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
103                    (length $config{cgiurl} ||
104                     exists $links{$page."/".$config{discussionpage}})) {
105                         $template->param(discussionlink => htmllink($page, $page, $config{discussionpage}, noimageinline => 1, forcesubpage => 1));
106                         $actions++;
107                 }
108         }
109         if ($actions) {
110                 $template->param(have_actions => 1);
111         }
112         templateactions($template, $page);
113
114         my @backlinks=sort { $a->{page} cmp $b->{page} } backlinks($page);
115         my ($backlinks, $more_backlinks);
116         if (@backlinks <= $config{numbacklinks} || ! $config{numbacklinks}) {
117                 $backlinks=\@backlinks;
118                 $more_backlinks=[];
119         }
120         else {
121                 $backlinks=[@backlinks[0..$config{numbacklinks}-1]];
122                 $more_backlinks=[@backlinks[$config{numbacklinks}..$#backlinks]];
123         }
124
125         $template->param(
126                 title => $page eq 'index' 
127                         ? $config{wikiname} 
128                         : pagetitle(basename($page)),
129                 wikiname => $config{wikiname},
130                 content => $content,
131                 backlinks => $backlinks,
132                 more_backlinks => $more_backlinks,
133                 mtime => displaytime($pagemtime{$page}),
134                 ctime => displaytime($pagectime{$page}, undef, 1),
135                 baseurl => baseurl($page),
136                 html5 => $config{html5},
137         );
138
139         run_hooks(pagetemplate => sub {
140                 shift->(page => $page, destpage => $page, template => $template);
141         });
142         
143         $content=$template->output;
144         
145         run_hooks(format => sub {
146                 $content=shift->(
147                         page => $page,
148                         content => $content,
149                 );
150         });
151
152         return $content;
153 }
154
155 sub scan ($) {
156         my $file=shift;
157
158         debug(sprintf(gettext("scanning %s"), $file));
159
160         my $type=pagetype($file);
161         if (defined $type) {
162                 my $srcfile=srcfile($file);
163                 my $content=readfile($srcfile);
164                 my $page=pagename($file);
165                 will_render($page, htmlpage($page), 1);
166
167                 if ($config{discussion}) {
168                         # Discussion links are a special case since they're
169                         # not in the text of the page, but on its template.
170                         $links{$page}=[ $page."/".lc($config{discussionpage}) ];
171                 }
172                 else {
173                         $links{$page}=[];
174                 }
175                 delete $typedlinks{$page};
176
177                 # Preprocess in scan-only mode.
178                 preprocess($page, $page, $content, 1);
179
180                 run_hooks(scan => sub {
181                         shift->(
182                                 page => $page,
183                                 content => $content,
184                         );
185                 });
186         }
187         else {
188                 will_render($file, $file, 1);
189         }
190 }
191
192 sub fast_file_copy (@) {
193         my $srcfile=shift;
194         my $destfile=shift;
195         my $srcfd=shift;
196         my $destfd=shift;
197         my $cleanup=shift;
198
199         my $blksize = 16384;
200         my ($len, $buf, $written);
201         while ($len = sysread $srcfd, $buf, $blksize) {
202                 if (! defined $len) {
203                         next if $! =~ /^Interrupted/;
204                         error("failed to read $srcfile: $!", $cleanup);
205                 }
206                 my $offset = 0;
207                 while ($len) {
208                         defined($written = syswrite $destfd, $buf, $len, $offset)
209                                 or error("failed to write $destfile: $!", $cleanup);
210                         $len -= $written;
211                         $offset += $written;
212                 }
213         }
214 }
215
216 sub render ($$) {
217         my $file=shift;
218         return if $rendered{$file};
219         debug(shift);
220         $rendered{$file}=1;
221         
222         my $type=pagetype($file);
223         my $srcfile=srcfile($file);
224         if (defined $type) {
225                 my $page=pagename($file);
226                 delete $depends{$page};
227                 delete $depends_simple{$page};
228                 will_render($page, htmlpage($page), 1);
229                 return if $type=~/^_/;
230                 
231                 my $content=htmlize($page, $page, $type,
232                         linkify($page, $page,
233                         preprocess($page, $page,
234                         filter($page, $page,
235                         readfile($srcfile)))));
236                 
237                 my $output=htmlpage($page);
238                 writefile($output, $config{destdir}, genpage($page, $content));
239         }
240         else {
241                 delete $depends{$file};
242                 delete $depends_simple{$file};
243                 will_render($file, $file, 1);
244                 
245                 if ($config{hardlink}) {
246                         # only hardlink if owned by same user
247                         my @stat=stat($srcfile);
248                         if ($stat[4] == $>) {
249                                 prep_writefile($file, $config{destdir});
250                                 unlink($config{destdir}."/".$file);
251                                 if (link($srcfile, $config{destdir}."/".$file)) {
252                                         return;
253                                 }
254                         }
255                         # if hardlink fails, fall back to copying
256                 }
257                 
258                 my $srcfd=readfile($srcfile, 1, 1);
259                 writefile($file, $config{destdir}, undef, 1, sub {
260                         fast_file_copy($srcfile, $file, $srcfd, @_);
261                 });
262         }
263 }
264
265 sub prune ($;$) {
266         my $file=shift;
267         my $up_to=shift;
268
269         unlink($file);
270         my $dir=dirname($file);
271         while ((! defined $up_to || $dir =~ m{^\Q$up_to\E\/}) && rmdir($dir)) {
272                 $dir=dirname($dir);
273         }
274 }
275
276 sub srcdir_check () {
277         # security check, avoid following symlinks in the srcdir path by default
278         my $test=$config{srcdir};
279         while (length $test) {
280                 if (-l $test && ! $config{allow_symlinks_before_srcdir}) {
281                         error(sprintf(gettext("symlink found in srcdir path (%s) -- set allow_symlinks_before_srcdir to allow this"), $test));
282                 }
283                 unless ($test=~s/\/+$//) {
284                         $test=dirname($test);
285                 }
286         }
287         
288 }
289
290 # Finds all files in the srcdir, and the underlaydirs.
291 # Returns the files, and their corresponding pages.
292 #
293 # When run in only_underlay mode, adds only the underlay files to
294 # the files and pages passed in.
295 sub find_src_files (;$$$) {
296         my $only_underlay=shift;
297         my @files;
298         if (defined $_[0]) {
299                 @files=@{shift()};
300         }
301         my %pages;
302         if (defined $_[0]) {
303                 %pages=%{shift()};
304         }
305
306         eval q{use File::Find};
307         error($@) if $@;
308
309         eval q{use Cwd};
310         die $@ if $@;
311         my $origdir=getcwd();
312         my $abssrcdir=Cwd::abs_path($config{srcdir});
313         
314         @IkiWiki::underlayfiles=();
315
316         my ($page, $underlay);
317         my $helper=sub {
318                 my $file=decode_utf8($_);
319
320                 return if -l $file || -d _;
321                 $file=~s/^\.\///;
322                 return if ! length $file;
323                 $page = pagename($file);
324                 if (! exists $pagesources{$page} &&
325                     file_pruned($file)) {
326                         $File::Find::prune=1;
327                         return;
328                 }
329
330                 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
331                 if (! defined $f) {
332                         warn(sprintf(gettext("skipping bad filename %s"), $file)."\n");
333                         return;
334                 }
335         
336                 if ($underlay) {
337                         # avoid underlaydir override attacks; see security.mdwn
338                         if (! -l "$abssrcdir/$f" && ! -e _) {
339                                 if (! $pages{$page}) {
340                                         push @files, $f;
341                                         push @IkiWiki::underlayfiles, $f;
342                                         $pages{$page}=1;
343                                 }
344                         }
345                 }
346                 else {
347                         push @files, $f;
348                         if ($pages{$page}) {
349                                 debug(sprintf(gettext("%s has multiple possible source pages"), $page));
350                         }
351                         $pages{$page}=1;
352                 }
353         };
354
355         unless ($only_underlay) {
356                 chdir($config{srcdir}) || die "chdir $config{srcdir}: $!";
357                 find({
358                         no_chdir => 1,
359                         wanted => $helper,
360                 }, '.');
361                 chdir($origdir) || die "chdir $origdir: $!";
362         }
363
364         $underlay=1;
365         foreach (@{$config{underlaydirs}}, $config{underlaydir}) {
366                 if (chdir($_)) {
367                         find({
368                                 no_chdir => 1,
369                                 wanted => $helper,
370                         }, '.');
371                         chdir($origdir) || die "chdir: $!";
372                 }
373         };
374
375         return \@files, \%pages;
376 }
377
378 # Given a hash of files that have changed, and a hash of files that were
379 # deleted, should return the same results as find_src_files, with the same
380 # sanity checks. But a lot faster!
381 sub process_changed_files ($$) {
382         my $changed_raw=shift;
383         my $deleted_raw=shift;
384
385         my @files;
386         my %pages;
387
388         foreach my $file (keys %$changed_raw) {
389                 my $page = pagename($file);
390                 next if ! exists $pagesources{$page} && file_pruned($file);
391                 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
392                 if (! defined $f) {
393                         warn(sprintf(gettext("skipping bad filename %s"), $file)."\n");
394                         next;
395                 }
396                 push @files, $f;
397                 if ($pages{$page}) {
398                         debug(sprintf(gettext("%s has multiple possible source pages"), $page));
399                 }
400                 $pages{$page}=1;
401         }
402
403         # So far, we only have the changed files. Now add in all the old
404         # files that were not changed or deleted, excluding ones that came
405         # from the underlay.
406         my %old_underlay;
407         foreach my $f (@IkiWiki::underlayfiles) {
408                 $old_underlay{$f}=1;
409         }
410         foreach my $page (keys %pagesources) {
411                 my $f=$pagesources{$page};
412                 unless ($old_underlay{$f} || exists $pages{$page} || exists $deleted_raw->{$f}) {
413                         $pages{$page}=1;
414                         push @files, $f;
415                 }
416         }
417
418         # add in the underlay
419         find_src_files(1, \@files, \%pages);
420 }
421
422 sub find_new_files ($) {
423         my $files=shift;
424         my @new;
425         my @internal_new;
426
427         my $times_noted;
428
429         foreach my $file (@$files) {
430                 my $page=pagename($file);
431
432                 if ($config{rcs} && $config{gettime} &&
433                     -e "$config{srcdir}/$file") {
434                         if (! $times_noted) {
435                                 debug(sprintf(gettext("querying %s for file creation and modification times.."), $config{rcs}));
436                                 $times_noted=1;
437                         }
438
439                         eval {
440                                 my $ctime=rcs_getctime($file);
441                                 if ($ctime > 0) {
442                                         $pagectime{$page}=$ctime;
443                                 }
444                         };
445                         if ($@) {
446                                 print STDERR $@;
447                         }
448                         my $mtime;
449                         eval {
450                                 $mtime=rcs_getmtime($file);
451                         };
452                         if ($@) {
453                                 print STDERR $@;
454                         }
455                         elsif ($mtime > 0) {
456                                 utime($mtime, $mtime, "$config{srcdir}/$file");
457                         }
458                 }
459
460                 if (exists $pagesources{$page} && $pagesources{$page} ne $file) {
461                         # the page has changed its type
462                         $forcerebuild{$page}=1;
463                 }
464                 $pagesources{$page}=$file;
465                 if (! $pagemtime{$page}) {
466                         if (isinternal($page)) {
467                                 push @internal_new, $file;
468                         }
469                         else {
470                                 push @new, $file;
471                         }
472                         $pagecase{lc $page}=$page;
473                         if (! exists $pagectime{$page}) {
474                                 $pagectime{$page}=(srcfile_stat($file))[10];
475                         }
476                 }
477         }
478
479         return \@new, \@internal_new;
480 }
481
482 sub find_del_files ($) {
483         my $pages=shift;
484         my @del;
485         my @internal_del;
486
487         foreach my $page (keys %pagesources) {
488                 if (! $pages->{$page}) {
489                         if (isinternal($page)) {
490                                 push @internal_del, $pagesources{$page};
491                         }
492                         else {
493                                 push @del, $pagesources{$page};
494                         }
495                         $links{$page}=[];
496                         delete $typedlinks{$page};
497                         $renderedfiles{$page}=[];
498                         $pagemtime{$page}=0;
499                 }
500         }
501
502         return \@del, \@internal_del;
503 }
504
505 sub remove_del (@) {
506         foreach my $file (@_) {
507                 my $page=pagename($file);
508                 if (! isinternal($page)) {
509                         debug(sprintf(gettext("removing obsolete %s"), $page));
510                 }
511         
512                 foreach my $old (@{$oldrenderedfiles{$page}}) {
513                         prune($config{destdir}."/".$old, $config{destdir});
514                 }
515
516                 foreach my $source (keys %destsources) {
517                         if ($destsources{$source} eq $page) {
518                                 delete $destsources{$source};
519                         }
520                 }
521         
522                 delete $pagecase{lc $page};
523                 $delpagesources{$page}=$pagesources{$page};
524                 delete $pagesources{$page};
525         }
526 }
527
528 sub find_changed ($) {
529         my $files=shift;
530         my @changed;
531         my @internal_changed;
532         foreach my $file (@$files) {
533                 my $page=pagename($file);
534                 my ($srcfile, @stat)=srcfile_stat($file);
535                 if (! exists $pagemtime{$page} ||
536                     $stat[9] > $pagemtime{$page} ||
537                     $forcerebuild{$page}) {
538                         $pagemtime{$page}=$stat[9];
539
540                         if (isinternal($page)) {
541                                 my $content = readfile($srcfile);
542
543                                 # Preprocess internal page in scan-only mode.
544                                 preprocess($page, $page, $content, 1);
545
546                                 run_hooks(scan => sub {
547                                         shift->(
548                                                 page => $page,
549                                                 content => $content,
550                                         );
551                                 });
552
553                                 push @internal_changed, $file;
554                         }
555                         else {
556                                 push @changed, $file;
557                         }
558                 }
559         }
560         return \@changed, \@internal_changed;
561 }
562
563 sub calculate_old_links ($$) {
564         my ($changed, $del)=@_;
565         my %oldlink_targets;
566         foreach my $file (@$changed, @$del) {
567                 my $page=pagename($file);
568                 if (exists $oldlinks{$page}) {
569                         foreach my $l (@{$oldlinks{$page}}) {
570                                 $oldlink_targets{$page}{$l}=bestlink($page, $l);
571                         }
572                 }
573         }
574         return \%oldlink_targets;
575 }
576
577 sub derender_internal ($) {
578         my $file=shift;
579         my $page=pagename($file);
580         delete $depends{$page};
581         delete $depends_simple{$page};
582         foreach my $old (@{$renderedfiles{$page}}) {
583                 delete $destsources{$old};
584         }
585         $renderedfiles{$page}=[];
586 }
587
588 sub render_linkers ($) {
589         my $f=shift;
590         my $p=pagename($f);
591         foreach my $page (keys %{$backlinks{$p}}) {
592                 my $file=$pagesources{$page};
593                 render($file, sprintf(gettext("building %s, which links to %s"), $file, $p));
594         }
595 }
596
597 sub remove_unrendered () {
598         foreach my $src (keys %rendered) {
599                 my $page=pagename($src);
600                 foreach my $file (@{$oldrenderedfiles{$page}}) {
601                         if (! grep { $_ eq $file } @{$renderedfiles{$page}}) {
602                                 debug(sprintf(gettext("removing %s, no longer built by %s"), $file, $page));
603                                 prune($config{destdir}."/".$file, $config{destdir});
604                         }
605                 }
606         }
607 }
608
609 sub link_types_changed ($$) {
610         # each is of the form { type => { link => 1 } }
611         my $new = shift;
612         my $old = shift;
613
614         return 0 if !defined $new && !defined $old;
615         return 1 if (!defined $new && %$old) || (!defined $old && %$new);
616
617         while (my ($type, $links) = each %$new) {
618                 foreach my $link (keys %$links) {
619                         return 1 unless exists $old->{$type}{$link};
620                 }
621         }
622
623         while (my ($type, $links) = each %$old) {
624                 foreach my $link (keys %$links) {
625                         return 1 unless exists $new->{$type}{$link};
626                 }
627         }
628
629         return 0;
630 }
631
632 sub calculate_changed_links ($$$) {
633         my ($changed, $del, $oldlink_targets)=@_;
634
635         my (%backlinkchanged, %linkchangers);
636
637         foreach my $file (@$changed, @$del) {
638                 my $page=pagename($file);
639
640                 if (exists $links{$page}) {
641                         foreach my $l (@{$links{$page}}) {
642                                 my $target=bestlink($page, $l);
643                                 if (! exists $oldlink_targets->{$page}{$l} ||
644                                     $target ne $oldlink_targets->{$page}{$l}) {
645                                         $backlinkchanged{$target}=1;
646                                         $linkchangers{lc($page)}=1;
647                                 }
648                                 delete $oldlink_targets->{$page}{$l};
649                         }
650                 }
651                 if (exists $oldlink_targets->{$page} &&
652                     %{$oldlink_targets->{$page}}) {
653                         foreach my $target (values %{$oldlink_targets->{$page}}) {
654                                 $backlinkchanged{$target}=1;
655                         }
656                         $linkchangers{lc($page)}=1;
657                 }
658
659                 # we currently assume that changing the type of a link doesn't
660                 # change backlinks
661                 if (!exists $linkchangers{lc($page)}) {
662                         if (link_types_changed($typedlinks{$page}, $oldtypedlinks{$page})) {
663                                 $linkchangers{lc($page)}=1;
664                         }
665                 }
666         }
667
668         return \%backlinkchanged, \%linkchangers;
669 }
670
671 sub render_dependent ($$$$$$$) {
672         my ($files, $new, $internal_new, $del, $internal_del,
673                 $internal_changed, $linkchangers)=@_;
674
675         my @changed=(keys %rendered, @$del);
676         my @exists_changed=(@$new, @$del);
677         
678         my %lc_changed = map { lc(pagename($_)) => 1 } @changed;
679         my %lc_exists_changed = map { lc(pagename($_)) => 1 } @exists_changed;
680
681         foreach my $p ("templates/page.tmpl", keys %{$depends_simple{""}}) {
682                 if ($rendered{$p} || grep { $_ eq $p } @$del) {
683                         foreach my $f (@$files) {
684                                 next if $rendered{$f};
685                                 render($f, sprintf(gettext("building %s, which depends on %s"), $f, $p));
686                         }
687                         return 0;
688                 }
689         }
690          
691         foreach my $f (@$files) {
692                 next if $rendered{$f};
693                 my $p=pagename($f);
694                 my $reason = undef;
695
696                 if (exists $depends_simple{$p} && ! defined $reason) {
697                         foreach my $d (keys %{$depends_simple{$p}}) {
698                                 if (($depends_simple{$p}{$d} & $IkiWiki::DEPEND_CONTENT &&
699                                      $lc_changed{$d})
700                                     ||
701                                     ($depends_simple{$p}{$d} & $IkiWiki::DEPEND_PRESENCE &&
702                                      $lc_exists_changed{$d})
703                                     ||
704                                     ($depends_simple{$p}{$d} & $IkiWiki::DEPEND_LINKS &&
705                                      $linkchangers->{$d})
706                                 ) {
707                                         $reason = $d;
708                                         last;
709                                 }
710                         }
711                 }
712         
713                 if (exists $depends{$p} && ! defined $reason) {
714                         foreach my $dep (keys %{$depends{$p}}) {
715                                 my $sub=pagespec_translate($dep);
716                                 next unless defined $sub;
717
718                                 # only consider internal files
719                                 # if the page explicitly depends
720                                 # on such files
721                                 my $internal_dep=$dep =~ /(?:internal|comment|comment_pending)\(/;
722
723                                 my $in=sub {
724                                         my $list=shift;
725                                         my $type=shift;
726                                         foreach my $file (@$list) {
727                                                 next if $file eq $f;
728                                                 my $page=pagename($file);
729                                                 if ($sub->($page, location => $p)) {
730                                                         if ($type == $IkiWiki::DEPEND_LINKS) {
731                                                                 next unless $linkchangers->{lc($page)};
732                                                         }
733                                                         $reason=$page;
734                                                         return 1;
735                                                 }
736                                         }
737                                         return undef;
738                                 };
739
740                                 if ($depends{$p}{$dep} & $IkiWiki::DEPEND_CONTENT) {
741                                         last if $in->(\@changed, $IkiWiki::DEPEND_CONTENT);
742                                         last if $internal_dep && (
743                                                 $in->($internal_new, $IkiWiki::DEPEND_CONTENT) ||
744                                                 $in->($internal_del, $IkiWiki::DEPEND_CONTENT) ||
745                                                 $in->($internal_changed, $IkiWiki::DEPEND_CONTENT)
746                                         );
747                                 }
748                                 if ($depends{$p}{$dep} & $IkiWiki::DEPEND_PRESENCE) {
749                                         last if $in->(\@exists_changed, $IkiWiki::DEPEND_PRESENCE);
750                                         last if $internal_dep && (
751                                                 $in->($internal_new, $IkiWiki::DEPEND_PRESENCE) ||
752                                                 $in->($internal_del, $IkiWiki::DEPEND_PRESENCE)
753                                         );
754                                 }
755                                 if ($depends{$p}{$dep} & $IkiWiki::DEPEND_LINKS) {
756                                         last if $in->(\@changed, $IkiWiki::DEPEND_LINKS);
757                                         last if $internal_dep && (
758                                                 $in->($internal_new, $IkiWiki::DEPEND_LINKS) ||
759                                                 $in->($internal_del, $IkiWiki::DEPEND_LINKS) ||
760                                                 $in->($internal_changed, $IkiWiki::DEPEND_LINKS)
761                                         );
762                                 }
763                         }
764                 }
765         
766                 if (defined $reason) {
767                         render($f, sprintf(gettext("building %s, which depends on %s"), $f, $reason));
768                         return 1;
769                 }
770         }
771
772         return 0;
773 }
774
775 sub render_backlinks ($) {
776         my $backlinkchanged=shift;
777         foreach my $link (keys %$backlinkchanged) {
778                 my $linkfile=$pagesources{$link};
779                 if (defined $linkfile) {
780                         render($linkfile, sprintf(gettext("building %s, to update its backlinks"), $linkfile));
781                 }
782         }
783 }
784
785 sub gen_autofile ($$$) {
786         my $autofile=shift;
787         my $pages=shift;
788         my $del=shift;
789
790         if (file_pruned($autofile)) {
791                 return;
792         }
793
794         my ($file)="$config{srcdir}/$autofile" =~ /$config{wiki_file_regexp}/; # untaint
795         if (! defined $file) {
796                 return;
797         }
798
799         # Remember autofiles that were tried, and never try them again later.
800         if (exists $wikistate{$autofiles{$autofile}{plugin}}{autofile}{$autofile}) {
801                 return;
802         }
803         $wikistate{$autofiles{$autofile}{plugin}}{autofile}{$autofile}=1;
804
805         if (srcfile($autofile, 1) || file_pruned($autofile)) {
806                 return;
807         }
808         
809         if (-l $file || -d _ || -e _) {
810                 return;
811         }
812
813         my $page = pagename($file);
814         if ($pages->{$page}) {
815                 return;
816         }
817
818         if (grep { $_ eq $autofile } @$del) {
819                 return;
820         }
821
822         $autofiles{$autofile}{generator}->();
823         $pages->{$page}=1;
824         return 1;
825 }
826
827 sub refresh () {
828         srcdir_check();
829         run_hooks(refresh => sub { shift->() });
830         my ($files, $pages, $new, $internal_new, $del, $internal_del, $changed, $internal_changed);
831         my $want_find_changes=$config{only_committed_changes} &&
832                 exists $IkiWiki::hooks{rcs}{rcs_find_changes} &&
833                 exists $IkiWiki::hooks{rcs}{rcs_get_current_rev};
834         if (! $config{rebuild} && $want_find_changes && defined $IkiWiki::lastrev && length $IkiWiki::lastrev) {
835                 my ($changed_raw, $del_raw);
836                 ($changed_raw, $del_raw, $IkiWiki::lastrev) = $IkiWiki::hooks{rcs}{rcs_find_changes}{call}->($IkiWiki::lastrev);
837                 ($files, $pages)=process_changed_files($changed_raw, $del_raw);
838         }
839         else {
840                 ($files, $pages)=find_src_files();
841         }
842         if ($want_find_changes) {
843                 if (! defined($IkiWiki::lastrev) || ! length $IkiWiki::lastrev) {
844                         $IkiWiki::lastrev=$IkiWiki::hooks{rcs}{rcs_get_current_rev}{call}->();
845                 }
846         }
847         ($new, $internal_new)=find_new_files($files);
848         ($del, $internal_del)=find_del_files($pages);
849         ($changed, $internal_changed)=find_changed($files);
850         my %existingfiles;
851         run_hooks(needsbuild => sub {
852                 my $ret=shift->($changed, [@$del, @$internal_del]);
853                 if (ref $ret eq 'ARRAY' && $ret != $changed) {
854                         if (! %existingfiles) {
855                                 foreach my $f (@$files) {
856                                         $existingfiles{$f}=1;
857                                 }
858                         }
859                         @$changed=grep $existingfiles{$_}, @$ret;
860                 }
861         });
862         my $oldlink_targets=calculate_old_links($changed, $del);
863
864         foreach my $file (@$changed) {
865                 scan($file);
866         }
867
868         foreach my $autofile (keys %autofiles) {
869                 if (gen_autofile($autofile, $pages, $del)) {
870                         push @{$files}, $autofile;
871                         push @{$new}, $autofile if find_new_files([$autofile]);
872                         push @{$changed}, $autofile if find_changed([$autofile]);
873                         
874                         scan($autofile);
875                 }
876         }
877
878         calculate_links();
879         
880         remove_del(@$del, @$internal_del);
881
882         foreach my $file (@$changed) {
883                 render($file, sprintf(gettext("building %s"), $file));
884         }
885         foreach my $file (@$internal_new, @$internal_del, @$internal_changed) {
886                 derender_internal($file);
887         }
888
889         run_hooks(build_affected => sub {
890                 my %affected = shift->();
891                 while (my ($page, $message) = each %affected) {
892                         next unless exists $pagesources{$page};
893                         render($pagesources{$page}, $message);
894                 }
895         });
896
897         my ($backlinkchanged, $linkchangers)=calculate_changed_links($changed,
898                 $del, $oldlink_targets);
899
900         foreach my $file (@$new, @$del) {
901                 render_linkers($file);
902         }
903
904         if (@$changed || @$internal_changed ||
905             @$del || @$internal_del || @$internal_new) {
906                 1 while render_dependent($files, $new, $internal_new,
907                         $del, $internal_del, $internal_changed,
908                         $linkchangers);
909         }
910
911         render_backlinks($backlinkchanged);
912         remove_unrendered();
913
914         if (@$del || @$internal_del) {
915                 run_hooks(delete => sub { shift->(@$del, @$internal_del) });
916         }
917         if (%rendered) {
918                 run_hooks(rendered => sub { shift->(keys %rendered) });
919                 run_hooks(change => sub { shift->(keys %rendered) }); # back-compat
920         }
921         my %all_changed = map { $_ => 1 }
922                 @$new, @$changed, @$del,
923                 @$internal_new, @$internal_changed, @$internal_del;
924         run_hooks(changes => sub { shift->(keys %all_changed) });
925 }
926
927 sub clean_rendered {
928         lockwiki();
929         loadindex();
930         remove_unrendered();
931         foreach my $page (keys %oldrenderedfiles) {
932                 foreach my $file (@{$oldrenderedfiles{$page}}) {
933                         prune($config{destdir}."/".$file, $config{destdir});
934                 }
935         }
936 }
937
938 sub commandline_render () {
939         lockwiki();
940         loadindex();
941         unlockwiki();
942
943         my $srcfile=possibly_foolish_untaint($config{render});
944         my $file=$srcfile;
945         $file=~s/\Q$config{srcdir}\E\/?//;
946
947         my $type=pagetype($file);
948         die sprintf(gettext("ikiwiki: cannot build %s"), $srcfile)."\n" unless defined $type;
949         my $content=readfile($srcfile);
950         my $page=pagename($file);
951         $pagesources{$page}=$file;
952         $content=filter($page, $page, $content);
953         $content=preprocess($page, $page, $content);
954         $content=linkify($page, $page, $content);
955         $content=htmlize($page, $page, $type, $content);
956         $pagemtime{$page}=(stat($srcfile))[9];
957         $pagectime{$page}=$pagemtime{$page} if ! exists $pagectime{$page};
958
959         print genpage($page, $content);
960         exit 0;
961 }
962
963 1