reorg
[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         # security check, avoid following symlinks in the srcdir path
249         my $test=$config{srcdir};
250         while (length $test) {
251                 if (-l $test) {
252                         error("symlink found in srcdir path ($test)");
253                 }
254                 unless ($test=~s/\/+$//) {
255                         $test=dirname($test);
256                 }
257         }
258
259         # find existing pages
260         my %exists;
261         my @files;
262         eval q{use File::Find};
263         error($@) if $@;
264         find({
265                 no_chdir => 1,
266                 wanted => sub {
267                         $_=decode_utf8($_);
268                         if (file_pruned($_, $config{srcdir})) {
269                                 $File::Find::prune=1;
270                         }
271                         elsif (! -d $_ && ! -l $_) {
272                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
273                                 if (! defined $f) {
274                                         warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
275                                 }
276                                 else {
277                                         $f=~s/^\Q$config{srcdir}\E\/?//;
278                                         push @files, $f;
279                                         $exists{pagename($f)}=1;
280                                 }
281                         }
282                 },
283         }, $config{srcdir});
284         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
285                 find({
286                         no_chdir => 1,
287                         wanted => sub {
288                                 $_=decode_utf8($_);
289                                 if (file_pruned($_, $dir)) {
290                                         $File::Find::prune=1;
291                                 }
292                                 elsif (! -d $_ && ! -l $_) {
293                                         my ($f)=/$config{wiki_file_regexp}/; # untaint
294                                         if (! defined $f) {
295                                                 warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
296                                         }
297                                         else {
298                                                 $f=~s/^\Q$dir\E\/?//;
299                                                 # avoid underlaydir
300                                                 # override attacks; see
301                                                 # security.mdwn
302                                                 if (! -e "$config{srcdir}/$f" && 
303                                                     ! -l "$config{srcdir}/$f") {
304                                                         my $page=pagename($f);
305                                                         if (! $exists{$page}) {
306                                                                 push @files, $f;
307                                                                 $exists{$page}=1;
308                                                         }
309                                                 }
310                                         }
311                                 }
312                         },
313                 }, $dir);
314         };
315
316         my %rendered;
317
318         # check for added or removed pages
319         my @add;
320         foreach my $file (@files) {
321                 my $page=pagename($file);
322                 $pagesources{$page}=$file;
323                 if (! $pagemtime{$page}) {
324                         push @add, $file;
325                         $pagecase{lc $page}=$page;
326                         if ($config{getctime} && -e "$config{srcdir}/$file") {
327                                 $pagectime{$page}=rcs_getctime("$config{srcdir}/$file");
328                         }
329                         elsif (! exists $pagectime{$page}) {
330                                 $pagectime{$page}=mtime(srcfile($file));
331                         }
332                 }
333         }
334         my @del;
335         foreach my $page (keys %pagemtime) {
336                 if (! $exists{$page}) {
337                         debug(sprintf(gettext("removing old page %s"), $page));
338                         push @del, $pagesources{$page};
339                         $links{$page}=[];
340                         $renderedfiles{$page}=[];
341                         $pagemtime{$page}=0;
342                         prune($config{destdir}."/".$_)
343                                 foreach @{$oldrenderedfiles{$page}};
344                         delete $pagesources{$page};
345                         foreach (keys %destsources) {
346                                 if ($destsources{$_} eq $page) {
347                                         delete $destsources{$_};
348                                 }
349                         }
350                 }
351         }
352
353         # find changed and new files
354         my @needsbuild;
355         foreach my $file (@files) {
356                 my $page=pagename($file);
357                 
358                 my $mtime=mtime(srcfile($file));
359                 if (! exists $pagemtime{$page} ||
360                     $mtime > $pagemtime{$page} ||
361                     $forcerebuild{$page}) {
362                         $pagemtime{$page}=$mtime;
363                         push @needsbuild, $file;
364                 }
365         }
366         run_hooks(needsbuild => sub { shift->(\@needsbuild) });
367
368         # scan and render files
369         foreach my $file (@needsbuild) {
370                 debug(sprintf(gettext("scanning %s"), $file));
371                 scan($file);
372         }
373         calculate_backlinks();
374         foreach my $file (@needsbuild) {
375                 debug(sprintf(gettext("rendering %s"), $file));
376                 render($file);
377                 $rendered{$file}=1;
378         }
379         
380         # rebuild pages that link to added or removed pages
381         if (@add || @del) {
382                 foreach my $f (@add, @del) {
383                         my $p=pagename($f);
384                         foreach my $page (keys %{$backlinks{$p}}) {
385                                 my $file=$pagesources{$page};
386                                 next if $rendered{$file};
387                                 debug(sprintf(gettext("rendering %s, which links to %s"), $file, $p));
388                                 render($file);
389                                 $rendered{$file}=1;
390                         }
391                 }
392         }
393
394         if (%rendered || @del) {
395                 # rebuild dependant pages
396                 foreach my $f (@files) {
397                         next if $rendered{$f};
398                         my $p=pagename($f);
399                         if (exists $depends{$p}) {
400                                 foreach my $file (keys %rendered, @del) {
401                                         next if $f eq $file;
402                                         my $page=pagename($file);
403                                         if (pagespec_match($page, $depends{$p}, location => $p)) {
404                                                 debug(sprintf(gettext("rendering %s, which depends on %s"), $f, $page));
405                                                 render($f);
406                                                 $rendered{$f}=1;
407                                                 last;
408                                         }
409                                 }
410                         }
411                 }
412                 
413                 # handle backlinks; if a page has added/removed links,
414                 # update the pages it links to
415                 my %linkchanged;
416                 foreach my $file (keys %rendered, @del) {
417                         my $page=pagename($file);
418                         
419                         if (exists $links{$page}) {
420                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
421                                         if (length $link &&
422                                             (! exists $oldlinks{$page} ||
423                                              ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
424                                                 $linkchanged{$link}=1;
425                                         }
426                                 }
427                         }
428                         if (exists $oldlinks{$page}) {
429                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
430                                         if (length $link &&
431                                             (! exists $links{$page} || 
432                                              ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
433                                                 $linkchanged{$link}=1;
434                                         }
435                                 }
436                         }
437                 }
438                 foreach my $link (keys %linkchanged) {
439                         my $linkfile=$pagesources{$link};
440                         if (defined $linkfile) {
441                                 next if $rendered{$linkfile};
442                                 debug(sprintf(gettext("rendering %s, to update its backlinks"), $linkfile));
443                                 render($linkfile);
444                                 $rendered{$linkfile}=1;
445                         }
446                 }
447         }
448
449         # remove no longer rendered files
450         foreach my $src (keys %rendered) {
451                 my $page=pagename($src);
452                 foreach my $file (@{$oldrenderedfiles{$page}}) {
453                         if (! grep { $_ eq $file } @{$renderedfiles{$page}}) {
454                                 debug(sprintf(gettext("removing %s, no longer rendered by %s"), $file, $page));
455                                 prune($config{destdir}."/".$file);
456                         }
457                 }
458         }
459
460         if (@del) {
461                 run_hooks(delete => sub { shift->(@del) });
462         }
463         if (%rendered) {
464                 run_hooks(change => sub { shift->(keys %rendered) });
465         }
466 } #}}}
467
468 sub commandline_render () { #{{{
469         loadplugins();
470         checkconfig();
471         lockwiki();
472         loadindex();
473         unlockwiki();
474
475         my $srcfile=possibly_foolish_untaint($config{render});
476         my $file=$srcfile;
477         $file=~s/\Q$config{srcdir}\E\/?//;
478
479         my $type=pagetype($file);
480         die sprintf(gettext("ikiwiki: cannot render %s"), $srcfile)."\n" unless defined $type;
481         my $content=readfile($srcfile);
482         my $page=pagename($file);
483         $pagesources{$page}=$file;
484         $content=filter($page, $page, $content);
485         $content=preprocess($page, $page, $content);
486         $content=linkify($page, $page, $content);
487         $content=htmlize($page, $type, $content);
488
489         print genpage($page, $content, mtime($srcfile));
490         exit 0;
491 } #}}}
492
493 1