* Patch from Enrico that
[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;
12         my $page=shift;
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         if (exists $hooks{sanitize}) {
35                 foreach my $id (keys %{$hooks{sanitize}}) {
36                         $content=$hooks{sanitize}{$id}{call}->($content);
37                 }
38         }
39         
40         return $content;
41 } #}}}
42
43 sub backlinks ($) { #{{{
44         my $page=shift;
45
46         my @links;
47         foreach my $p (keys %links) {
48                 next if bestlink($page, $p) eq $page;
49                 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
50                         my $href=abs2rel(htmlpage($p), dirname($page));
51                         
52                         # Trim common dir prefixes from both pages.
53                         my $p_trimmed=$p;
54                         my $page_trimmed=$page;
55                         my $dir;
56                         1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
57                                 defined $dir &&
58                                 $p_trimmed=~s/^\Q$dir\E// &&
59                                 $page_trimmed=~s/^\Q$dir\E//;
60                                        
61                         push @links, { url => $href, page => $p_trimmed };
62                 }
63         }
64
65         return sort { $a->{page} cmp $b->{page} } @links;
66 } #}}}
67
68 sub parentlinks ($) { #{{{
69         my $page=shift;
70         
71         my @ret;
72         my $pagelink="";
73         my $path="";
74         my $skip=1;
75         return if $page eq 'index'; # toplevel
76         foreach my $dir (reverse split("/", $page)) {
77                 if (! $skip) {
78                         $path.="../";
79                         unshift @ret, { url => "$path$dir.html", page => $dir };
80                 }
81                 else {
82                         $skip=0;
83                 }
84         }
85         unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
86         return @ret;
87 } #}}}
88
89 sub preprocess ($$;$) { #{{{
90         my $page=shift;
91         my $content=shift;
92         my $onlystrip=shift || 0; # strip directives without processing
93
94         my $handle=sub {
95                 my $escape=shift;
96                 my $command=shift;
97                 my $params=shift;
98                 if (length $escape) {
99                         return "[[$command $params]]";
100                 }
101                 elsif ($onlystrip) {
102                         return "";
103                 }
104                 elsif (exists $hooks{preprocess}{$command}) {
105                         # Note: preserve order of params, some plugins may
106                         # consider it significant.
107                         my @params;
108                         while ($params =~ /(?:(\w+)=)?(?:"([^"]+)"|(\S+))(?:\s+|$)/g) {
109                                 if (defined $1) {
110                                         push @params, $1, (defined $2 ? $2 : $3);
111                                 }
112                                 else {
113                                         push @params, (defined $2 ? $2 : $3), '';
114                                 }
115                         }
116                         return $hooks{preprocess}{$command}{call}->(@params, page => $page);
117                 }
118                 else {
119                         return "[[$command not processed]]";
120                 }
121         };
122         
123         $content =~ s{(\\?)$config{wiki_processor_regexp}}{$handle->($1, $2, $3)}eg;
124         return $content;
125 } #}}}
126
127 sub add_depends ($$) { #{{{
128         my $page=shift;
129         my $globlist=shift;
130         
131         if (! exists $depends{$page}) {
132                 $depends{$page}=$globlist;
133         }
134         else {
135                 $depends{$page}=globlist_merge($depends{$page}, $globlist);
136         }
137 } # }}}
138
139 sub globlist_merge ($$) { #{{{
140         my $a=shift;
141         my $b=shift;
142
143         my $ret="";
144         # Only add negated globs if they are not matched by the other globlist.
145         foreach my $i ((map { [ $a, $_ ] } split(" ", $b)), 
146                        (map { [ $b, $_ ] } split(" ", $a))) {
147                 if ($i->[1]=~/^!(.*)/) {
148                         if (! globlist_match($1, $i->[0])) {
149                                 $ret.=" ".$i->[1];
150                         }
151                 }
152                 else {
153                         $ret.=" ".$i->[1];
154                 }
155         }
156         
157         return $ret;
158 } #}}}
159
160 sub genpage ($$$) { #{{{
161         my $page=shift;
162         my $content=shift;
163         my $mtime=shift;
164
165         my $template=template("page.tmpl", blind_cache => 1);
166         my $actions=0;
167
168         if (length $config{cgiurl}) {
169                 $template->param(editurl => cgiurl(do => "edit", page => $page));
170                 $template->param(prefsurl => cgiurl(do => "prefs"));
171                 if ($config{rcs}) {
172                         $template->param(recentchangesurl => cgiurl(do => "recentchanges"));
173                 }
174                 $actions++;
175         }
176
177         if (length $config{historyurl}) {
178                 my $u=$config{historyurl};
179                 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
180                 $template->param(historyurl => $u);
181                 $actions++;
182         }
183         if ($config{discussion}) {
184                 $template->param(discussionlink => htmllink($page, $page, "Discussion", 1, 1));
185                 $actions++;
186         }
187
188         if ($actions) {
189                 $template->param(have_actions => 1);
190         }
191
192         $template->param(
193                 title => $page eq 'index' 
194                         ? $config{wikiname} 
195                         : pagetitle(basename($page)),
196                 wikiname => $config{wikiname},
197                 parentlinks => [parentlinks($page)],
198                 content => $content,
199                 backlinks => [backlinks($page)],
200                 mtime => displaytime($mtime),
201                 styleurl => styleurl($page),
202         );
203
204         if (exists $hooks{pagetemplate}) {
205                 foreach my $id (keys %{$hooks{pagetemplate}}) {
206                         $hooks{pagetemplate}{$id}{call}->($page, $template);
207                 }
208         }
209         
210         return $template->output;
211 } #}}}
212
213 sub check_overwrite ($$) { #{{{
214         # Important security check. Make sure to call this before saving
215         # any files to the source directory.
216         my $dest=shift;
217         my $src=shift;
218         
219         if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
220                 error("$dest already exists and was not rendered from $src before");
221         }
222 } #}}}
223
224 sub displaytime ($) { #{{{
225         my $time=shift;
226
227         eval q{use POSIX};
228         # strftime doesn't know about encodings, so make sure
229         # its output is properly treated as utf8
230         return decode_utf8(POSIX::strftime(
231                         $config{timeformat}, localtime($time)));
232 } #}}}
233
234 sub mtime ($) { #{{{
235         my $file=shift;
236         
237         return (stat($file))[9];
238 } #}}}
239
240 sub findlinks ($$) { #{{{
241         my $page=shift;
242         my $content=shift;
243
244         my @links;
245         while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
246                 push @links, titlepage($2);
247         }
248         if ($config{discussion}) {
249                 # Discussion links are a special case since they're not in the
250                 # text of the page, but on its template.
251                 return @links, "$page/discussion";
252         }
253         else {
254                 return @links;
255         }
256 } #}}}
257
258 sub filter ($$) {
259         my $page=shift;
260         my $content=shift;
261
262         if (exists $hooks{filter}) {
263                 foreach my $id (keys %{$hooks{filter}}) {
264                         $content=$hooks{filter}{$id}{call}->(
265                                 page => $page,
266                                 content => $content
267                         );
268                 }
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=linkify($page, $page, $content);
289                 $content=preprocess($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                         $pagesources{$page}=$file;
381                         if ($config{getctime} && -e "$config{srcdir}/$file") {
382                                 $pagectime{$page}=rcs_getctime("$config{srcdir}/$file");
383                         }
384                         elsif (! exists $pagectime{$page}) {
385                                 $pagectime{$page}=mtime(srcfile($file));
386                         }
387                 }
388         }
389         my @del;
390         foreach my $page (keys %oldpagemtime) {
391                 if (! $exists{$page}) {
392                         debug("removing old page $page");
393                         push @del, $pagesources{$page};
394                         prune($config{destdir}."/".$renderedfiles{$page});
395                         delete $renderedfiles{$page};
396                         $oldpagemtime{$page}=0;
397                         delete $pagesources{$page};
398                 }
399         }
400         
401         # render any updated files
402         foreach my $file (@files) {
403                 my $page=pagename($file);
404                 
405                 if (! exists $oldpagemtime{$page} ||
406                     mtime(srcfile($file)) > $oldpagemtime{$page}) {
407                         debug("rendering $file");
408                         render($file);
409                         $rendered{$file}=1;
410                 }
411         }
412         
413         # if any files were added or removed, check to see if each page
414         # needs an update due to linking to them or inlining them.
415         # TODO: inefficient; pages may get rendered above and again here;
416         # problem is the bestlink may have changed and we won't know until
417         # now
418         if (@add || @del) {
419 FILE:           foreach my $file (@files) {
420                         my $page=pagename($file);
421                         foreach my $f (@add, @del) {
422                                 my $p=pagename($f);
423                                 foreach my $link (@{$links{$page}}) {
424                                         if (bestlink($page, $link) eq $p) {
425                                                 debug("rendering $file, which links to $p");
426                                                 render($file);
427                                                 $rendered{$file}=1;
428                                                 next FILE;
429                                         }
430                                 }
431                         }
432                 }
433         }
434
435         # Handle backlinks; if a page has added/removed links, update the
436         # pages it links to. Also handles rebuilding dependant pages.
437         # TODO: inefficient; pages may get rendered above and again here;
438         # problem is the backlinks could be wrong in the first pass render
439         # above
440         if (%rendered || @del) {
441                 foreach my $f (@files) {
442                         my $p=pagename($f);
443                         if (exists $depends{$p}) {
444                                 foreach my $file (keys %rendered, @del) {
445                                         next if $f eq $file;
446                                         my $page=pagename($file);
447                                         if (globlist_match($page, $depends{$p})) {
448                                                 debug("rendering $f, which depends on $page");
449                                                 render($f);
450                                                 $rendered{$f}=1;
451                                                 last;
452                                         }
453                                 }
454                         }
455                 }
456                 
457                 my %linkchanged;
458                 foreach my $file (keys %rendered, @del) {
459                         my $page=pagename($file);
460                         
461                         if (exists $links{$page}) {
462                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
463                                         if (length $link &&
464                                             (! exists $oldlinks{$page} ||
465                                              ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
466                                                 $linkchanged{$link}=1;
467                                         }
468                                 }
469                         }
470                         if (exists $oldlinks{$page}) {
471                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
472                                         if (length $link &&
473                                             (! exists $links{$page} || 
474                                              ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
475                                                 $linkchanged{$link}=1;
476                                         }
477                                 }
478                         }
479                 }
480                 foreach my $link (keys %linkchanged) {
481                         my $linkfile=$pagesources{$link};
482                         if (defined $linkfile) {
483                                 debug("rendering $linkfile, to update its backlinks");
484                                 render($linkfile);
485                                 $rendered{$linkfile}=1;
486                         }
487                 }
488         }
489
490         if (@del && exists $hooks{delete}) {
491                 foreach my $id (keys %{$hooks{delete}}) {
492                         $hooks{delete}{$id}{call}->(@del);
493                 }
494         }
495         if (%rendered && exists $hooks{change}) {
496                 foreach my $id (keys %{$hooks{change}}) {
497                         $hooks{change}{$id}{call}->(keys %rendered);
498                 }
499         }
500 } #}}}
501
502 1