fix add_depends to new api
[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;
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 find_changed_links (@_) {
62         my %linkchanged;
63         my %linkchangers;
64         foreach my $file (@_) {
65                 my $page=pagename($file);
66                 
67                 if (exists $links{$page}) {
68                         foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
69                                 if (length $link &&
70                                     (! exists $oldlinks{$page} ||
71                                      ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
72                                         $linkchanged{$link}=1;
73                                         $linkchangers{lc($page)}=1;
74                                 }
75                         }
76                 }
77                 if (exists $oldlinks{$page}) {
78                         foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
79                                 if (length $link &&
80                                     (! exists $links{$page} || 
81                                      ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
82                                         $linkchanged{$link}=1;
83                                         $linkchangers{lc($page)}=1;
84                                 }
85                         }
86                 }
87         }
88
89         return \%linkchanged, \%linkchangers;
90 }
91
92 sub genpage ($$) {
93         my $page=shift;
94         my $content=shift;
95
96         my $templatefile;
97         run_hooks(templatefile => sub {
98                 return if defined $templatefile;
99                 my $file=shift->(page => $page);
100                 if (defined $file && defined template_file($file)) {
101                         $templatefile=$file;
102                 }
103         });
104         my $template=template(defined $templatefile ? $templatefile : 'page.tmpl', blind_cache => 1);
105         my $actions=0;
106
107         if (length $config{cgiurl}) {
108                 $template->param(editurl => cgiurl(do => "edit", page => $page))
109                         if IkiWiki->can("cgi_editpage");
110                 $template->param(prefsurl => cgiurl(do => "prefs"))
111                         if exists $hooks{auth};
112                 $actions++;
113         }
114                 
115         if (defined $config{historyurl} && length $config{historyurl}) {
116                 my $u=$config{historyurl};
117                 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
118                 $template->param(historyurl => $u);
119                 $actions++;
120         }
121         if ($config{discussion}) {
122                 if ($page !~ /.*\/\Q$config{discussionpage}\E$/ &&
123                    (length $config{cgiurl} ||
124                     exists $links{$page."/".$config{discussionpage}})) {
125                         $template->param(discussionlink => htmllink($page, $page, $config{discussionpage}, noimageinline => 1, forcesubpage => 1));
126                         $actions++;
127                 }
128         }
129
130         if ($actions) {
131                 $template->param(have_actions => 1);
132         }
133
134         my @backlinks=sort { $a->{page} cmp $b->{page} } backlinks($page);
135         my ($backlinks, $more_backlinks);
136         if (@backlinks <= $config{numbacklinks} || ! $config{numbacklinks}) {
137                 $backlinks=\@backlinks;
138                 $more_backlinks=[];
139         }
140         else {
141                 $backlinks=[@backlinks[0..$config{numbacklinks}-1]];
142                 $more_backlinks=[@backlinks[$config{numbacklinks}..$#backlinks]];
143         }
144
145         $template->param(
146                 title => $page eq 'index' 
147                         ? $config{wikiname} 
148                         : pagetitle(basename($page)),
149                 wikiname => $config{wikiname},
150                 content => $content,
151                 backlinks => $backlinks,
152                 more_backlinks => $more_backlinks,
153                 mtime => displaytime($pagemtime{$page}),
154                 ctime => displaytime($pagectime{$page}),
155                 baseurl => baseurl($page),
156         );
157
158         run_hooks(pagetemplate => sub {
159                 shift->(page => $page, destpage => $page, template => $template);
160         });
161         
162         $content=$template->output;
163         
164         run_hooks(postscan => sub {
165                 shift->(page => $page, content => $content);
166         });
167
168         run_hooks(format => sub {
169                 $content=shift->(
170                         page => $page,
171                         content => $content,
172                 );
173         });
174
175         return $content;
176 }
177
178 sub scan ($) {
179         my $file=shift;
180
181         my $type=pagetype($file);
182         if (defined $type) {
183                 my $srcfile=srcfile($file);
184                 my $content=readfile($srcfile);
185                 my $page=pagename($file);
186                 will_render($page, htmlpage($page), 1);
187
188                 if ($config{discussion}) {
189                         # Discussion links are a special case since they're
190                         # not in the text of the page, but on its template.
191                         $links{$page}=[ $page."/".lc($config{discussionpage}) ];
192                 }
193                 else {
194                         $links{$page}=[];
195                 }
196
197                 run_hooks(scan => sub {
198                         shift->(
199                                 page => $page,
200                                 content => $content,
201                         );
202                 });
203
204                 # Preprocess in scan-only mode.
205                 preprocess($page, $page, $content, 1);
206         }
207         else {
208                 will_render($file, $file, 1);
209         }
210 }
211
212 sub fast_file_copy (@) {
213         my $srcfile=shift;
214         my $destfile=shift;
215         my $srcfd=shift;
216         my $destfd=shift;
217         my $cleanup=shift;
218
219         my $blksize = 16384;
220         my ($len, $buf, $written);
221         while ($len = sysread $srcfd, $buf, $blksize) {
222                 if (! defined $len) {
223                         next if $! =~ /^Interrupted/;
224                         error("failed to read $srcfile: $!", $cleanup);
225                 }
226                 my $offset = 0;
227                 while ($len) {
228                         defined($written = syswrite $destfd, $buf, $len, $offset)
229                                 or error("failed to write $destfile: $!", $cleanup);
230                         $len -= $written;
231                         $offset += $written;
232                 }
233         }
234 }
235
236 sub render ($) {
237         my $file=shift;
238         
239         my $type=pagetype($file);
240         my $srcfile=srcfile($file);
241         if (defined $type) {
242                 my $page=pagename($file);
243                 delete $depends{$page};
244                 delete $depends_simple{$page};
245                 will_render($page, htmlpage($page), 1);
246                 return if $type=~/^_/;
247                 
248                 my $content=htmlize($page, $page, $type,
249                         linkify($page, $page,
250                         preprocess($page, $page,
251                         filter($page, $page,
252                         readfile($srcfile)))));
253                 
254                 my $output=htmlpage($page);
255                 writefile($output, $config{destdir}, genpage($page, $content));
256         }
257         else {
258                 delete $depends{$file};
259                 delete $depends_simple{$file};
260                 will_render($file, $file, 1);
261                 
262                 if ($config{hardlink}) {
263                         # only hardlink if owned by same user
264                         my @stat=stat($srcfile);
265                         if ($stat[4] == $>) {
266                                 prep_writefile($file, $config{destdir});
267                                 unlink($config{destdir}."/".$file);
268                                 if (link($srcfile, $config{destdir}."/".$file)) {
269                                         return;
270                                 }
271                         }
272                         # if hardlink fails, fall back to copying
273                 }
274                 
275                 my $srcfd=readfile($srcfile, 1, 1);
276                 writefile($file, $config{destdir}, undef, 1, sub {
277                         fast_file_copy($srcfile, $file, $srcfd, @_);
278                 });
279         }
280 }
281
282 sub prune ($) {
283         my $file=shift;
284
285         unlink($file);
286         my $dir=dirname($file);
287         while (rmdir($dir)) {
288                 $dir=dirname($dir);
289         }
290 }
291
292 sub srcdir_check () {
293         # security check, avoid following symlinks in the srcdir path by default
294         my $test=$config{srcdir};
295         while (length $test) {
296                 if (-l $test && ! $config{allow_symlinks_before_srcdir}) {
297                         error(sprintf(gettext("symlink found in srcdir path (%s) -- set allow_symlinks_before_srcdir to allow this"), $test));
298                 }
299                 unless ($test=~s/\/+$//) {
300                         $test=dirname($test);
301                 }
302         }
303         
304 }
305
306 sub find_src_files () {
307         my (@files, %pages);
308         eval q{use File::Find};
309         error($@) if $@;
310         find({
311                 no_chdir => 1,
312                 wanted => sub {
313                         $_=decode_utf8($_);
314                         if (file_pruned($_, $config{srcdir})) {
315                                 $File::Find::prune=1;
316                         }
317                         elsif (! -l $_ && ! -d _) {
318                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
319                                 if (! defined $f) {
320                                         warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
321                                 }
322                                 else {
323                                         $f=~s/^\Q$config{srcdir}\E\/?//;
324                                         push @files, $f;
325                                         my $pagename = pagename($f);
326                                         if ($pages{$pagename}) {
327                                                 debug(sprintf(gettext("%s has multiple possible source pages"), $pagename));
328                                         }
329                                         $pages{$pagename}=1;
330                                 }
331                         }
332                 },
333         }, $config{srcdir});
334         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
335                 find({
336                         no_chdir => 1,
337                         wanted => sub {
338                                 $_=decode_utf8($_);
339                                 if (file_pruned($_, $dir)) {
340                                         $File::Find::prune=1;
341                                 }
342                                 elsif (! -l $_ && ! -d _) {
343                                         my ($f)=/$config{wiki_file_regexp}/; # untaint
344                                         if (! defined $f) {
345                                                 warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
346                                         }
347                                         else {
348                                                 $f=~s/^\Q$dir\E\/?//;
349                                                 # avoid underlaydir
350                                                 # override attacks; see
351                                                 # security.mdwn
352                                                 if (! -l "$config{srcdir}/$f" && 
353                                                     ! -e _) {
354                                                         my $page=pagename($f);
355                                                         if (! $pages{$page}) {
356                                                                 push @files, $f;
357                                                                 $pages{$page}=1;
358                                                         }
359                                                 }
360                                         }
361                                 }
362                         },
363                 }, $dir);
364         };
365
366         # Returns a list of all source files found, and a hash of 
367         # the corresponding page names.
368         return \@files, \%pages;
369 }
370
371 sub refresh () {
372         srcdir_check();
373         run_hooks(refresh => sub { shift->() });
374         my ($files, $exists)=find_src_files();
375
376         my (%rendered, @add, @del, @internal, @internal_change);
377         # check for added or removed pages
378         foreach my $file (@$files) {
379                 my $page=pagename($file);
380                 if (exists $pagesources{$page} && $pagesources{$page} ne $file) {
381                         # the page has changed its type
382                         $forcerebuild{$page}=1;
383                 }
384                 $pagesources{$page}=$file;
385                 if (! $pagemtime{$page}) {
386                         if (isinternal($page)) {
387                                 push @internal, $file;
388                         }
389                         else {
390                                 push @add, $file;
391                                 if ($config{getctime} && -e "$config{srcdir}/$file") {
392                                         eval {
393                                                 my $time=rcs_getctime("$config{srcdir}/$file");
394                                                 $pagectime{$page}=$time;
395                                         };
396                                         if ($@) {
397                                                 print STDERR $@;
398                                         }
399                                 }
400                         }
401                         $pagecase{lc $page}=$page;
402                         if (! exists $pagectime{$page}) {
403                                 $pagectime{$page}=(srcfile_stat($file))[10];
404                         }
405                 }
406         }
407         foreach my $page (keys %pagemtime) {
408                 if (! $exists->{$page}) {
409                         if (isinternal($page)) {
410                                 push @internal, $pagesources{$page};
411                         }
412                         else {
413                                 debug(sprintf(gettext("removing old page %s"), $page));
414                                 push @del, $pagesources{$page};
415                         }
416                         $links{$page}=[];
417                         $renderedfiles{$page}=[];
418                         $pagemtime{$page}=0;
419                         foreach my $old (@{$oldrenderedfiles{$page}}) {
420                                 prune($config{destdir}."/".$old);
421                         }
422                         delete $pagesources{$page};
423                         foreach my $source (keys %destsources) {
424                                 if ($destsources{$source} eq $page) {
425                                         delete $destsources{$source};
426                                 }
427                         }
428                 }
429         }
430
431         # find changed and new files
432         my @needsbuild;
433         foreach my $file (@$files) {
434                 my $page=pagename($file);
435                 my ($srcfile, @stat)=srcfile_stat($file);
436                 if (! exists $pagemtime{$page} ||
437                     $stat[9] > $pagemtime{$page} ||
438                     $forcerebuild{$page}) {
439                         $pagemtime{$page}=$stat[9];
440                         if (isinternal($page)) {
441                                 push @internal_change, $file;
442                                 # Preprocess internal page in scan-only mode.
443                                 preprocess($page, $page, readfile($srcfile), 1);
444                         }
445                         else {
446                                 push @needsbuild, $file;
447                         }
448                 }
449         }
450         run_hooks(needsbuild => sub { shift->(\@needsbuild) });
451
452         # scan and render files
453         foreach my $file (@needsbuild) {
454                 debug(sprintf(gettext("scanning %s"), $file));
455                 scan($file);
456         }
457         calculate_links();
458         foreach my $file (@needsbuild) {
459                 debug(sprintf(gettext("building %s"), $file));
460                 render($file);
461                 $rendered{$file}=1;
462         }
463         foreach my $file (@internal, @internal_change) {
464                 # internal pages are not rendered
465                 my $page=pagename($file);
466                 delete $depends{$page};
467                 delete $depends_simple{$page};
468                 foreach my $old (@{$renderedfiles{$page}}) {
469                         delete $destsources{$old};
470                 }
471                 $renderedfiles{$page}=[];
472         }
473         
474         # rebuild pages that link to added or removed pages
475         if (@add || @del) {
476                 foreach my $f (@add, @del) {
477                         my $p=pagename($f);
478                         foreach my $page (keys %{$backlinks{$p}}) {
479                                 my $file=$pagesources{$page};
480                                 next if $rendered{$file};
481                                 debug(sprintf(gettext("building %s, which links to %s"), $file, $p));
482                                 render($file);
483                                 $rendered{$file}=1;
484                         }
485                 }
486         }
487
488         if (%rendered || @del || @internal || @internal_change) {
489                 my @changed=(keys %rendered, @del);
490                 my ($linkchanged, $linkchangers)=find_changed_links(@changed);
491
492                 my $unsettled;
493                 do {
494                         $unsettled=0;
495                         @changed=(keys %rendered, @del);
496                         my @exists_changed=(@add, @del);
497         
498                         my %lc_changed = map { lc(pagename($_)) => 1 } @changed;
499                         my %lc_exists_changed = map { lc(pagename($_)) => 1 } @exists_changed;
500          
501                         # rebuild dependant pages
502                         foreach my $f (@$files) {
503                                 next if $rendered{$f};
504                                 my $p=pagename($f);
505                                 my $reason = undef;
506         
507                                 if (exists $depends_simple{$p}) {
508                                         foreach my $d (keys %{$depends_simple{$p}}) {
509                                                 if (($depends_simple{$p}{$d} & $IkiWiki::DEPEND_CONTENT &&
510                                                      $lc_changed{$d})
511                                                     ||
512                                                     ($depends_simple{$p}{$d} & $IkiWiki::DEPEND_PRESENCE &&
513                                                      $lc_exists_changed{$d})
514                                                     ||
515                                                     ($depends_simple{$p}{$d} & $IkiWiki::DEPEND_LINKS &&
516                                                      $linkchangers->{$d})
517                                                 ) {
518                                                         $reason = $d;
519                                                         last;
520                                                 }
521                                         }
522                                 }
523         
524                                 if (exists $depends{$p} && ! defined $reason) {
525                                         D: foreach my $d (keys %{$depends{$p}}) {
526                                                 my $sub=pagespec_translate($d);
527                                                 next if $@ || ! defined $sub;
528         
529                                                 # only consider internal files
530                                                 # if the page explicitly depends
531                                                 # on such files
532                                                 my $internal_dep=$d =~ /internal\(/;
533
534                                                 my @candidates;
535                                                 if ($depends{$p}{$d} & $IkiWiki::DEPEND_PRESENCE) {
536                                                         @candidates=@exists_changed;
537                                                         push @candidates, @internal
538                                                                 if $internal_dep;
539                                                 }
540                                                 if (($depends{$p}{$d} & ($IkiWiki::DEPEND_CONTENT | $IkiWiki::DEPEND_LINKS))) {
541                                                         @candidates=@changed;
542                                                         push @candidates, @internal, @internal_change
543                                                                 if $internal_dep;
544                                                 }
545
546                                                 foreach my $file (@candidates) {
547                                                         next if $file eq $f;
548                                                         my $page=pagename($file);
549                                                         if ($sub->($page, location => $p)) {
550                                                                 if ($depends{$p}{$d} & $IkiWiki::DEPEND_LINKS) {
551                                                                         next unless $linkchangers->{lc($page)};
552                                                                 }
553                                                                 $reason = $page;
554                                                                 last D;
555                                                         }
556                                                 }
557                                         }
558                                 }
559         
560                                 if (defined $reason) {
561                                         debug(sprintf(gettext("building %s, which depends on %s"), $f, $reason));
562                                         render($f);
563                                         $rendered{$f}=1;
564                                         $unsettled=1;
565                                         last;
566                                 }
567                         }
568                 } while $unsettled;
569                 
570                 # update backlinks at end
571                 foreach my $link (keys %{$linkchanged}) {
572                         my $linkfile=$pagesources{$link};
573                         if (defined $linkfile) {
574                                 next if $rendered{$linkfile};
575                                 debug(sprintf(gettext("building %s, to update its backlinks"), $linkfile));
576                                 render($linkfile);
577                                 $rendered{$linkfile}=1;
578                         }
579                 }
580         }
581
582         # remove no longer rendered files
583         foreach my $src (keys %rendered) {
584                 my $page=pagename($src);
585                 foreach my $file (@{$oldrenderedfiles{$page}}) {
586                         if (! grep { $_ eq $file } @{$renderedfiles{$page}}) {
587                                 debug(sprintf(gettext("removing %s, no longer built by %s"), $file, $page));
588                                 prune($config{destdir}."/".$file);
589                         }
590                 }
591         }
592
593         if (@del) {
594                 run_hooks(delete => sub { shift->(@del) });
595         }
596         if (%rendered) {
597                 run_hooks(change => sub { shift->(keys %rendered) });
598         }
599 }
600
601 sub commandline_render () {
602         lockwiki();
603         loadindex();
604         unlockwiki();
605
606         my $srcfile=possibly_foolish_untaint($config{render});
607         my $file=$srcfile;
608         $file=~s/\Q$config{srcdir}\E\/?//;
609
610         my $type=pagetype($file);
611         die sprintf(gettext("ikiwiki: cannot build %s"), $srcfile)."\n" unless defined $type;
612         my $content=readfile($srcfile);
613         my $page=pagename($file);
614         $pagesources{$page}=$file;
615         $content=filter($page, $page, $content);
616         $content=preprocess($page, $page, $content);
617         $content=linkify($page, $page, $content);
618         $content=htmlize($page, $page, $type, $content);
619         $pagemtime{$page}=(stat($srcfile))[9];
620         $pagectime{$page}=$pagemtime{$page} if ! exists $pagectime{$page};
621
622         print genpage($page, $content);
623         exit 0;
624 }
625
626 1