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