web commit by http://jcflack.myopenid.com/
[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 scan ($) { #{{{
150         my $file=shift;
151
152         my $type=pagetype($file);
153         if (defined $type) {
154                 my $srcfile=srcfile($file);
155                 my $content=readfile($srcfile);
156                 my $page=pagename($file);
157                 will_render($page, htmlpage($page), 1);
158
159                 if ($config{discussion}) {
160                         # Discussion links are a special case since they're
161                         # not in the text of the page, but on its template.
162                         $links{$page}=[ $page."/".gettext("discussion") ];
163                 }
164                 else {
165                         $links{$page}=[];
166                 }
167
168                 run_hooks(scan => sub {
169                         shift->(
170                                 page => $page,
171                                 content => $content,
172                         );
173                 });
174
175                 # Preprocess in scan-only mode.
176                 preprocess($page, $page, $content, 1);
177         }
178         else {
179                 will_render($file, $file, 1);
180         }
181 } #}}}
182
183 sub render ($) { #{{{
184         my $file=shift;
185         
186         my $type=pagetype($file);
187         my $srcfile=srcfile($file);
188         if (defined $type) {
189                 my $page=pagename($file);
190                 delete $depends{$page};
191                 will_render($page, htmlpage($page), 1);
192                 return if $type=~/^_/;
193                 
194                 my $content=htmlize($page, $page, $type,
195                         linkify($page, $page,
196                         preprocess($page, $page,
197                         filter($page, $page,
198                         readfile($srcfile)))));
199                 
200                 my $output=htmlpage($page);
201                 writefile($output, $config{destdir}, genpage($page, $content));
202         }
203         else {
204                 delete $depends{$file};
205                 will_render($file, $file, 1);
206                 
207                 if ($config{hardlink}) {
208                         prep_writefile($file, $config{destdir});
209                         unlink($config{destdir}."/".$file);
210                         if (link($srcfile, $config{destdir}."/".$file)) {
211                                 return;
212                         }
213                         # if hardlink fails, fall back to copying
214                 }
215                 
216                 my $srcfd=readfile($srcfile, 1, 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 (! -l $_ && ! -d _) {
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 (! -l $_ && ! -d _) {
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 (! -l "$config{srcdir}/$f" && 
308                                                     ! -e _) {
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         # check for added or removed pages
323         foreach my $file (@files) {
324                 my $page=pagename($file);
325                 $pagesources{$page}=$file;
326                 if (! $pagemtime{$page}) {
327                         if (isinternal($page)) {
328                                 push @internal, $file;
329                         }
330                         else {
331                                 push @add, $file;
332                                 if ($config{getctime} && -e "$config{srcdir}/$file") {
333                                         eval {
334                                                 my $time=rcs_getctime("$config{srcdir}/$file");
335                                                 $pagectime{$page}=$time;
336                                         };
337                                         if ($@) {
338                                                 print STDERR $@;
339                                         }
340                                 }
341                         }
342                         $pagecase{lc $page}=$page;
343                         if (! exists $pagectime{$page}) {
344                                 $pagectime{$page}=(srcfile_stat($file))[10];
345                         }
346                 }
347         }
348         foreach my $page (keys %pagemtime) {
349                 if (! $exists{$page}) {
350                         if (isinternal($page)) {
351                                 push @internal, $pagesources{$page};
352                         }
353                         else {
354                                 debug(sprintf(gettext("removing old page %s"), $page));
355                                 push @del, $pagesources{$page};
356                         }
357                         $links{$page}=[];
358                         $renderedfiles{$page}=[];
359                         $pagemtime{$page}=0;
360                         prune($config{destdir}."/".$_)
361                                 foreach @{$oldrenderedfiles{$page}};
362                         delete $pagesources{$page};
363                         foreach (keys %destsources) {
364                                 if ($destsources{$_} eq $page) {
365                                         delete $destsources{$_};
366                                 }
367                         }
368                 }
369         }
370
371         # find changed and new files
372         my @needsbuild;
373         foreach my $file (@files) {
374                 my $page=pagename($file);
375                 my ($srcfile, @stat)=srcfile_stat($file);
376                 if (! exists $pagemtime{$page} ||
377                     $stat[9] > $pagemtime{$page} ||
378                     $forcerebuild{$page}) {
379                         $pagemtime{$page}=$stat[9];
380                         if (isinternal($page)) {
381                                 push @internal, $file;
382                                 # Preprocess internal page in scan-only mode.
383                                 preprocess($page, $page, readfile($srcfile), 1);
384                         }
385                         else {
386                                 push @needsbuild, $file;
387                         }
388                 }
389         }
390         run_hooks(needsbuild => sub { shift->(\@needsbuild) });
391
392         # scan and render files
393         foreach my $file (@needsbuild) {
394                 debug(sprintf(gettext("scanning %s"), $file));
395                 scan($file);
396         }
397         calculate_backlinks();
398         foreach my $file (@needsbuild) {
399                 debug(sprintf(gettext("rendering %s"), $file));
400                 render($file);
401                 $rendered{$file}=1;
402         }
403         foreach my $file (@internal) {
404                 # internal pages are not rendered
405                 my $page=pagename($file);
406                 delete $depends{$page};
407                 foreach my $old (@{$renderedfiles{$page}}) {
408                         delete $destsources{$old};
409                 }
410                 $renderedfiles{$page}=[];
411         }
412         
413         # rebuild pages that link to added or removed pages
414         if (@add || @del) {
415                 foreach my $f (@add, @del) {
416                         my $p=pagename($f);
417                         foreach my $page (keys %{$backlinks{$p}}) {
418                                 my $file=$pagesources{$page};
419                                 next if $rendered{$file};
420                                 debug(sprintf(gettext("rendering %s, which links to %s"), $file, $p));
421                                 render($file);
422                                 $rendered{$file}=1;
423                         }
424                 }
425         }
426
427         if (%rendered || @del || @internal) {
428                 my @changed=(keys %rendered, @del);
429
430                 # rebuild dependant pages
431                 foreach my $f (@files) {
432                         next if $rendered{$f};
433                         my $p=pagename($f);
434                         if (exists $depends{$p}) {
435                                 # only consider internal files
436                                 # if the page explicitly depends on such files
437                                 foreach my $file (@changed, $depends{$p}=~/internal\(/ ? @internal : ()) {
438                                         next if $f eq $file;
439                                         my $page=pagename($file);
440                                         if (pagespec_match($page, $depends{$p}, location => $p)) {
441                                                 debug(sprintf(gettext("rendering %s, which depends on %s"), $f, $page));
442                                                 render($f);
443                                                 $rendered{$f}=1;
444                                                 last;
445                                         }
446                                 }
447                         }
448                 }
449                 
450                 # handle backlinks; if a page has added/removed links,
451                 # update the pages it links to
452                 my %linkchanged;
453                 foreach my $file (@changed) {
454                         my $page=pagename($file);
455                         
456                         if (exists $links{$page}) {
457                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
458                                         if (length $link &&
459                                             (! exists $oldlinks{$page} ||
460                                              ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
461                                                 $linkchanged{$link}=1;
462                                         }
463                                 }
464                         }
465                         if (exists $oldlinks{$page}) {
466                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
467                                         if (length $link &&
468                                             (! exists $links{$page} || 
469                                              ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
470                                                 $linkchanged{$link}=1;
471                                         }
472                                 }
473                         }
474                 }
475
476                 foreach my $link (keys %linkchanged) {
477                         my $linkfile=$pagesources{$link};
478                         if (defined $linkfile) {
479                                 next if $rendered{$linkfile};
480                                 debug(sprintf(gettext("rendering %s, to update its backlinks"), $linkfile));
481                                 render($linkfile);
482                                 $rendered{$linkfile}=1;
483                         }
484                 }
485         }
486
487         # remove no longer rendered files
488         foreach my $src (keys %rendered) {
489                 my $page=pagename($src);
490                 foreach my $file (@{$oldrenderedfiles{$page}}) {
491                         if (! grep { $_ eq $file } @{$renderedfiles{$page}}) {
492                                 debug(sprintf(gettext("removing %s, no longer rendered by %s"), $file, $page));
493                                 prune($config{destdir}."/".$file);
494                         }
495                 }
496         }
497
498         if (@del) {
499                 run_hooks(delete => sub { shift->(@del) });
500         }
501         if (%rendered) {
502                 run_hooks(change => sub { shift->(keys %rendered) });
503         }
504 } #}}}
505
506 sub commandline_render () { #{{{
507         lockwiki();
508         loadindex();
509         unlockwiki();
510
511         my $srcfile=possibly_foolish_untaint($config{render});
512         my $file=$srcfile;
513         $file=~s/\Q$config{srcdir}\E\/?//;
514
515         my $type=pagetype($file);
516         die sprintf(gettext("ikiwiki: cannot render %s"), $srcfile)."\n" unless defined $type;
517         my $content=readfile($srcfile);
518         my $page=pagename($file);
519         $pagesources{$page}=$file;
520         $content=filter($page, $page, $content);
521         $content=preprocess($page, $page, $content);
522         $content=linkify($page, $page, $content);
523         $content=htmlize($page, $page, $type, $content);
524         $pagemtime{$page}=(stat($srcfile))[9];
525
526         print genpage($page, $content);
527         exit 0;
528 } #}}}
529
530 1