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