releasing version 2.40
[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                 $actions++;
86         }
87                 
88         if (length $config{historyurl}) {
89                 my $u=$config{historyurl};
90                 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
91                 $template->param(historyurl => $u);
92                 $actions++;
93         }
94         if ($config{discussion}) {
95                 my $discussionlink=gettext("discussion");
96                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
97                    (length $config{cgiurl} ||
98                     exists $links{$page."/".$discussionlink})) {
99                         $template->param(discussionlink => htmllink($page, $page, gettext("Discussion"), noimageinline => 1, forcesubpage => 1));
100                         $actions++;
101                 }
102         }
103
104         if ($actions) {
105                 $template->param(have_actions => 1);
106         }
107
108         my @backlinks=sort { $a->{page} cmp $b->{page} } backlinks($page);
109         my ($backlinks, $more_backlinks);
110         if (@backlinks <= $config{numbacklinks} || ! $config{numbacklinks}) {
111                 $backlinks=\@backlinks;
112                 $more_backlinks=[];
113         }
114         else {
115                 $backlinks=[@backlinks[0..$config{numbacklinks}-1]];
116                 $more_backlinks=[@backlinks[$config{numbacklinks}..$#backlinks]];
117         }
118
119         $template->param(
120                 title => $page eq 'index' 
121                         ? $config{wikiname} 
122                         : pagetitle(basename($page)),
123                 wikiname => $config{wikiname},
124                 parentlinks => [parentlinks($page)],
125                 content => $content,
126                 backlinks => $backlinks,
127                 more_backlinks => $more_backlinks,
128                 mtime => displaytime($pagemtime{$page}),
129                 ctime => displaytime($pagectime{$page}),
130                 baseurl => baseurl($page),
131         );
132
133         run_hooks(pagetemplate => sub {
134                 shift->(page => $page, destpage => $page, template => $template);
135         });
136         
137         $content=$template->output;
138
139         run_hooks(format => sub {
140                 $content=shift->(
141                         page => $page,
142                         content => $content,
143                 );
144         });
145
146         return $content;
147 } #}}}
148
149 sub mtime ($) { #{{{
150         my $file=shift;
151         
152         return (stat($file))[9];
153 } #}}}
154
155 sub scan ($) { #{{{
156         my $file=shift;
157
158         my $type=pagetype($file);
159         if (defined $type) {
160                 my $srcfile=srcfile($file);
161                 my $content=readfile($srcfile);
162                 my $page=pagename($file);
163                 will_render($page, htmlpage($page), 1);
164
165                 # Always needs to be done, since filters might add links
166                 # to the content.
167                 $content=filter($page, $page, $content);
168         
169                 if ($config{discussion}) {
170                         # Discussion links are a special case since they're
171                         # not in the text of the page, but on its template.
172                         $links{$page}=[ $page."/".gettext("discussion") ];
173                 }
174                 else {
175                         $links{$page}=[];
176                 }
177
178                 run_hooks(scan => sub {
179                         shift->(
180                                 page => $page,
181                                 content => $content,
182                         );
183                 });
184
185                 # Preprocess in scan-only mode.
186                 preprocess($page, $page, $content, 1);
187         }
188         else {
189                 will_render($file, $file, 1);
190         }
191 } #}}}
192
193 sub render ($) { #{{{
194         my $file=shift;
195         
196         my $type=pagetype($file);
197         my $srcfile=srcfile($file);
198         if (defined $type) {
199                 my $page=pagename($file);
200                 delete $depends{$page};
201                 will_render($page, htmlpage($page), 1);
202                 return if $type=~/^_/;
203                 
204                 my $content=htmlize($page, $type,
205                         linkify($page, $page,
206                         preprocess($page, $page,
207                         filter($page, $page,
208                         readfile($srcfile)))));
209                 
210                 my $output=htmlpage($page);
211                 writefile($output, $config{destdir}, genpage($page, $content));
212         }
213         else {
214                 my $srcfd=readfile($srcfile, 1, 1);
215                 delete $depends{$file};
216                 will_render($file, $file, 1);
217                 writefile($file, $config{destdir}, undef, 1, sub {
218                         my $destfd=shift;
219                         my $cleanup=shift;
220
221                         my $blksize = 16384;
222                         my ($len, $buf, $written);
223                         while ($len = sysread $srcfd, $buf, $blksize) {
224                                 if (! defined $len) {
225                                         next if $! =~ /^Interrupted/;
226                                         error("failed to read $srcfile: $!", $cleanup);
227                                 }
228                                 my $offset = 0;
229                                 while ($len) {
230                                         defined($written = syswrite $destfd, $buf, $len, $offset)
231                                                 or error("failed to write $file: $!", $cleanup);
232                                         $len -= $written;
233                                         $offset += $written;
234                                 }
235                         }
236                 });
237         }
238 } #}}}
239
240 sub prune ($) { #{{{
241         my $file=shift;
242
243         unlink($file);
244         my $dir=dirname($file);
245         while (rmdir($dir)) {
246                 $dir=dirname($dir);
247         }
248 } #}}}
249
250 sub refresh () { #{{{
251         # security check, avoid following symlinks in the srcdir path
252         my $test=$config{srcdir};
253         while (length $test) {
254                 if (-l $test) {
255                         error("symlink found in srcdir path ($test)");
256                 }
257                 unless ($test=~s/\/+$//) {
258                         $test=dirname($test);
259                 }
260         }
261         
262         run_hooks(refresh => sub { shift->() });
263
264         # find existing pages
265         my %exists;
266         my @files;
267         eval q{use File::Find};
268         error($@) if $@;
269         find({
270                 no_chdir => 1,
271                 wanted => sub {
272                         $_=decode_utf8($_);
273                         if (file_pruned($_, $config{srcdir})) {
274                                 $File::Find::prune=1;
275                         }
276                         elsif (! -d $_ && ! -l $_) {
277                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
278                                 if (! defined $f) {
279                                         warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
280                                 }
281                                 else {
282                                         $f=~s/^\Q$config{srcdir}\E\/?//;
283                                         push @files, $f;
284                                         $exists{pagename($f)}=1;
285                                 }
286                         }
287                 },
288         }, $config{srcdir});
289         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
290                 find({
291                         no_chdir => 1,
292                         wanted => sub {
293                                 $_=decode_utf8($_);
294                                 if (file_pruned($_, $dir)) {
295                                         $File::Find::prune=1;
296                                 }
297                                 elsif (! -d $_ && ! -l $_) {
298                                         my ($f)=/$config{wiki_file_regexp}/; # untaint
299                                         if (! defined $f) {
300                                                 warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
301                                         }
302                                         else {
303                                                 $f=~s/^\Q$dir\E\/?//;
304                                                 # avoid underlaydir
305                                                 # override attacks; see
306                                                 # security.mdwn
307                                                 if (! -e "$config{srcdir}/$f" && 
308                                                     ! -l "$config{srcdir}/$f") {
309                                                         my $page=pagename($f);
310                                                         if (! $exists{$page}) {
311                                                                 push @files, $f;
312                                                                 $exists{$page}=1;
313                                                         }
314                                                 }
315                                         }
316                                 }
317                         },
318                 }, $dir);
319         };
320
321         my (%rendered, @add, @del, @internal);
322
323         # check for added or removed pages
324         foreach my $file (@files) {
325                 my $page=pagename($file);
326                 $pagesources{$page}=$file;
327                 if (! $pagemtime{$page}) {
328                         if (isinternal($page)) {
329                                 push @internal, $file;
330                         }
331                         else {
332                                 push @add, $file;
333                                 if ($config{getctime} && -e "$config{srcdir}/$file") {
334                                         eval {
335                                                 my $time=rcs_getctime("$config{srcdir}/$file");
336                                                 $pagectime{$page}=$time;
337                                         };
338                                         if ($@) {
339                                                 print STDERR $@;
340                                         }
341                                 }
342                         }
343                         $pagecase{lc $page}=$page;
344                         if (! exists $pagectime{$page}) {
345                                 $pagectime{$page}=mtime(srcfile($file));
346                         }
347                 }
348         }
349         foreach my $page (keys %pagemtime) {
350                 if (! $exists{$page}) {
351                         if (isinternal($page)) {
352                                 push @internal, $pagesources{$page};
353                         }
354                         else {
355                                 debug(sprintf(gettext("removing old page %s"), $page));
356                                 push @del, $pagesources{$page};
357                         }
358                         $links{$page}=[];
359                         $renderedfiles{$page}=[];
360                         $pagemtime{$page}=0;
361                         prune($config{destdir}."/".$_)
362                                 foreach @{$oldrenderedfiles{$page}};
363                         delete $pagesources{$page};
364                         foreach (keys %destsources) {
365                                 if ($destsources{$_} eq $page) {
366                                         delete $destsources{$_};
367                                 }
368                         }
369                 }
370         }
371
372         # find changed and new files
373         my @needsbuild;
374         foreach my $file (@files) {
375                 my $page=pagename($file);
376                 
377                 my $mtime=mtime(srcfile($file));
378                 if (! exists $pagemtime{$page} ||
379                     $mtime > $pagemtime{$page} ||
380                     $forcerebuild{$page}) {
381                         $pagemtime{$page}=$mtime;
382                         if (isinternal($page)) {
383                                 push @internal, $file;
384                                 # Preprocess internal page in scan-only mode.
385                                 preprocess($page, $page, readfile(srcfile($file)), 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         loadplugins();
510         checkconfig();
511         lockwiki();
512         loadindex();
513         unlockwiki();
514
515         my $srcfile=possibly_foolish_untaint($config{render});
516         my $file=$srcfile;
517         $file=~s/\Q$config{srcdir}\E\/?//;
518
519         my $type=pagetype($file);
520         die sprintf(gettext("ikiwiki: cannot render %s"), $srcfile)."\n" unless defined $type;
521         my $content=readfile($srcfile);
522         my $page=pagename($file);
523         $pagesources{$page}=$file;
524         $content=filter($page, $page, $content);
525         $content=preprocess($page, $page, $content);
526         $content=linkify($page, $page, $content);
527         $content=htmlize($page, $type, $content);
528         $pagemtime{$page}=mtime($srcfile);
529
530         print genpage($page, $content);
531         exit 0;
532 } #}}}
533
534 1