* Patch from Roland Mas to support an rss=no parameter to inline directives.
[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$dir.html", 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 $globlist=shift;
133         
134         if (! exists $depends{$page}) {
135                 $depends{$page}=$globlist;
136         }
137         else {
138                 $depends{$page}=globlist_merge($depends{$page}, $globlist);
139         }
140 } # }}}
141
142 sub globlist_merge ($$) { #{{{
143         my $a=shift;
144         my $b=shift;
145
146         my $ret="";
147         # Only add negated globs if they are not matched by the other globlist.
148         foreach my $i ((map { [ $a, $_ ] } split(" ", $b)), 
149                        (map { [ $b, $_ ] } split(" ", $a))) {
150                 if ($i->[1]=~/^!(.*)/) {
151                         if (! globlist_match($1, $i->[0])) {
152                                 $ret.=" ".$i->[1];
153                         }
154                 }
155                 else {
156                         $ret.=" ".$i->[1];
157                 }
158         }
159         
160         return $ret;
161 } #}}}
162
163 sub genpage ($$$) { #{{{
164         my $page=shift;
165         my $content=shift;
166         my $mtime=shift;
167
168         my $template=template("page.tmpl", blind_cache => 1);
169         my $actions=0;
170
171         if (length $config{cgiurl}) {
172                 $template->param(editurl => cgiurl(do => "edit", page => $page));
173                 $template->param(prefsurl => cgiurl(do => "prefs"));
174                 if ($config{rcs}) {
175                         $template->param(recentchangesurl => cgiurl(do => "recentchanges"));
176                 }
177                 $actions++;
178         }
179
180         if (length $config{historyurl}) {
181                 my $u=$config{historyurl};
182                 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
183                 $template->param(historyurl => $u);
184                 $actions++;
185         }
186         if ($config{discussion}) {
187                 $template->param(discussionlink => htmllink($page, $page, "Discussion", 1, 1));
188                 $actions++;
189         }
190
191         if ($actions) {
192                 $template->param(have_actions => 1);
193         }
194
195         $template->param(
196                 title => $page eq 'index' 
197                         ? $config{wikiname} 
198                         : pagetitle(basename($page)),
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         run_hooks(pagetemplate => sub {
208                 shift->(page => $page, destpage => $page, template => $template);
209         });
210         
211         return $template->output;
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=linkify($page, $page, $content);
285                 $content=preprocess($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                         $pagesources{$page}=$file;
377                         if ($config{getctime} && -e "$config{srcdir}/$file") {
378                                 $pagectime{$page}=rcs_getctime("$config{srcdir}/$file");
379                         }
380                         elsif (! exists $pagectime{$page}) {
381                                 $pagectime{$page}=mtime(srcfile($file));
382                         }
383                 }
384         }
385         my @del;
386         foreach my $page (keys %oldpagemtime) {
387                 if (! $exists{$page}) {
388                         debug("removing old page $page");
389                         push @del, $pagesources{$page};
390                         prune($config{destdir}."/".$renderedfiles{$page});
391                         delete $renderedfiles{$page};
392                         $oldpagemtime{$page}=0;
393                         delete $pagesources{$page};
394                 }
395         }
396         
397         # render any updated files
398         foreach my $file (@files) {
399                 my $page=pagename($file);
400                 
401                 if (! exists $oldpagemtime{$page} ||
402                     mtime(srcfile($file)) > $oldpagemtime{$page} ||
403                     $forcerebuild{$page}) {
404                         debug("rendering $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) {
488                 run_hooks(delete => sub { shift->(@del) });
489         }
490         if (%rendered) {
491                 run_hooks(change => sub { shift->(keys %rendered) });
492         }
493 } #}}}
494
495 1