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