response
[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         foreach my $dir (split("/", $page)) {
59                 next if $dir eq 'index';
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
71         my $templatefile;
72         run_hooks(templatefile => sub {
73                 return if defined $templatefile;
74                 my $file=shift->(page => $page);
75                 if (defined $file && defined template_file($file)) {
76                         $templatefile=$file;
77                 }
78         });
79         my $template=template(defined $templatefile ? $templatefile : 'page.tmpl', blind_cache => 1);
80         my $actions=0;
81
82         if (length $config{cgiurl}) {
83                 $template->param(editurl => cgiurl(do => "edit", page => pagetitle($page, 1)));
84                 $template->param(prefsurl => cgiurl(do => "prefs"));
85                 if ($config{rcs}) {
86                         $template->param(recentchangesurl => cgiurl(do => "recentchanges"));
87                 }
88                 $actions++;
89         }
90
91         if (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                 my $discussionlink=gettext("discussion");
99                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
100                    (length $config{cgiurl} ||
101                     exists $links{$page."/".$discussionlink})) {
102                         $template->param(discussionlink => htmllink($page, $page, gettext("Discussion"), noimageinline => 1, forcesubpage => 1));
103                         $actions++;
104                 }
105         }
106
107         if ($actions) {
108                 $template->param(have_actions => 1);
109         }
110
111         my @backlinks=sort { $a->{page} cmp $b->{page} } backlinks($page);
112         my ($backlinks, $more_backlinks);
113         if (@backlinks <= $config{numbacklinks} || ! $config{numbacklinks}) {
114                 $backlinks=\@backlinks;
115                 $more_backlinks=[];
116         }
117         else {
118                 $backlinks=[@backlinks[0..$config{numbacklinks}-1]];
119                 $more_backlinks=[@backlinks[$config{numbacklinks}..$#backlinks]];
120         }
121
122         $template->param(
123                 title => $page eq 'index' 
124                         ? $config{wikiname} 
125                         : pagetitle(basename($page)),
126                 wikiname => $config{wikiname},
127                 parentlinks => [parentlinks($page)],
128                 content => $content,
129                 backlinks => $backlinks,
130                 more_backlinks => $more_backlinks,
131                 mtime => displaytime($pagemtime{$page}),
132                 baseurl => baseurl($page),
133         );
134
135         run_hooks(pagetemplate => sub {
136                 shift->(page => $page, destpage => $page, template => $template);
137         });
138         
139         $content=$template->output;
140
141         run_hooks(format => sub {
142                 $content=shift->(
143                         page => $page,
144                         content => $content,
145                 );
146         });
147
148         return $content;
149 } #}}}
150
151 sub mtime ($) { #{{{
152         my $file=shift;
153         
154         return (stat($file))[9];
155 } #}}}
156
157 sub scan ($) { #{{{
158         my $file=shift;
159
160         my $type=pagetype($file);
161         if (defined $type) {
162                 my $srcfile=srcfile($file);
163                 my $content=readfile($srcfile);
164                 my $page=pagename($file);
165                 will_render($page, htmlpage($page), 1);
166
167                 # Always needs to be done, since filters might add links
168                 # to the content.
169                 $content=filter($page, $page, $content);
170
171                 my @links;
172                 while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
173                         push @links, linkpage($2);
174                 }
175                 if ($config{discussion}) {
176                         # Discussion links are a special case since they're
177                         # not in the text of the page, but on its template.
178                         push @links, $page."/".gettext("discussion");
179                 }
180                 $links{$page}=\@links;
181                 
182                 # Preprocess in scan-only mode.
183                 preprocess($page, $page, $content, 1);
184         }
185         else {
186                 will_render($file, $file, 1);
187         }
188 } #}}}
189
190 sub render ($) { #{{{
191         my $file=shift;
192         
193         my $type=pagetype($file);
194         my $srcfile=srcfile($file);
195         if (defined $type) {
196                 my $page=pagename($file);
197                 delete $depends{$page};
198                 will_render($page, htmlpage($page), 1);
199                 
200                 my $content=htmlize($page, $type,
201                         linkify($page, $page,
202                         preprocess($page, $page,
203                         filter($page, $page,
204                         readfile($srcfile)))));
205                 
206                 my $output=htmlpage($page);
207                 writefile($output, $config{destdir}, genpage($page, $content));
208                 utime($pagemtime{$page}, $pagemtime{$page}, $config{destdir}."/".$output);
209         }
210         else {
211                 my $srcfd=readfile($srcfile, 1, 1);
212                 delete $depends{$file};
213                 will_render($file, $file, 1);
214                 writefile($file, $config{destdir}, undef, 1, sub {
215                         my $destfd=shift;
216                         my $cleanup=shift;
217
218                         my $blksize = 16384;
219                         my ($len, $buf, $written);
220                         while ($len = sysread $srcfd, $buf, $blksize) {
221                                 if (! defined $len) {
222                                         next if $! =~ /^Interrupted/;
223                                         error("failed to read $srcfile: $!", $cleanup);
224                                 }
225                                 my $offset = 0;
226                                 while ($len) {
227                                         defined($written = syswrite $destfd, $buf, $len, $offset)
228                                                 or error("failed to write $file: $!", $cleanup);
229                                         $len -= $written;
230                                         $offset += $written;
231                                 }
232                         }
233                 });
234                 utime($pagemtime{$file}, $pagemtime{$file}, $config{destdir}."/".$file);
235         }
236 } #}}}
237
238 sub prune ($) { #{{{
239         my $file=shift;
240
241         unlink($file);
242         my $dir=dirname($file);
243         while (rmdir($dir)) {
244                 $dir=dirname($dir);
245         }
246 } #}}}
247
248 sub refresh () { #{{{
249         # security check, avoid following symlinks in the srcdir path
250         my $test=$config{srcdir};
251         while (length $test) {
252                 if (-l $test) {
253                         error("symlink found in srcdir path ($test)");
254                 }
255                 unless ($test=~s/\/+$//) {
256                         $test=dirname($test);
257                 }
258         }
259
260         # find existing pages
261         my %exists;
262         my @files;
263         eval q{use File::Find};
264         error($@) if $@;
265         find({
266                 no_chdir => 1,
267                 wanted => sub {
268                         $_=decode_utf8($_);
269                         if (file_pruned($_, $config{srcdir})) {
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                                         $f=~s/^\Q$config{srcdir}\E\/?//;
279                                         push @files, $f;
280                                         $exists{pagename($f)}=1;
281                                 }
282                         }
283                 },
284         }, $config{srcdir});
285         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
286                 find({
287                         no_chdir => 1,
288                         wanted => sub {
289                                 $_=decode_utf8($_);
290                                 if (file_pruned($_, $dir)) {
291                                         $File::Find::prune=1;
292                                 }
293                                 elsif (! -d $_ && ! -l $_) {
294                                         my ($f)=/$config{wiki_file_regexp}/; # untaint
295                                         if (! defined $f) {
296                                                 warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
297                                         }
298                                         else {
299                                                 $f=~s/^\Q$dir\E\/?//;
300                                                 # avoid underlaydir
301                                                 # override attacks; see
302                                                 # security.mdwn
303                                                 if (! -e "$config{srcdir}/$f" && 
304                                                     ! -l "$config{srcdir}/$f") {
305                                                         my $page=pagename($f);
306                                                         if (! $exists{$page}) {
307                                                                 push @files, $f;
308                                                                 $exists{$page}=1;
309                                                         }
310                                                 }
311                                         }
312                                 }
313                         },
314                 }, $dir);
315         };
316
317         my %rendered;
318
319         # check for added or removed pages
320         my @add;
321         foreach my $file (@files) {
322                 my $page=pagename($file);
323                 $pagesources{$page}=$file;
324                 if (! $pagemtime{$page}) {
325                         push @add, $file;
326                         $pagecase{lc $page}=$page;
327                         if ($config{getctime} && -e "$config{srcdir}/$file") {
328                                 $pagectime{$page}=rcs_getctime("$config{srcdir}/$file");
329                         }
330                         elsif (! exists $pagectime{$page}) {
331                                 $pagectime{$page}=mtime(srcfile($file));
332                         }
333                 }
334         }
335         my @del;
336         foreach my $page (keys %pagemtime) {
337                 if (! $exists{$page}) {
338                         debug(sprintf(gettext("removing old page %s"), $page));
339                         push @del, $pagesources{$page};
340                         $links{$page}=[];
341                         $renderedfiles{$page}=[];
342                         $pagemtime{$page}=0;
343                         prune($config{destdir}."/".$_)
344                                 foreach @{$oldrenderedfiles{$page}};
345                         delete $pagesources{$page};
346                         foreach (keys %destsources) {
347                                 if ($destsources{$_} eq $page) {
348                                         delete $destsources{$_};
349                                 }
350                         }
351                 }
352         }
353
354         # find changed and new files
355         my @needsbuild;
356         foreach my $file (@files) {
357                 my $page=pagename($file);
358                 
359                 my $mtime=mtime(srcfile($file));
360                 if (! exists $pagemtime{$page} ||
361                     $mtime > $pagemtime{$page} ||
362                     $forcerebuild{$page}) {
363                         $pagemtime{$page}=$mtime;
364                         push @needsbuild, $file;
365                 }
366         }
367         run_hooks(needsbuild => sub { shift->(\@needsbuild) });
368
369         # scan and render files
370         foreach my $file (@needsbuild) {
371                 debug(sprintf(gettext("scanning %s"), $file));
372                 scan($file);
373         }
374         calculate_backlinks();
375         foreach my $file (@needsbuild) {
376                 debug(sprintf(gettext("rendering %s"), $file));
377                 render($file);
378                 $rendered{$file}=1;
379         }
380         
381         # rebuild pages that link to added or removed pages
382         if (@add || @del) {
383                 foreach my $f (@add, @del) {
384                         my $p=pagename($f);
385                         foreach my $page (keys %{$backlinks{$p}}) {
386                                 my $file=$pagesources{$page};
387                                 next if $rendered{$file};
388                                 debug(sprintf(gettext("rendering %s, which links to %s"), $file, $p));
389                                 render($file);
390                                 $rendered{$file}=1;
391                         }
392                 }
393         }
394
395         if (%rendered || @del) {
396                 # rebuild dependant pages
397                 foreach my $f (@files) {
398                         next if $rendered{$f};
399                         my $p=pagename($f);
400                         if (exists $depends{$p}) {
401                                 foreach my $file (keys %rendered, @del) {
402                                         next if $f eq $file;
403                                         my $page=pagename($file);
404                                         if (pagespec_match($page, $depends{$p}, location => $p)) {
405                                                 debug(sprintf(gettext("rendering %s, which depends on %s"), $f, $page));
406                                                 render($f);
407                                                 $rendered{$f}=1;
408                                                 last;
409                                         }
410                                 }
411                         }
412                 }
413                 
414                 # handle backlinks; if a page has added/removed links,
415                 # update the pages it links to
416                 my %linkchanged;
417                 foreach my $file (keys %rendered, @del) {
418                         my $page=pagename($file);
419                         
420                         if (exists $links{$page}) {
421                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
422                                         if (length $link &&
423                                             (! exists $oldlinks{$page} ||
424                                              ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
425                                                 $linkchanged{$link}=1;
426                                         }
427                                 }
428                         }
429                         if (exists $oldlinks{$page}) {
430                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
431                                         if (length $link &&
432                                             (! exists $links{$page} || 
433                                              ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
434                                                 $linkchanged{$link}=1;
435                                         }
436                                 }
437                         }
438                 }
439                 foreach my $link (keys %linkchanged) {
440                         my $linkfile=$pagesources{$link};
441                         if (defined $linkfile) {
442                                 next if $rendered{$linkfile};
443                                 debug(sprintf(gettext("rendering %s, to update its backlinks"), $linkfile));
444                                 render($linkfile);
445                                 $rendered{$linkfile}=1;
446                         }
447                 }
448         }
449
450         # remove no longer rendered files
451         foreach my $src (keys %rendered) {
452                 my $page=pagename($src);
453                 foreach my $file (@{$oldrenderedfiles{$page}}) {
454                         if (! grep { $_ eq $file } @{$renderedfiles{$page}}) {
455                                 debug(sprintf(gettext("removing %s, no longer rendered by %s"), $file, $page));
456                                 prune($config{destdir}."/".$file);
457                         }
458                 }
459         }
460
461         if (@del) {
462                 run_hooks(delete => sub { shift->(@del) });
463         }
464         if (%rendered) {
465                 run_hooks(change => sub { shift->(keys %rendered) });
466         }
467 } #}}}
468
469 sub commandline_render () { #{{{
470         loadplugins();
471         checkconfig();
472         lockwiki();
473         loadindex();
474         unlockwiki();
475
476         my $srcfile=possibly_foolish_untaint($config{render});
477         my $file=$srcfile;
478         $file=~s/\Q$config{srcdir}\E\/?//;
479
480         my $type=pagetype($file);
481         die sprintf(gettext("ikiwiki: cannot render %s"), $srcfile)."\n" unless defined $type;
482         my $content=readfile($srcfile);
483         my $page=pagename($file);
484         $pagesources{$page}=$file;
485         $content=filter($page, $page, $content);
486         $content=preprocess($page, $page, $content);
487         $content=linkify($page, $page, $content);
488         $content=htmlize($page, $type, $content);
489         $pagemtime{$page}=mtime($srcfile);
490
491         print genpage($page, $content);
492         exit 0;
493 } #}}}
494
495 1