* Fix re-rendering of pages when a linked to page goes away. This was broken
[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 my $backlinks_calculated=0;
12
13 sub calculate_backlinks () { #{{{
14         return if $backlinks_calculated;
15         %backlinks=();
16         foreach my $page (keys %links) {
17                 foreach my $link (@{$links{$page}}) {
18                         my $bestlink=bestlink($page, $link);
19                         if (length $bestlink && $bestlink ne $page) {
20                                 $backlinks{$bestlink}{$page}=1;
21                         }
22                 }
23         }
24         $backlinks_calculated=1;
25 } #}}}
26
27 sub backlinks ($) { #{{{
28         my $page=shift;
29
30         calculate_backlinks();
31
32         my @links;
33         foreach my $p (keys %{$backlinks{$page}}) {
34                 my $href=urlto($p, $page);
35                 
36                 # Trim common dir prefixes from both pages.
37                 my $p_trimmed=$p;
38                 my $page_trimmed=$page;
39                 my $dir;
40                 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
41                         defined $dir &&
42                         $p_trimmed=~s/^\Q$dir\E// &&
43                         $page_trimmed=~s/^\Q$dir\E//;
44                                
45                 push @links, { url => $href, page => pagetitle($p_trimmed) };
46         }
47         return @links;
48 } #}}}
49
50 sub parentlinks ($) { #{{{
51         my $page=shift;
52         
53         my @ret;
54         my $pagelink="";
55         my $path="";
56         my $title=$config{wikiname};
57         
58         return if $page eq 'index'; # toplevel
59         foreach my $dir (split("/", $page)) {
60                 push @ret, { url => urlto($path, $page), page => $title };
61                 $path.="/".$dir;
62                 $title=pagetitle($dir);
63         }
64         return @ret;
65 } #}}}
66
67 sub genpage ($$$) { #{{{
68         my $page=shift;
69         my $content=shift;
70         my $mtime=shift;
71
72         my $template=template("page.tmpl", blind_cache => 1);
73         my $actions=0;
74
75         if (length $config{cgiurl}) {
76                 $template->param(editurl => cgiurl(do => "edit", page => pagetitle($page, 1)));
77                 $template->param(prefsurl => cgiurl(do => "prefs"));
78                 if ($config{rcs}) {
79                         $template->param(recentchangesurl => cgiurl(do => "recentchanges"));
80                 }
81                 $actions++;
82         }
83
84         if (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                 my $discussionlink=gettext("discussion");
92                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
93                    (length $config{cgiurl} ||
94                     exists $links{$page."/".$discussionlink})) {
95                         $template->param(discussionlink => htmllink($page, $page, gettext("Discussion"), noimageinline => 1, forcesubpage => 1));
96                         $actions++;
97                 }
98         }
99
100         if ($actions) {
101                 $template->param(have_actions => 1);
102         }
103
104         my @backlinks=sort { $a->{page} cmp $b->{page} } backlinks($page);
105         my ($backlinks, $more_backlinks);
106         if (@backlinks <= $config{numbacklinks} || ! $config{numbacklinks}) {
107                 $backlinks=\@backlinks;
108                 $more_backlinks=[];
109         }
110         else {
111                 $backlinks=[@backlinks[0..$config{numbacklinks}-1]];
112                 $more_backlinks=[@backlinks[$config{numbacklinks}..$#backlinks]];
113         }
114
115         $template->param(
116                 title => $page eq 'index' 
117                         ? $config{wikiname} 
118                         : pagetitle(basename($page)),
119                 wikiname => $config{wikiname},
120                 parentlinks => [parentlinks($page)],
121                 content => $content,
122                 backlinks => $backlinks,
123                 more_backlinks => $more_backlinks,
124                 mtime => displaytime($mtime),
125                 baseurl => baseurl($page),
126         );
127
128         run_hooks(pagetemplate => sub {
129                 shift->(page => $page, destpage => $page, template => $template);
130         });
131         
132         $content=$template->output;
133
134         run_hooks(format => sub {
135                 $content=shift->(
136                         page => $page,
137                         content => $content,
138                 );
139         });
140
141         return $content;
142 } #}}}
143
144 sub mtime ($) { #{{{
145         my $file=shift;
146         
147         return (stat($file))[9];
148 } #}}}
149
150 sub scan ($) { #{{{
151         my $file=shift;
152
153         my $type=pagetype($file);
154         if (defined $type) {
155                 my $srcfile=srcfile($file);
156                 my $content=readfile($srcfile);
157                 my $page=pagename($file);
158                 will_render($page, htmlpage($page), 1);
159
160                 # Always needs to be done, since filters might add links
161                 # to the content.
162                 $content=filter($page, $page, $content);
163
164                 my @links;
165                 while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
166                         push @links, linkpage($2);
167                 }
168                 if ($config{discussion}) {
169                         # Discussion links are a special case since they're
170                         # not in the text of the page, but on its template.
171                         push @links, $page."/".gettext("discussion");
172                 }
173                 $links{$page}=\@links;
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 render ($) { #{{{
184         my $file=shift;
185         
186         my $type=pagetype($file);
187         my $srcfile=srcfile($file);
188         if (defined $type) {
189                 my $page=pagename($file);
190                 delete $depends{$page};
191                 will_render($page, htmlpage($page), 1);
192                 
193                 my $content=htmlize($page, $type,
194                         linkify($page, $page,
195                         preprocess($page, $page,
196                         filter($page, $page,
197                         readfile($srcfile)))));
198                 
199                 writefile(htmlpage($page), $config{destdir},
200                         genpage($page, $content, mtime($srcfile)));
201         }
202         else {
203                 my $srcfd=readfile($srcfile, 1, 1);
204                 delete $depends{$file};
205                 will_render($file, $file, 1);
206                 writefile($file, $config{destdir}, undef, 1, sub {
207                         my $destfd=shift;
208                         my $cleanup=shift;
209
210                         my $blksize = 16384;
211                         my ($len, $buf, $written);
212                         while ($len = sysread $srcfd, $buf, $blksize) {
213                                 if (! defined $len) {
214                                         next if $! =~ /^Interrupted/;
215                                         error("failed to read $srcfile: $!", $cleanup);
216                                 }
217                                 my $offset = 0;
218                                 while ($len) {
219                                         defined($written = syswrite $destfd, $buf, $len, $offset)
220                                                 or error("failed to write $file: $!", $cleanup);
221                                         $len -= $written;
222                                         $offset += $written;
223                                 }
224                         }
225                 });
226         }
227 } #}}}
228
229 sub prune ($) { #{{{
230         my $file=shift;
231
232         unlink($file);
233         my $dir=dirname($file);
234         while (rmdir($dir)) {
235                 $dir=dirname($dir);
236         }
237 } #}}}
238
239 sub refresh () { #{{{
240         # find existing pages
241         my %exists;
242         my @files;
243         eval q{use File::Find};
244         error($@) if $@;
245         find({
246                 no_chdir => 1,
247                 wanted => sub {
248                         $_=decode_utf8($_);
249                         if (file_pruned($_, $config{srcdir})) {
250                                 $File::Find::prune=1;
251                         }
252                         elsif (! -d $_ && ! -l $_) {
253                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
254                                 if (! defined $f) {
255                                         warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
256                                 }
257                                 else {
258                                         $f=~s/^\Q$config{srcdir}\E\/?//;
259                                         push @files, $f;
260                                         $exists{pagename($f)}=1;
261                                 }
262                         }
263                 },
264         }, $config{srcdir});
265         find({
266                 no_chdir => 1,
267                 wanted => sub {
268                         $_=decode_utf8($_);
269                         if (file_pruned($_, $config{underlaydir})) {
270                                 $File::Find::prune=1;
271                         }
272                         elsif (! -d $_ && ! -l $_) {
273                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
274                                 if (! defined $f) {
275                                         warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
276                                 }
277                                 else {
278                                         # Don't add pages that are in the
279                                         # srcdir.
280                                         $f=~s/^\Q$config{underlaydir}\E\/?//;
281                                         if (! -e "$config{srcdir}/$f" && 
282                                             ! -l "$config{srcdir}/$f") {
283                                                 my $page=pagename($f);
284                                                 if (! $exists{$page}) {
285                                                         push @files, $f;
286                                                         $exists{$page}=1;
287                                                 }
288                                         }
289                                 }
290                         }
291                 },
292         }, $config{underlaydir});
293
294         my %rendered;
295
296         # check for added or removed pages
297         my @add;
298         foreach my $file (@files) {
299                 my $page=pagename($file);
300                 $pagesources{$page}=$file;
301                 if (! $pagemtime{$page}) {
302                         push @add, $file;
303                         $pagecase{lc $page}=$page;
304                         if ($config{getctime} && -e "$config{srcdir}/$file") {
305                                 $pagectime{$page}=rcs_getctime("$config{srcdir}/$file");
306                         }
307                         elsif (! exists $pagectime{$page}) {
308                                 $pagectime{$page}=mtime(srcfile($file));
309                         }
310                 }
311         }
312         my @del;
313         foreach my $page (keys %pagemtime) {
314                 if (! $exists{$page}) {
315                         debug(sprintf(gettext("removing old page %s"), $page));
316                         push @del, $pagesources{$page};
317                         $links{$page}=[];
318                         $renderedfiles{$page}=[];
319                         $pagemtime{$page}=0;
320                         prune($config{destdir}."/".$_)
321                                 foreach @{$oldrenderedfiles{$page}};
322                         delete $pagesources{$page};
323                         foreach (keys %destsources) {
324                                 if ($destsources{$_} eq $page) {
325                                         delete $destsources{$_};
326                                 }
327                         }
328                 }
329         }
330
331         # find changed and new files
332         my @needsbuild;
333         foreach my $file (@files) {
334                 my $page=pagename($file);
335                 
336                 my $mtime=mtime(srcfile($file));
337                 if (! exists $pagemtime{$page} ||
338                     $mtime > $pagemtime{$page} ||
339                     $forcerebuild{$page}) {
340                         $pagemtime{$page}=$mtime;
341                         push @needsbuild, $file;
342                 }
343         }
344         run_hooks(needsbuild => sub { shift->(\@needsbuild) });
345
346         # scan and rendder files
347         foreach my $file (@needsbuild) {
348                 debug(sprintf(gettext("scanning %s"), $file));
349                 scan($file);
350         }
351         calculate_backlinks();
352         foreach my $file (@needsbuild) {
353                 debug(sprintf(gettext("rendering %s"), $file));
354                 render($file);
355                 $rendered{$file}=1;
356         }
357         
358         # rebuild pages that link to added or removed pages
359         if (@add || @del) {
360                 foreach my $f (@add, @del) {
361                         my $p=pagename($f);
362                         foreach my $page (keys %{$backlinks{$p}}) {
363                                 my $file=$pagesources{$page};
364                                 next if $rendered{$file};
365                                 debug(sprintf(gettext("rendering %s, which links to %s"), $file, $p));
366                                 render($file);
367                                 $rendered{$file}=1;
368                         }
369                 }
370         }
371
372         if (%rendered || @del) {
373                 # rebuild dependant pages
374                 foreach my $f (@files) {
375                         next if $rendered{$f};
376                         my $p=pagename($f);
377                         if (exists $depends{$p}) {
378                                 foreach my $file (keys %rendered, @del) {
379                                         next if $f eq $file;
380                                         my $page=pagename($file);
381                                         if (pagespec_match($page, $depends{$p}, location => $p)) {
382                                                 debug(sprintf(gettext("rendering %s, which depends on %s"), $f, $page));
383                                                 render($f);
384                                                 $rendered{$f}=1;
385                                                 last;
386                                         }
387                                 }
388                         }
389                 }
390                 
391                 # handle backlinks; if a page has added/removed links,
392                 # update the pages it links to
393                 my %linkchanged;
394                 foreach my $file (keys %rendered, @del) {
395                         my $page=pagename($file);
396                         
397                         if (exists $links{$page}) {
398                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
399                                         if (length $link &&
400                                             (! exists $oldlinks{$page} ||
401                                              ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
402                                                 $linkchanged{$link}=1;
403                                         }
404                                 }
405                         }
406                         if (exists $oldlinks{$page}) {
407                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
408                                         if (length $link &&
409                                             (! exists $links{$page} || 
410                                              ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
411                                                 $linkchanged{$link}=1;
412                                         }
413                                 }
414                         }
415                 }
416                 foreach my $link (keys %linkchanged) {
417                         my $linkfile=$pagesources{$link};
418                         if (defined $linkfile) {
419                                 next if $rendered{$linkfile};
420                                 debug(sprintf(gettext("rendering %s, to update its backlinks"), $linkfile));
421                                 render($linkfile);
422                                 $rendered{$linkfile}=1;
423                         }
424                 }
425         }
426
427         # remove no longer rendered files
428         foreach my $src (keys %rendered) {
429                 my $page=pagename($src);
430                 foreach my $file (@{$oldrenderedfiles{$page}}) {
431                         if (! grep { $_ eq $file } @{$renderedfiles{$page}}) {
432                                 debug(sprintf(gettext("removing %s, no longer rendered by %s"), $file, $page));
433                                 prune($config{destdir}."/".$file);
434                         }
435                 }
436         }
437
438         if (@del) {
439                 run_hooks(delete => sub { shift->(@del) });
440         }
441         if (%rendered) {
442                 run_hooks(change => sub { shift->(keys %rendered) });
443         }
444 } #}}}
445
446 sub commandline_render () { #{{{
447         loadplugins();
448         checkconfig();
449         lockwiki();
450         loadindex();
451         unlockwiki();
452
453         my $srcfile=possibly_foolish_untaint($config{render});
454         my $file=$srcfile;
455         $file=~s/\Q$config{srcdir}\E\/?//;
456
457         my $type=pagetype($file);
458         die sprintf(gettext("ikiwiki: cannot render %s"), $srcfile)."\n" unless defined $type;
459         my $content=readfile($srcfile);
460         my $page=pagename($file);
461         $pagesources{$page}=$file;
462         $content=filter($page, $page, $content);
463         $content=preprocess($page, $page, $content);
464         $content=linkify($page, $page, $content);
465         $content=htmlize($page, $type, $content);
466
467         print genpage($page, $content, mtime($srcfile));
468         exit 0;
469 } #}}}
470
471 1