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