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