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