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