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