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