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