fix the other half of the filecheck filename bug
[ikiwiki.git] / IkiWiki / Render.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use IkiWiki;
8 use Encode;
9
10 my (%backlinks, %rendered);
11 our %brokenlinks;
12 my $links_calculated=0;
13
14 sub calculate_links () {
15         return if $links_calculated;
16         %backlinks=%brokenlinks=();
17         foreach my $page (keys %links) {
18                 foreach my $link (@{$links{$page}}) {
19                         my $bestlink=bestlink($page, $link);
20                         if (length $bestlink) {
21                                 $backlinks{$bestlink}{$page}=1
22                                         if $bestlink ne $page;
23                         }
24                         else {
25                                 push @{$brokenlinks{$link}}, $page;
26                         }
27                 }
28         }
29         $links_calculated=1;
30 }
31
32 sub backlink_pages ($) {
33         my $page=shift;
34
35         calculate_links();
36
37         return keys %{$backlinks{$page}};
38 }
39
40 sub backlinks ($) {
41         my $page=shift;
42
43         my @links;
44         foreach my $p (backlink_pages($page)) {
45                 my $href=urlto($p, $page);
46                 
47                 # Trim common dir prefixes from both pages.
48                 my $p_trimmed=$p;
49                 my $page_trimmed=$page;
50                 my $dir;
51                 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
52                         defined $dir &&
53                         $p_trimmed=~s/^\Q$dir\E// &&
54                         $page_trimmed=~s/^\Q$dir\E//;
55                                
56                 push @links, { url => $href, page => pagetitle($p_trimmed) };
57         }
58         return @links;
59 }
60
61 sub genpage ($$) {
62         my $page=shift;
63         my $content=shift;
64         
65         run_hooks(postscan => sub {
66                 shift->(page => $page, content => $content);
67         });
68
69         my $templatefile;
70         run_hooks(templatefile => sub {
71                 return if defined $templatefile;
72                 my $file=shift->(page => $page);
73                 if (defined $file && defined template_file($file)) {
74                         $templatefile=$file;
75                 }
76         });
77         my $template=template(defined $templatefile ? $templatefile : 'page.tmpl', blind_cache => 1);
78         my $actions=0;
79
80         if (length $config{cgiurl}) {
81                 if (IkiWiki->can("cgi_editpage")) {
82                         $template->param(editurl => cgiurl(do => "edit", page => $page));
83                         $actions++;
84                 }
85                 if (exists $hooks{auth}) {
86                         $template->param(prefsurl => cgiurl(do => "prefs"));
87                         $actions++;
88                 }
89         }
90                 
91         if (defined $config{historyurl} && length $config{historyurl}) {
92                 my $u=$config{historyurl};
93                 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
94                 $template->param(historyurl => $u);
95                 $actions++;
96         }
97         if ($config{discussion}) {
98                 if ($page !~ /.*\/\Q$config{discussionpage}\E$/i &&
99                    (length $config{cgiurl} ||
100                     exists $links{$page."/".$config{discussionpage}})) {
101                         $template->param(discussionlink => htmllink($page, $page, $config{discussionpage}, noimageinline => 1, forcesubpage => 1));
102                         $actions++;
103                 }
104         }
105
106         if ($actions) {
107                 $template->param(have_actions => 1);
108         }
109
110         my @backlinks=sort { $a->{page} cmp $b->{page} } backlinks($page);
111         my ($backlinks, $more_backlinks);
112         if (@backlinks <= $config{numbacklinks} || ! $config{numbacklinks}) {
113                 $backlinks=\@backlinks;
114                 $more_backlinks=[];
115         }
116         else {
117                 $backlinks=[@backlinks[0..$config{numbacklinks}-1]];
118                 $more_backlinks=[@backlinks[$config{numbacklinks}..$#backlinks]];
119         }
120
121         $template->param(
122                 title => $page eq 'index' 
123                         ? $config{wikiname} 
124                         : pagetitle(basename($page)),
125                 wikiname => $config{wikiname},
126                 content => $content,
127                 backlinks => $backlinks,
128                 more_backlinks => $more_backlinks,
129                 mtime => displaytime($pagemtime{$page}),
130                 ctime => displaytime($pagectime{$page}),
131                 baseurl => baseurl($page),
132         );
133
134         run_hooks(pagetemplate => sub {
135                 shift->(page => $page, destpage => $page, template => $template);
136         });
137         
138         $content=$template->output;
139         
140         run_hooks(format => sub {
141                 $content=shift->(
142                         page => $page,
143                         content => $content,
144                 );
145         });
146
147         return $content;
148 }
149
150 sub scan ($) {
151         my $file=shift;
152
153         debug(sprintf(gettext("scanning %s"), $file));
154
155         my $type=pagetype($file);
156         if (defined $type) {
157                 my $srcfile=srcfile($file);
158                 my $content=readfile($srcfile);
159                 my $page=pagename($file);
160                 will_render($page, htmlpage($page), 1);
161
162                 if ($config{discussion}) {
163                         # Discussion links are a special case since they're
164                         # not in the text of the page, but on its template.
165                         $links{$page}=[ $page."/".lc($config{discussionpage}) ];
166                 }
167                 else {
168                         $links{$page}=[];
169                 }
170
171                 run_hooks(scan => sub {
172                         shift->(
173                                 page => $page,
174                                 content => $content,
175                         );
176                 });
177
178                 # Preprocess in scan-only mode.
179                 preprocess($page, $page, $content, 1);
180         }
181         else {
182                 will_render($file, $file, 1);
183         }
184 }
185
186 sub fast_file_copy (@) {
187         my $srcfile=shift;
188         my $destfile=shift;
189         my $srcfd=shift;
190         my $destfd=shift;
191         my $cleanup=shift;
192
193         my $blksize = 16384;
194         my ($len, $buf, $written);
195         while ($len = sysread $srcfd, $buf, $blksize) {
196                 if (! defined $len) {
197                         next if $! =~ /^Interrupted/;
198                         error("failed to read $srcfile: $!", $cleanup);
199                 }
200                 my $offset = 0;
201                 while ($len) {
202                         defined($written = syswrite $destfd, $buf, $len, $offset)
203                                 or error("failed to write $destfile: $!", $cleanup);
204                         $len -= $written;
205                         $offset += $written;
206                 }
207         }
208 }
209
210 sub render ($$) {
211         my $file=shift;
212         return if $rendered{$file};
213         debug(shift);
214         $rendered{$file}=1;
215         
216         my $type=pagetype($file);
217         my $srcfile=srcfile($file);
218         if (defined $type) {
219                 my $page=pagename($file);
220                 delete $depends{$page};
221                 delete $depends_simple{$page};
222                 will_render($page, htmlpage($page), 1);
223                 return if $type=~/^_/;
224                 
225                 my $content=htmlize($page, $page, $type,
226                         linkify($page, $page,
227                         preprocess($page, $page,
228                         filter($page, $page,
229                         readfile($srcfile)))));
230                 
231                 my $output=htmlpage($page);
232                 writefile($output, $config{destdir}, genpage($page, $content));
233         }
234         else {
235                 delete $depends{$file};
236                 delete $depends_simple{$file};
237                 will_render($file, $file, 1);
238                 
239                 if ($config{hardlink}) {
240                         # only hardlink if owned by same user
241                         my @stat=stat($srcfile);
242                         if ($stat[4] == $>) {
243                                 prep_writefile($file, $config{destdir});
244                                 unlink($config{destdir}."/".$file);
245                                 if (link($srcfile, $config{destdir}."/".$file)) {
246                                         return;
247                                 }
248                         }
249                         # if hardlink fails, fall back to copying
250                 }
251                 
252                 my $srcfd=readfile($srcfile, 1, 1);
253                 writefile($file, $config{destdir}, undef, 1, sub {
254                         fast_file_copy($srcfile, $file, $srcfd, @_);
255                 });
256         }
257 }
258
259 sub prune ($) {
260         my $file=shift;
261
262         unlink($file);
263         my $dir=dirname($file);
264         while (rmdir($dir)) {
265                 $dir=dirname($dir);
266         }
267 }
268
269 sub srcdir_check () {
270         # security check, avoid following symlinks in the srcdir path by default
271         my $test=$config{srcdir};
272         while (length $test) {
273                 if (-l $test && ! $config{allow_symlinks_before_srcdir}) {
274                         error(sprintf(gettext("symlink found in srcdir path (%s) -- set allow_symlinks_before_srcdir to allow this"), $test));
275                 }
276                 unless ($test=~s/\/+$//) {
277                         $test=dirname($test);
278                 }
279         }
280         
281 }
282
283 sub find_src_files () {
284         my @files;
285         my %pages;
286         eval q{use File::Find};
287         error($@) if $@;
288         find({
289                 no_chdir => 1,
290                 wanted => sub {
291                         my $file=decode_utf8($_);
292                         $file=~s/^\Q$config{srcdir}\E\/?//;
293                         return if -l $_ || -d _ || ! length $file;
294                         my $page = pagename($file);
295                         if (! exists $pagesources{$page} &&
296                             file_pruned($file)) {
297                                 $File::Find::prune=1;
298                                 return;
299                         }
300
301                         my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
302                         if (! defined $f) {
303                                 warn(sprintf(gettext("skipping bad filename %s"), $file)."\n");
304                         }
305                         else {
306                                 push @files, $f;
307                                 if ($pages{$page}) {
308                                         debug(sprintf(gettext("%s has multiple possible source pages"), $page));
309                                 }
310                                 $pages{$page}=1;
311                         }
312                 },
313         }, $config{srcdir});
314         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
315                 find({
316                         no_chdir => 1,
317                         wanted => sub {
318                                 my $file=decode_utf8($_);
319                                 $file=~s/^\Q$dir\E\/?//;
320                                 return if -l $_ || -d _ || ! length $file;
321                                 my $page=pagename($file);
322                                 if (! exists $pagesources{$page} &&
323                                     file_pruned($file)) {
324                                         $File::Find::prune=1;
325                                         return;
326                                 }
327
328                                 my ($f) = $file =~ /$config{wiki_file_regexp}/; # untaint
329                                 if (! defined $f) {
330                                         warn(sprintf(gettext("skipping bad filename %s"), $file)."\n");
331                                 }
332                                 else {
333                                         # avoid underlaydir override
334                                         # attacks; see security.mdwn
335                                         if (! -l "$config{srcdir}/$f" && 
336                                             ! -e _) {
337                                                 if (! $pages{$page}) {
338                                                         push @files, $f;
339                                                         $pages{$page}=1;
340                                                 }
341                                         }
342                                 }
343                         },
344                 }, $dir);
345         };
346         return \@files, \%pages;
347 }
348
349 sub find_new_files ($) {
350         my $files=shift;
351         my @new;
352         my @internal_new;
353
354         foreach my $file (@$files) {
355                 my $page=pagename($file);
356                 if (exists $pagesources{$page} && $pagesources{$page} ne $file) {
357                         # the page has changed its type
358                         $forcerebuild{$page}=1;
359                 }
360                 $pagesources{$page}=$file;
361                 if (! $pagemtime{$page}) {
362                         if (isinternal($page)) {
363                                 push @internal_new, $file;
364                         }
365                         else {
366                                 push @new, $file;
367                                 if ($config{getctime} && -e "$config{srcdir}/$file") {
368                                         eval {
369                                                 my $time=rcs_getctime("$config{srcdir}/$file");
370                                                 $pagectime{$page}=$time;
371                                         };
372                                         if ($@) {
373                                                 print STDERR $@;
374                                         }
375                                 }
376                         }
377                         $pagecase{lc $page}=$page;
378                         if (! exists $pagectime{$page}) {
379                                 $pagectime{$page}=(srcfile_stat($file))[10];
380                         }
381                 }
382         }
383
384         return \@new, \@internal_new;
385 }
386
387 sub find_del_files ($) {
388         my $pages=shift;
389         my @del;
390         my @internal_del;
391
392         foreach my $page (keys %pagemtime) {
393                 if (! $pages->{$page}) {
394                         if (isinternal($page)) {
395                                 push @internal_del, $pagesources{$page};
396                         }
397                         else {
398                                 push @del, $pagesources{$page};
399                         }
400                         $links{$page}=[];
401                         $renderedfiles{$page}=[];
402                         $pagemtime{$page}=0;
403                 }
404         }
405
406         return \@del, \@internal_del;
407 }
408
409 sub remove_del (@) {
410         foreach my $file (@_) {
411                 my $page=pagename($file);
412                 if (! isinternal($page)) {
413                         debug(sprintf(gettext("removing old page %s"), $page));
414                 }
415         
416                 foreach my $old (@{$oldrenderedfiles{$page}}) {
417                         prune($config{destdir}."/".$old);
418                 }
419
420                 foreach my $source (keys %destsources) {
421                         if ($destsources{$source} eq $page) {
422                                 delete $destsources{$source};
423                         }
424                 }
425         
426                 delete $pagecase{lc $page};
427                 delete $pagesources{$page};
428         }
429 }
430
431 sub find_changed ($) {
432         my $files=shift;
433         my @changed;
434         my @internal_changed;
435         foreach my $file (@$files) {
436                 my $page=pagename($file);
437                 my ($srcfile, @stat)=srcfile_stat($file);
438                 if (! exists $pagemtime{$page} ||
439                     $stat[9] > $pagemtime{$page} ||
440                     $forcerebuild{$page}) {
441                         $pagemtime{$page}=$stat[9];
442
443                         if (isinternal($page)) {
444                                 # Preprocess internal page in scan-only mode.
445                                 preprocess($page, $page, readfile($srcfile), 1);
446                                 push @internal_changed, $file;
447                         }
448                         else {
449                                 push @changed, $file;
450                         }
451                 }
452         }
453         return \@changed, \@internal_changed;
454 }
455
456 sub calculate_old_links ($$) {
457         my ($changed, $del)=@_;
458         my %oldlink_targets;
459         foreach my $file (@$changed, @$del) {
460                 my $page=pagename($file);
461                 if (exists $oldlinks{$page}) {
462                         foreach my $l (@{$oldlinks{$page}}) {
463                                 $oldlink_targets{$page}{$l}=bestlink($page, $l);
464                         }
465                 }
466         }
467         return \%oldlink_targets;
468 }
469
470 sub derender_internal ($) {
471         my $file=shift;
472         my $page=pagename($file);
473         delete $depends{$page};
474         delete $depends_simple{$page};
475         foreach my $old (@{$renderedfiles{$page}}) {
476                 delete $destsources{$old};
477         }
478         $renderedfiles{$page}=[];
479 }
480
481 sub render_linkers ($) {
482         my $f=shift;
483         my $p=pagename($f);
484         foreach my $page (keys %{$backlinks{$p}}) {
485                 my $file=$pagesources{$page};
486                 render($file, sprintf(gettext("building %s, which links to %s"), $file, $p));
487         }
488 }
489
490 sub remove_unrendered () {
491         foreach my $src (keys %rendered) {
492                 my $page=pagename($src);
493                 foreach my $file (@{$oldrenderedfiles{$page}}) {
494                         if (! grep { $_ eq $file } @{$renderedfiles{$page}}) {
495                                 debug(sprintf(gettext("removing %s, no longer built by %s"), $file, $page));
496                                 prune($config{destdir}."/".$file);
497                         }
498                 }
499         }
500 }
501
502 sub calculate_changed_links ($$$) {
503         my ($changed, $del, $oldlink_targets)=@_;
504
505         my (%backlinkchanged, %linkchangers);
506
507         foreach my $file (@$changed, @$del) {
508                 my $page=pagename($file);
509
510                 if (exists $links{$page}) {
511                         foreach my $l (@{$links{$page}}) {
512                                 my $target=bestlink($page, $l);
513                                 if (! exists $oldlink_targets->{$page}{$l} ||
514                                     $target ne $oldlink_targets->{$page}{$l}) {
515                                         $backlinkchanged{$target}=1;
516                                         $linkchangers{lc($page)}=1;
517                                 }
518                                 delete $oldlink_targets->{$page}{$l};
519                         }
520                 }
521                 if (exists $oldlink_targets->{$page} &&
522                     %{$oldlink_targets->{$page}}) {
523                         foreach my $target (values %{$oldlink_targets->{$page}}) {
524                                 $backlinkchanged{$target}=1;
525                         }
526                         $linkchangers{lc($page)}=1;
527                 }
528         }
529
530         return \%backlinkchanged, \%linkchangers;
531 }
532
533 sub render_dependent ($$$$$$$) {
534         my ($files, $new, $internal_new, $del, $internal_del,
535                 $internal_changed, $linkchangers)=@_;
536
537         my @changed=(keys %rendered, @$del);
538         my @exists_changed=(@$new, @$del);
539         
540         my %lc_changed = map { lc(pagename($_)) => 1 } @changed;
541         my %lc_exists_changed = map { lc(pagename($_)) => 1 } @exists_changed;
542          
543         foreach my $f (@$files) {
544                 next if $rendered{$f};
545                 my $p=pagename($f);
546                 my $reason = undef;
547         
548                 if (exists $depends_simple{$p}) {
549                         foreach my $d (keys %{$depends_simple{$p}}) {
550                                 if (($depends_simple{$p}{$d} & $IkiWiki::DEPEND_CONTENT &&
551                                      $lc_changed{$d})
552                                     ||
553                                     ($depends_simple{$p}{$d} & $IkiWiki::DEPEND_PRESENCE &&
554                                      $lc_exists_changed{$d})
555                                     ||
556                                     ($depends_simple{$p}{$d} & $IkiWiki::DEPEND_LINKS &&
557                                      $linkchangers->{$d})
558                                 ) {
559                                         $reason = $d;
560                                         last;
561                                 }
562                         }
563                 }
564         
565                 if (exists $depends{$p} && ! defined $reason) {
566                         foreach my $dep (keys %{$depends{$p}}) {
567                                 my $sub=pagespec_translate($dep);
568                                 next if $@ || ! defined $sub;
569
570                                 # only consider internal files
571                                 # if the page explicitly depends
572                                 # on such files
573                                 my $internal_dep=$dep =~ /internal\(/;
574
575                                 my $in=sub {
576                                         my $list=shift;
577                                         my $type=shift;
578                                         foreach my $file (@$list) {
579                                                 next if $file eq $f;
580                                                 my $page=pagename($file);
581                                                 if ($sub->($page, location => $p)) {
582                                                         if ($type == $IkiWiki::DEPEND_LINKS) {
583                                                                 next unless $linkchangers->{lc($page)};
584                                                         }
585                                                         return $page;
586                                                 }
587                                         }
588                                         return undef;
589                                 };
590
591                                 if ($depends{$p}{$dep} & $IkiWiki::DEPEND_CONTENT) {
592                                         last if $reason =
593                                                 $in->(\@changed, $IkiWiki::DEPEND_CONTENT);
594                                         last if $internal_dep && ($reason =
595                                                 $in->($internal_new, $IkiWiki::DEPEND_CONTENT) ||
596                                                 $in->($internal_del, $IkiWiki::DEPEND_CONTENT) ||
597                                                 $in->($internal_changed, $IkiWiki::DEPEND_CONTENT));
598                                 }
599                                 if ($depends{$p}{$dep} & $IkiWiki::DEPEND_PRESENCE) {
600                                         last if $reason = 
601                                                 $in->(\@exists_changed, $IkiWiki::DEPEND_PRESENCE);
602                                         last if $internal_dep && ($reason =
603                                                 $in->($internal_new, $IkiWiki::DEPEND_PRESENCE) ||
604                                                 $in->($internal_del, $IkiWiki::DEPEND_PRESENCE));
605                                 }
606                                 if ($depends{$p}{$dep} & $IkiWiki::DEPEND_LINKS) {
607                                         last if $reason =
608                                                 $in->(\@changed, $IkiWiki::DEPEND_LINKS);
609                                         last if $internal_dep && ($reason =
610                                                 $in->($internal_new, $IkiWiki::DEPEND_LINKS) ||
611                                                 $in->($internal_del, $IkiWiki::DEPEND_LINKS) ||
612                                                 $in->($internal_changed, $IkiWiki::DEPEND_LINKS));
613                                 }
614                         }
615                 }
616         
617                 if (defined $reason) {
618                         render($f, sprintf(gettext("building %s, which depends on %s"), $f, $reason));
619                         return 1;
620                 }
621         }
622
623         return 0;
624 }
625
626 sub render_backlinks ($) {
627         my $backlinkchanged=shift;
628         foreach my $link (keys %$backlinkchanged) {
629                 my $linkfile=$pagesources{$link};
630                 if (defined $linkfile) {
631                         render($linkfile, sprintf(gettext("building %s, to update its backlinks"), $linkfile));
632                 }
633         }
634 }
635
636 sub refresh () {
637         srcdir_check();
638         run_hooks(refresh => sub { shift->() });
639         my ($files, $pages)=find_src_files();
640         my ($new, $internal_new)=find_new_files($files);
641         my ($del, $internal_del)=find_del_files($pages);
642         my ($changed, $internal_changed)=find_changed($files);
643         run_hooks(needsbuild => sub { shift->($changed) });
644         my $oldlink_targets=calculate_old_links($changed, $del);
645
646         foreach my $file (@$changed) {
647                 scan($file);
648         }
649
650         calculate_links();
651         
652         remove_del(@$del, @$internal_del);
653
654         foreach my $file (@$changed) {
655                 render($file, sprintf(gettext("building %s"), $file));
656         }
657         foreach my $file (@$internal_new, @$internal_del, @$internal_changed) {
658                 derender_internal($file);
659         }
660
661         my ($backlinkchanged, $linkchangers)=calculate_changed_links($changed,
662                 $del, $oldlink_targets);
663
664         foreach my $file (@$new, @$del) {
665                 render_linkers($file);
666         }
667         
668         if (@$changed || @$internal_changed ||
669             @$del || @$internal_del || @$internal_new) {
670                 1 while render_dependent($files, $new, $internal_new,
671                         $del, $internal_del, $internal_changed,
672                         $linkchangers);
673         }
674
675         render_backlinks($backlinkchanged);
676         remove_unrendered();
677
678         if (@$del) {
679                 run_hooks(delete => sub { shift->(@$del) });
680         }
681         if (%rendered) {
682                 run_hooks(change => sub { shift->(keys %rendered) });
683         }
684 }
685
686 sub clean_rendered {
687         lockwiki();
688         loadindex();
689         remove_unrendered();
690         foreach my $page (keys %oldrenderedfiles) {
691                 foreach my $file (@{$oldrenderedfiles{$page}}) {
692                         prune($config{destdir}."/".$file);
693                 }
694         }
695 }
696
697 sub commandline_render () {
698         lockwiki();
699         loadindex();
700         unlockwiki();
701
702         my $srcfile=possibly_foolish_untaint($config{render});
703         my $file=$srcfile;
704         $file=~s/\Q$config{srcdir}\E\/?//;
705
706         my $type=pagetype($file);
707         die sprintf(gettext("ikiwiki: cannot build %s"), $srcfile)."\n" unless defined $type;
708         my $content=readfile($srcfile);
709         my $page=pagename($file);
710         $pagesources{$page}=$file;
711         $content=filter($page, $page, $content);
712         $content=preprocess($page, $page, $content);
713         $content=linkify($page, $page, $content);
714         $content=htmlize($page, $page, $type, $content);
715         $pagemtime{$page}=(stat($srcfile))[9];
716         $pagectime{$page}=$pagemtime{$page} if ! exists $pagectime{$page};
717
718         print genpage($page, $content);
719         exit 0;
720 }
721
722 1