finalize release
[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 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         my $type=pagetype($file);
151         if (defined $type) {
152                 my $srcfile=srcfile($file);
153                 my $content=readfile($srcfile);
154                 my $page=pagename($file);
155                 will_render($page, htmlpage($page), 1);
156
157                 if ($config{discussion}) {
158                         # Discussion links are a special case since they're
159                         # not in the text of the page, but on its template.
160                         $links{$page}=[ $page."/".lc($config{discussionpage}) ];
161                 }
162                 else {
163                         $links{$page}=[];
164                 }
165
166                 run_hooks(scan => sub {
167                         shift->(
168                                 page => $page,
169                                 content => $content,
170                         );
171                 });
172
173                 # Preprocess in scan-only mode.
174                 preprocess($page, $page, $content, 1);
175         }
176         else {
177                 will_render($file, $file, 1);
178         }
179 }
180
181 sub fast_file_copy (@) {
182         my $srcfile=shift;
183         my $destfile=shift;
184         my $srcfd=shift;
185         my $destfd=shift;
186         my $cleanup=shift;
187
188         my $blksize = 16384;
189         my ($len, $buf, $written);
190         while ($len = sysread $srcfd, $buf, $blksize) {
191                 if (! defined $len) {
192                         next if $! =~ /^Interrupted/;
193                         error("failed to read $srcfile: $!", $cleanup);
194                 }
195                 my $offset = 0;
196                 while ($len) {
197                         defined($written = syswrite $destfd, $buf, $len, $offset)
198                                 or error("failed to write $destfile: $!", $cleanup);
199                         $len -= $written;
200                         $offset += $written;
201                 }
202         }
203 }
204
205 sub render ($) {
206         my $file=shift;
207         
208         my $type=pagetype($file);
209         my $srcfile=srcfile($file);
210         if (defined $type) {
211                 my $page=pagename($file);
212                 delete $depends{$page};
213                 delete $depends_simple{$page};
214                 will_render($page, htmlpage($page), 1);
215                 return if $type=~/^_/;
216                 
217                 my $content=htmlize($page, $page, $type,
218                         linkify($page, $page,
219                         preprocess($page, $page,
220                         filter($page, $page,
221                         readfile($srcfile)))));
222                 
223                 my $output=htmlpage($page);
224                 writefile($output, $config{destdir}, genpage($page, $content));
225         }
226         else {
227                 delete $depends{$file};
228                 delete $depends_simple{$file};
229                 will_render($file, $file, 1);
230                 
231                 if ($config{hardlink}) {
232                         # only hardlink if owned by same user
233                         my @stat=stat($srcfile);
234                         if ($stat[4] == $>) {
235                                 prep_writefile($file, $config{destdir});
236                                 unlink($config{destdir}."/".$file);
237                                 if (link($srcfile, $config{destdir}."/".$file)) {
238                                         return;
239                                 }
240                         }
241                         # if hardlink fails, fall back to copying
242                 }
243                 
244                 my $srcfd=readfile($srcfile, 1, 1);
245                 writefile($file, $config{destdir}, undef, 1, sub {
246                         fast_file_copy($srcfile, $file, $srcfd, @_);
247                 });
248         }
249 }
250
251 sub prune ($) {
252         my $file=shift;
253
254         unlink($file);
255         my $dir=dirname($file);
256         while (rmdir($dir)) {
257                 $dir=dirname($dir);
258         }
259 }
260
261 sub srcdir_check () {
262         # security check, avoid following symlinks in the srcdir path by default
263         my $test=$config{srcdir};
264         while (length $test) {
265                 if (-l $test && ! $config{allow_symlinks_before_srcdir}) {
266                         error(sprintf(gettext("symlink found in srcdir path (%s) -- set allow_symlinks_before_srcdir to allow this"), $test));
267                 }
268                 unless ($test=~s/\/+$//) {
269                         $test=dirname($test);
270                 }
271         }
272         
273 }
274
275 sub find_src_files () {
276         my (@files, %pages);
277         eval q{use File::Find};
278         error($@) if $@;
279         find({
280                 no_chdir => 1,
281                 wanted => sub {
282                         $_=decode_utf8($_);
283                         if (file_pruned($_, $config{srcdir})) {
284                                 $File::Find::prune=1;
285                         }
286                         elsif (! -l $_ && ! -d _) {
287                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
288                                 if (! defined $f) {
289                                         warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
290                                 }
291                                 else {
292                                         $f=~s/^\Q$config{srcdir}\E\/?//;
293                                         push @files, $f;
294                                         my $pagename = pagename($f);
295                                         if ($pages{$pagename}) {
296                                                 debug(sprintf(gettext("%s has multiple possible source pages"), $pagename));
297                                         }
298                                         $pages{$pagename}=1;
299                                 }
300                         }
301                 },
302         }, $config{srcdir});
303         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
304                 find({
305                         no_chdir => 1,
306                         wanted => sub {
307                                 $_=decode_utf8($_);
308                                 if (file_pruned($_, $dir)) {
309                                         $File::Find::prune=1;
310                                 }
311                                 elsif (! -l $_ && ! -d _) {
312                                         my ($f)=/$config{wiki_file_regexp}/; # untaint
313                                         if (! defined $f) {
314                                                 warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
315                                         }
316                                         else {
317                                                 $f=~s/^\Q$dir\E\/?//;
318                                                 # avoid underlaydir
319                                                 # override attacks; see
320                                                 # security.mdwn
321                                                 if (! -l "$config{srcdir}/$f" && 
322                                                     ! -e _) {
323                                                         my $page=pagename($f);
324                                                         if (! $pages{$page}) {
325                                                                 push @files, $f;
326                                                                 $pages{$page}=1;
327                                                         }
328                                                 }
329                                         }
330                                 }
331                         },
332                 }, $dir);
333         };
334
335         # Returns a list of all source files found, and a hash of 
336         # the corresponding page names.
337         return \@files, \%pages;
338 }
339
340 sub refresh () {
341         srcdir_check();
342         run_hooks(refresh => sub { shift->() });
343         my ($files, $exists)=find_src_files();
344
345         my (%rendered, @add, @del, @internal);
346         # check for added or removed pages
347         foreach my $file (@$files) {
348                 my $page=pagename($file);
349                 if (exists $pagesources{$page} && $pagesources{$page} ne $file) {
350                         # the page has changed its type
351                         $forcerebuild{$page}=1;
352                 }
353                 $pagesources{$page}=$file;
354                 if (! $pagemtime{$page}) {
355                         if (isinternal($page)) {
356                                 push @internal, $file;
357                         }
358                         else {
359                                 push @add, $file;
360                                 if ($config{getctime} && -e "$config{srcdir}/$file") {
361                                         eval {
362                                                 my $time=rcs_getctime("$config{srcdir}/$file");
363                                                 $pagectime{$page}=$time;
364                                         };
365                                         if ($@) {
366                                                 print STDERR $@;
367                                         }
368                                 }
369                         }
370                         $pagecase{lc $page}=$page;
371                         if (! exists $pagectime{$page}) {
372                                 $pagectime{$page}=(srcfile_stat($file))[10];
373                         }
374                 }
375         }
376         foreach my $page (keys %pagemtime) {
377                 if (! $exists->{$page}) {
378                         if (isinternal($page)) {
379                                 push @internal, $pagesources{$page};
380                         }
381                         else {
382                                 debug(sprintf(gettext("removing old page %s"), $page));
383                                 push @del, $pagesources{$page};
384                         }
385                         $links{$page}=[];
386                         $renderedfiles{$page}=[];
387                         $pagemtime{$page}=0;
388                         foreach my $old (@{$oldrenderedfiles{$page}}) {
389                                 prune($config{destdir}."/".$old);
390                         }
391                         delete $pagesources{$page};
392                         foreach my $source (keys %destsources) {
393                                 if ($destsources{$source} eq $page) {
394                                         delete $destsources{$source};
395                                 }
396                         }
397                 }
398         }
399
400         # find changed and new files
401         my @needsbuild;
402         foreach my $file (@$files) {
403                 my $page=pagename($file);
404                 my ($srcfile, @stat)=srcfile_stat($file);
405                 if (! exists $pagemtime{$page} ||
406                     $stat[9] > $pagemtime{$page} ||
407                     $forcerebuild{$page}) {
408                         $pagemtime{$page}=$stat[9];
409                         if (isinternal($page)) {
410                                 push @internal, $file;
411                                 # Preprocess internal page in scan-only mode.
412                                 preprocess($page, $page, readfile($srcfile), 1);
413                         }
414                         else {
415                                 push @needsbuild, $file;
416                         }
417                 }
418         }
419         run_hooks(needsbuild => sub { shift->(\@needsbuild) });
420
421         # scan and render files
422         foreach my $file (@needsbuild) {
423                 debug(sprintf(gettext("scanning %s"), $file));
424                 scan($file);
425         }
426         calculate_links();
427         foreach my $file (@needsbuild) {
428                 debug(sprintf(gettext("building %s"), $file));
429                 render($file);
430                 $rendered{$file}=1;
431         }
432         foreach my $file (@internal) {
433                 # internal pages are not rendered
434                 my $page=pagename($file);
435                 delete $depends{$page};
436                 delete $depends_simple{$page};
437                 foreach my $old (@{$renderedfiles{$page}}) {
438                         delete $destsources{$old};
439                 }
440                 $renderedfiles{$page}=[];
441         }
442         
443         # rebuild pages that link to added or removed pages
444         if (@add || @del) {
445                 foreach my $f (@add, @del) {
446                         my $p=pagename($f);
447                         foreach my $page (keys %{$backlinks{$p}}) {
448                                 my $file=$pagesources{$page};
449                                 next if $rendered{$file};
450                                 debug(sprintf(gettext("building %s, which links to %s"), $file, $p));
451                                 render($file);
452                                 $rendered{$file}=1;
453                         }
454                 }
455         }
456
457         if (%rendered || @del || @internal) {
458                 my @changed=(keys %rendered, @del);
459
460                 my %lcchanged = map { lc(pagename($_)) => 1 } @changed;
461  
462                 # rebuild dependant pages
463                 foreach my $f (@$files) {
464                         next if $rendered{$f};
465                         my $p=pagename($f);
466                         my $reason = undef;
467
468                         if (exists $depends_simple{$p}) {
469                                 foreach my $d (keys %{$depends_simple{$p}}) {
470                                         if (exists $lcchanged{$d}) {
471                                                 $reason = $d;
472                                                 last;
473                                         }
474                                 }
475                         }
476
477                         if (exists $depends{$p} && ! defined $reason) {
478                                 D: foreach my $d (keys %{$depends{$p}}) {
479                                         my $sub=pagespec_translate($d);
480                                         next if $@ || ! defined $sub;
481
482                                         # only consider internal files
483                                         # if the page explicitly depends
484                                         # on such files
485                                         foreach my $file (@changed, $d =~ /internal\(/ ? @internal : ()) {
486                                                 next if $file eq $f;
487                                                 my $page=pagename($file);
488                                                 if ($sub->($page, location => $p)) {
489                                                         $reason = $page;
490                                                         last D;
491                                                 }
492                                         }
493                                 }
494                         }
495
496                         if (defined $reason) {
497                                 debug(sprintf(gettext("building %s, which depends on %s"), $f, $reason));
498                                 render($f);
499                                 $rendered{$f}=1;
500                         }
501                 }
502                 
503                 # handle backlinks; if a page has added/removed links,
504                 # update the pages it links to
505                 my %linkchanged;
506                 foreach my $file (@changed) {
507                         my $page=pagename($file);
508                         
509                         if (exists $links{$page}) {
510                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
511                                         if (length $link &&
512                                             (! exists $oldlinks{$page} ||
513                                              ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
514                                                 $linkchanged{$link}=1;
515                                         }
516                                 }
517                         }
518                         if (exists $oldlinks{$page}) {
519                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
520                                         if (length $link &&
521                                             (! exists $links{$page} || 
522                                              ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
523                                                 $linkchanged{$link}=1;
524                                         }
525                                 }
526                         }
527                 }
528
529                 foreach my $link (keys %linkchanged) {
530                         my $linkfile=$pagesources{$link};
531                         if (defined $linkfile) {
532                                 next if $rendered{$linkfile};
533                                 debug(sprintf(gettext("building %s, to update its backlinks"), $linkfile));
534                                 render($linkfile);
535                                 $rendered{$linkfile}=1;
536                         }
537                 }
538         }
539
540         # remove no longer rendered files
541         foreach my $src (keys %rendered) {
542                 my $page=pagename($src);
543                 foreach my $file (@{$oldrenderedfiles{$page}}) {
544                         if (! grep { $_ eq $file } @{$renderedfiles{$page}}) {
545                                 debug(sprintf(gettext("removing %s, no longer built by %s"), $file, $page));
546                                 prune($config{destdir}."/".$file);
547                         }
548                 }
549         }
550
551         if (@del) {
552                 run_hooks(delete => sub { shift->(@del) });
553         }
554         if (%rendered) {
555                 run_hooks(change => sub { shift->(keys %rendered) });
556         }
557 }
558
559 sub commandline_render () {
560         lockwiki();
561         loadindex();
562         unlockwiki();
563
564         my $srcfile=possibly_foolish_untaint($config{render});
565         my $file=$srcfile;
566         $file=~s/\Q$config{srcdir}\E\/?//;
567
568         my $type=pagetype($file);
569         die sprintf(gettext("ikiwiki: cannot build %s"), $srcfile)."\n" unless defined $type;
570         my $content=readfile($srcfile);
571         my $page=pagename($file);
572         $pagesources{$page}=$file;
573         $content=filter($page, $page, $content);
574         $content=preprocess($page, $page, $content);
575         $content=linkify($page, $page, $content);
576         $content=htmlize($page, $page, $type, $content);
577         $pagemtime{$page}=(stat($srcfile))[9];
578         $pagectime{$page}=$pagemtime{$page} if ! exists $pagectime{$page};
579
580         print genpage($page, $content);
581         exit 0;
582 }
583
584 1