improve
[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 sub linkify ($$$) { #{{{
11         my $lpage=shift; # the page containing the links
12         my $page=shift; # the page the link will end up on (different for inline)
13         my $content=shift;
14
15         $content =~ s{(\\?)$config{wiki_link_regexp}}{
16                 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
17                    : ( $1 ? "[[$3]]" :    htmllink($lpage, $page, titlepage($3)))
18         }eg;
19         
20         return $content;
21 } #}}}
22
23 sub htmlize ($$) { #{{{
24         my $type=shift;
25         my $content=shift;
26         
27         if (exists $hooks{htmlize}{$type}) {
28                 $content=$hooks{htmlize}{$type}{call}->($content);
29         }
30         else {
31                 error("htmlization of $type not supported");
32         }
33
34         run_hooks(sanitize => sub {
35                 $content=shift->($content);
36         });
37         
38         return $content;
39 } #}}}
40
41 sub backlinks ($) { #{{{
42         my $page=shift;
43
44         my @links;
45         foreach my $p (keys %links) {
46                 next if bestlink($page, $p) eq $page;
47                 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
48                         my $href=abs2rel(htmlpage($p), dirname($page));
49                         
50                         # Trim common dir prefixes from both pages.
51                         my $p_trimmed=$p;
52                         my $page_trimmed=$page;
53                         my $dir;
54                         1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
55                                 defined $dir &&
56                                 $p_trimmed=~s/^\Q$dir\E// &&
57                                 $page_trimmed=~s/^\Q$dir\E//;
58                                        
59                         push @links, { url => $href, page => pagetitle($p_trimmed) };
60                 }
61         }
62
63         return sort { $a->{page} cmp $b->{page} } @links;
64 } #}}}
65
66 sub parentlinks ($) { #{{{
67         my $page=shift;
68         
69         my @ret;
70         my $pagelink="";
71         my $path="";
72         my $skip=1;
73         return if $page eq 'index'; # toplevel
74         foreach my $dir (reverse split("/", $page)) {
75                 if (! $skip) {
76                         $path.="../";
77                         unshift @ret, { url => $path.htmlpage($dir), page => pagetitle($dir) };
78                 }
79                 else {
80                         $skip=0;
81                 }
82         }
83         unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
84         return @ret;
85 } #}}}
86
87 my %preprocessing;
88 sub preprocess ($$$) { #{{{
89         my $page=shift; # the page the data comes from
90         my $destpage=shift; # the page the data will appear in (different for inline)
91         my $content=shift;
92
93         my $handle=sub {
94                 my $escape=shift;
95                 my $command=shift;
96                 my $params=shift;
97                 if (length $escape) {
98                         return "[[$command $params]]";
99                 }
100                 elsif (exists $hooks{preprocess}{$command}) {
101                         # Note: preserve order of params, some plugins may
102                         # consider it significant.
103                         my @params;
104                         while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
105                                 my $key=$1;
106                                 my $val;
107                                 if (defined $2) {
108                                         $val=$2;
109                                         $val=~s/\r\n/\n/mg;
110                                         $val=~s/^\n+//g;
111                                         $val=~s/\n+$//g;
112                                 }
113                                 elsif (defined $3) {
114                                         $val=$3;
115                                 }
116                                 elsif (defined $4) {
117                                         $val=$4;
118                                 }
119
120                                 if (defined $key) {
121                                         push @params, $key, $val;
122                                 }
123                                 else {
124                                         push @params, $val, '';
125                                 }
126                         }
127                         if ($preprocessing{$page}++ > 10) {
128                                 # Avoid loops of preprocessed pages preprocessing
129                                 # other pages that preprocess them, etc.
130                                 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
131                         }
132                         my $ret=$hooks{preprocess}{$command}{call}->(
133                                 @params,
134                                 page => $page,
135                                 destpage => $destpage,
136                         );
137                         $preprocessing{$page}--;
138                         return $ret;
139                 }
140                 else {
141                         return "[[$command $params]]";
142                 }
143         };
144         
145         $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
146         return $content;
147 } #}}}
148
149 sub add_depends ($$) { #{{{
150         my $page=shift;
151         my $pagespec=shift;
152         
153         if (! exists $depends{$page}) {
154                 $depends{$page}=$pagespec;
155         }
156         else {
157                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
158         }
159 } # }}}
160
161 sub genpage ($$$) { #{{{
162         my $page=shift;
163         my $content=shift;
164         my $mtime=shift;
165
166         my $template=template("page.tmpl", blind_cache => 1);
167         my $actions=0;
168
169         if (length $config{cgiurl}) {
170                 $template->param(editurl => cgiurl(do => "edit", page => $page));
171                 $template->param(prefsurl => cgiurl(do => "prefs"));
172                 if ($config{rcs}) {
173                         $template->param(recentchangesurl => cgiurl(do => "recentchanges"));
174                 }
175                 $actions++;
176         }
177
178         if (length $config{historyurl}) {
179                 my $u=$config{historyurl};
180                 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
181                 $template->param(historyurl => $u);
182                 $actions++;
183         }
184         if ($config{discussion}) {
185                 $template->param(discussionlink => htmllink($page, $page, "Discussion", 1, 1));
186                 $actions++;
187         }
188
189         if ($actions) {
190                 $template->param(have_actions => 1);
191         }
192
193         $template->param(
194                 title => $page eq 'index' 
195                         ? $config{wikiname} 
196                         : pagetitle(basename($page)),
197                 wikiname => $config{wikiname},
198                 parentlinks => [parentlinks($page)],
199                 content => $content,
200                 backlinks => [backlinks($page)],
201                 mtime => displaytime($mtime),
202                 baseurl => baseurl($page),
203         );
204
205         run_hooks(pagetemplate => sub {
206                 shift->(page => $page, destpage => $page, template => $template);
207         });
208         
209         $content=$template->output;
210
211         run_hooks(format => sub {
212                 $content=shift->($content);
213         });
214
215         return $content;
216 } #}}}
217
218 sub check_overwrite ($$) { #{{{
219         # Important security check. Make sure to call this before saving
220         # any files to the source directory.
221         my $dest=shift;
222         my $src=shift;
223         
224         if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
225                 error("$dest already exists and was not rendered from $src before");
226         }
227 } #}}}
228
229 sub displaytime ($) { #{{{
230         my $time=shift;
231
232         eval q{use POSIX};
233         # strftime doesn't know about encodings, so make sure
234         # its output is properly treated as utf8
235         return decode_utf8(POSIX::strftime(
236                         $config{timeformat}, localtime($time)));
237 } #}}}
238
239 sub mtime ($) { #{{{
240         my $file=shift;
241         
242         return (stat($file))[9];
243 } #}}}
244
245 sub findlinks ($$) { #{{{
246         my $page=shift;
247         my $content=shift;
248
249         my @links;
250         while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
251                 push @links, titlepage($2);
252         }
253         if ($config{discussion}) {
254                 # Discussion links are a special case since they're not in the
255                 # text of the page, but on its template.
256                 return @links, "$page/discussion";
257         }
258         else {
259                 return @links;
260         }
261 } #}}}
262
263 sub filter ($$) {
264         my $page=shift;
265         my $content=shift;
266
267         run_hooks(filter => sub {
268                 $content=shift->(page => $page, content => $content);
269         });
270
271         return $content;
272 }
273
274 sub render ($) { #{{{
275         my $file=shift;
276         
277         my $type=pagetype($file);
278         my $srcfile=srcfile($file);
279         if (defined $type) {
280                 my $content=readfile($srcfile);
281                 my $page=pagename($file);
282                 delete $depends{$page};
283                 
284                 $content=filter($page, $content);
285                 
286                 $links{$page}=[findlinks($page, $content)];
287                 
288                 $content=preprocess($page, $page, $content);
289                 $content=linkify($page, $page, $content);
290                 $content=htmlize($type, $content);
291                 
292                 check_overwrite("$config{destdir}/".htmlpage($page), $page);
293                 writefile(htmlpage($page), $config{destdir},
294                         genpage($page, $content, mtime($srcfile)));
295                 $oldpagemtime{$page}=time;
296                 $renderedfiles{$page}=htmlpage($page);
297         }
298         else {
299                 my $content=readfile($srcfile, 1);
300                 $links{$file}=[];
301                 delete $depends{$file};
302                 check_overwrite("$config{destdir}/$file", $file);
303                 writefile($file, $config{destdir}, $content, 1);
304                 $oldpagemtime{$file}=time;
305                 $renderedfiles{$file}=$file;
306         }
307 } #}}}
308
309 sub prune ($) { #{{{
310         my $file=shift;
311
312         unlink($file);
313         my $dir=dirname($file);
314         while (rmdir($dir)) {
315                 $dir=dirname($dir);
316         }
317 } #}}}
318
319 sub refresh () { #{{{
320         # find existing pages
321         my %exists;
322         my @files;
323         eval q{use File::Find};
324         find({
325                 no_chdir => 1,
326                 wanted => sub {
327                         $_=decode_utf8($_);
328                         if (/$config{wiki_file_prune_regexp}/) {
329                                 $File::Find::prune=1;
330                         }
331                         elsif (! -d $_ && ! -l $_) {
332                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
333                                 if (! defined $f) {
334                                         warn("skipping bad filename $_\n");
335                                 }
336                                 else {
337                                         $f=~s/^\Q$config{srcdir}\E\/?//;
338                                         push @files, $f;
339                                         $exists{pagename($f)}=1;
340                                 }
341                         }
342                 },
343         }, $config{srcdir});
344         find({
345                 no_chdir => 1,
346                 wanted => sub {
347                         $_=decode_utf8($_);
348                         if (/$config{wiki_file_prune_regexp}/) {
349                                 $File::Find::prune=1;
350                         }
351                         elsif (! -d $_ && ! -l $_) {
352                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
353                                 if (! defined $f) {
354                                         warn("skipping bad filename $_\n");
355                                 }
356                                 else {
357                                         # Don't add files that are in the
358                                         # srcdir.
359                                         $f=~s/^\Q$config{underlaydir}\E\/?//;
360                                         if (! -e "$config{srcdir}/$f" && 
361                                             ! -l "$config{srcdir}/$f") {
362                                                 push @files, $f;
363                                                 $exists{pagename($f)}=1;
364                                         }
365                                 }
366                         }
367                 },
368         }, $config{underlaydir});
369
370         my %rendered;
371
372         # check for added or removed pages
373         my @add;
374         foreach my $file (@files) {
375                 my $page=pagename($file);
376                 if (! $oldpagemtime{$page}) {
377                         debug("new page $page") unless exists $pagectime{$page};
378                         push @add, $file;
379                         $links{$page}=[];
380                         $pagecase{lc $page}=$page;
381                         $pagesources{$page}=$file;
382                         if ($config{getctime} && -e "$config{srcdir}/$file") {
383                                 $pagectime{$page}=rcs_getctime("$config{srcdir}/$file");
384                         }
385                         elsif (! exists $pagectime{$page}) {
386                                 $pagectime{$page}=mtime(srcfile($file));
387                         }
388                 }
389         }
390         my @del;
391         foreach my $page (keys %oldpagemtime) {
392                 if (! $exists{$page}) {
393                         debug("removing old page $page");
394                         push @del, $pagesources{$page};
395                         prune($config{destdir}."/".$renderedfiles{$page});
396                         delete $renderedfiles{$page};
397                         $oldpagemtime{$page}=0;
398                         delete $pagesources{$page};
399                 }
400         }
401         
402         # render any updated files
403         foreach my $file (@files) {
404                 my $page=pagename($file);
405                 
406                 if (! exists $oldpagemtime{$page} ||
407                     mtime(srcfile($file)) > $oldpagemtime{$page} ||
408                     $forcerebuild{$page}) {
409                         debug("rendering $file");
410                         render($file);
411                         $rendered{$file}=1;
412                 }
413         }
414         
415         # if any files were added or removed, check to see if each page
416         # needs an update due to linking to them or inlining them.
417         # TODO: inefficient; pages may get rendered above and again here;
418         # problem is the bestlink may have changed and we won't know until
419         # now
420         if (@add || @del) {
421 FILE:           foreach my $file (@files) {
422                         my $page=pagename($file);
423                         foreach my $f (@add, @del) {
424                                 my $p=pagename($f);
425                                 foreach my $link (@{$links{$page}}) {
426                                         if (bestlink($page, $link) eq $p) {
427                                                 debug("rendering $file, which links to $p");
428                                                 render($file);
429                                                 $rendered{$file}=1;
430                                                 next FILE;
431                                         }
432                                 }
433                         }
434                 }
435         }
436
437         # Handle backlinks; if a page has added/removed links, update the
438         # pages it links to. Also handles rebuilding dependant pages.
439         # TODO: inefficient; pages may get rendered above and again here;
440         # problem is the backlinks could be wrong in the first pass render
441         # above
442         if (%rendered || @del) {
443                 foreach my $f (@files) {
444                         my $p=pagename($f);
445                         if (exists $depends{$p}) {
446                                 foreach my $file (keys %rendered, @del) {
447                                         next if $f eq $file;
448                                         my $page=pagename($file);
449                                         if (pagespec_match($page, $depends{$p})) {
450                                                 debug("rendering $f, which depends on $page");
451                                                 render($f);
452                                                 $rendered{$f}=1;
453                                                 last;
454                                         }
455                                 }
456                         }
457                 }
458                 
459                 my %linkchanged;
460                 foreach my $file (keys %rendered, @del) {
461                         my $page=pagename($file);
462                         
463                         if (exists $links{$page}) {
464                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
465                                         if (length $link &&
466                                             (! exists $oldlinks{$page} ||
467                                              ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
468                                                 $linkchanged{$link}=1;
469                                         }
470                                 }
471                         }
472                         if (exists $oldlinks{$page}) {
473                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
474                                         if (length $link &&
475                                             (! exists $links{$page} || 
476                                              ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
477                                                 $linkchanged{$link}=1;
478                                         }
479                                 }
480                         }
481                 }
482                 foreach my $link (keys %linkchanged) {
483                         my $linkfile=$pagesources{$link};
484                         if (defined $linkfile) {
485                                 debug("rendering $linkfile, to update its backlinks");
486                                 render($linkfile);
487                                 $rendered{$linkfile}=1;
488                         }
489                 }
490         }
491
492         if (@del) {
493                 run_hooks(delete => sub { shift->(@del) });
494         }
495         if (%rendered) {
496                 run_hooks(change => sub { shift->(keys %rendered) });
497         }
498 } #}}}
499
500 1