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