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