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