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