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