* Build-depend on libtext-wikiformat-perl, so that the syntax check of
[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; # 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         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 => pagetitle($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 => pagetitle($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; # the page the data comes from
91         my $destpage=shift; # the page the data will appear in (different for inline)
92         my $content=shift;
93         my $onlystrip=shift || 0; # strip directives without processing
94
95         my $handle=sub {
96                 my $escape=shift;
97                 my $command=shift;
98                 my $params=shift;
99                 if (length $escape) {
100                         return "[[$command $params]]";
101                 }
102                 elsif ($onlystrip) {
103                         return "";
104                 }
105                 elsif (exists $hooks{preprocess}{$command}) {
106                         # Note: preserve order of params, some plugins may
107                         # consider it significant.
108                         my @params;
109                         while ($params =~ /(?:(\w+)=)?(?:"([^"]+)"|(\S+))(?:\s+|$)/g) {
110                                 if (defined $1) {
111                                         push @params, $1, (defined $2 ? $2 : $3);
112                                 }
113                                 else {
114                                         push @params, (defined $2 ? $2 : $3), '';
115                                 }
116                         }
117                         return $hooks{preprocess}{$command}{call}->(
118                                 @params,
119                                 page => $page,
120                                 destpage => $destpage,
121                         );
122                 }
123                 else {
124                         return "[[$command not processed]]";
125                 }
126         };
127         
128         $content =~ s{(\\?)$config{wiki_processor_regexp}}{$handle->($1, $2, $3)}eg;
129         return $content;
130 } #}}}
131
132 sub add_depends ($$) { #{{{
133         my $page=shift;
134         my $globlist=shift;
135         
136         if (! exists $depends{$page}) {
137                 $depends{$page}=$globlist;
138         }
139         else {
140                 $depends{$page}=globlist_merge($depends{$page}, $globlist);
141         }
142 } # }}}
143
144 sub globlist_merge ($$) { #{{{
145         my $a=shift;
146         my $b=shift;
147
148         my $ret="";
149         # Only add negated globs if they are not matched by the other globlist.
150         foreach my $i ((map { [ $a, $_ ] } split(" ", $b)), 
151                        (map { [ $b, $_ ] } split(" ", $a))) {
152                 if ($i->[1]=~/^!(.*)/) {
153                         if (! globlist_match($1, $i->[0])) {
154                                 $ret.=" ".$i->[1];
155                         }
156                 }
157                 else {
158                         $ret.=" ".$i->[1];
159                 }
160         }
161         
162         return $ret;
163 } #}}}
164
165 sub genpage ($$$) { #{{{
166         my $page=shift;
167         my $content=shift;
168         my $mtime=shift;
169
170         my $template=template("page.tmpl", blind_cache => 1);
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 => $page eq 'index' 
199                         ? $config{wikiname} 
200                         : pagetitle(basename($page)),
201                 wikiname => $config{wikiname},
202                 parentlinks => [parentlinks($page)],
203                 content => $content,
204                 backlinks => [backlinks($page)],
205                 mtime => displaytime($mtime),
206                 styleurl => styleurl($page),
207         );
208
209         if (exists $hooks{pagetemplate}) {
210                 foreach my $id (keys %{$hooks{pagetemplate}}) {
211                         $hooks{pagetemplate}{$id}{call}->(
212                                 page => $page,
213                                 destpage => $page,
214                                 template => $template,
215                         );
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 not rendered from $src before");
230         }
231 } #}}}
232
233 sub displaytime ($) { #{{{
234         my $time=shift;
235
236         eval q{use POSIX};
237         # strftime doesn't know about encodings, so make sure
238         # its output is properly treated as utf8
239         return decode_utf8(POSIX::strftime(
240                         $config{timeformat}, localtime($time)));
241 } #}}}
242
243 sub mtime ($) { #{{{
244         my $file=shift;
245         
246         return (stat($file))[9];
247 } #}}}
248
249 sub findlinks ($$) { #{{{
250         my $page=shift;
251         my $content=shift;
252
253         my @links;
254         while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
255                 push @links, titlepage($2);
256         }
257         if ($config{discussion}) {
258                 # Discussion links are a special case since they're not in the
259                 # text of the page, but on its template.
260                 return @links, "$page/discussion";
261         }
262         else {
263                 return @links;
264         }
265 } #}}}
266
267 sub filter ($$) {
268         my $page=shift;
269         my $content=shift;
270
271         if (exists $hooks{filter}) {
272                 foreach my $id (keys %{$hooks{filter}}) {
273                         $content=$hooks{filter}{$id}{call}->(
274                                 page => $page,
275                                 content => $content
276                         );
277                 }
278         }
279
280         return $content;
281 }
282
283 sub render ($) { #{{{
284         my $file=shift;
285         
286         my $type=pagetype($file);
287         my $srcfile=srcfile($file);
288         if (defined $type) {
289                 my $content=readfile($srcfile);
290                 my $page=pagename($file);
291                 delete $depends{$page};
292                 
293                 $content=filter($page, $content);
294                 
295                 $links{$page}=[findlinks($page, $content)];
296                 
297                 $content=linkify($page, $page, $content);
298                 $content=preprocess($page, $page, $content);
299                 $content=htmlize($type, $content);
300                 
301                 check_overwrite("$config{destdir}/".htmlpage($page), $page);
302                 writefile(htmlpage($page), $config{destdir},
303                         genpage($page, $content, mtime($srcfile)));
304                 $oldpagemtime{$page}=time;
305                 $renderedfiles{$page}=htmlpage($page);
306         }
307         else {
308                 my $content=readfile($srcfile, 1);
309                 $links{$file}=[];
310                 delete $depends{$file};
311                 check_overwrite("$config{destdir}/$file", $file);
312                 writefile($file, $config{destdir}, $content, 1);
313                 $oldpagemtime{$file}=time;
314                 $renderedfiles{$file}=$file;
315         }
316 } #}}}
317
318 sub prune ($) { #{{{
319         my $file=shift;
320
321         unlink($file);
322         my $dir=dirname($file);
323         while (rmdir($dir)) {
324                 $dir=dirname($dir);
325         }
326 } #}}}
327
328 sub refresh () { #{{{
329         # find existing pages
330         my %exists;
331         my @files;
332         eval q{use File::Find};
333         find({
334                 no_chdir => 1,
335                 wanted => sub {
336                         $_=decode_utf8($_);
337                         if (/$config{wiki_file_prune_regexp}/) {
338                                 $File::Find::prune=1;
339                         }
340                         elsif (! -d $_ && ! -l $_) {
341                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
342                                 if (! defined $f) {
343                                         warn("skipping bad filename $_\n");
344                                 }
345                                 else {
346                                         $f=~s/^\Q$config{srcdir}\E\/?//;
347                                         push @files, $f;
348                                         $exists{pagename($f)}=1;
349                                 }
350                         }
351                 },
352         }, $config{srcdir});
353         find({
354                 no_chdir => 1,
355                 wanted => sub {
356                         $_=decode_utf8($_);
357                         if (/$config{wiki_file_prune_regexp}/) {
358                                 $File::Find::prune=1;
359                         }
360                         elsif (! -d $_ && ! -l $_) {
361                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
362                                 if (! defined $f) {
363                                         warn("skipping bad filename $_\n");
364                                 }
365                                 else {
366                                         # Don't add files that are in the
367                                         # srcdir.
368                                         $f=~s/^\Q$config{underlaydir}\E\/?//;
369                                         if (! -e "$config{srcdir}/$f" && 
370                                             ! -l "$config{srcdir}/$f") {
371                                                 push @files, $f;
372                                                 $exists{pagename($f)}=1;
373                                         }
374                                 }
375                         }
376                 },
377         }, $config{underlaydir});
378
379         my %rendered;
380
381         # check for added or removed pages
382         my @add;
383         foreach my $file (@files) {
384                 my $page=pagename($file);
385                 if (! $oldpagemtime{$page}) {
386                         debug("new page $page") unless exists $pagectime{$page};
387                         push @add, $file;
388                         $links{$page}=[];
389                         $pagesources{$page}=$file;
390                         if ($config{getctime} && -e "$config{srcdir}/$file") {
391                                 $pagectime{$page}=rcs_getctime("$config{srcdir}/$file");
392                         }
393                         elsif (! exists $pagectime{$page}) {
394                                 $pagectime{$page}=mtime(srcfile($file));
395                         }
396                 }
397         }
398         my @del;
399         foreach my $page (keys %oldpagemtime) {
400                 if (! $exists{$page}) {
401                         debug("removing old page $page");
402                         push @del, $pagesources{$page};
403                         prune($config{destdir}."/".$renderedfiles{$page});
404                         delete $renderedfiles{$page};
405                         $oldpagemtime{$page}=0;
406                         delete $pagesources{$page};
407                 }
408         }
409         
410         # render any updated files
411         foreach my $file (@files) {
412                 my $page=pagename($file);
413                 
414                 if (! exists $oldpagemtime{$page} ||
415                     mtime(srcfile($file)) > $oldpagemtime{$page}) {
416                         debug("rendering $file");
417                         render($file);
418                         $rendered{$file}=1;
419                 }
420         }
421         
422         # if any files were added or removed, check to see if each page
423         # needs an update due to linking to them or inlining them.
424         # TODO: inefficient; pages may get rendered above and again here;
425         # problem is the bestlink may have changed and we won't know until
426         # now
427         if (@add || @del) {
428 FILE:           foreach my $file (@files) {
429                         my $page=pagename($file);
430                         foreach my $f (@add, @del) {
431                                 my $p=pagename($f);
432                                 foreach my $link (@{$links{$page}}) {
433                                         if (bestlink($page, $link) eq $p) {
434                                                 debug("rendering $file, which links to $p");
435                                                 render($file);
436                                                 $rendered{$file}=1;
437                                                 next FILE;
438                                         }
439                                 }
440                         }
441                 }
442         }
443
444         # Handle backlinks; if a page has added/removed links, update the
445         # pages it links to. Also handles rebuilding dependant pages.
446         # TODO: inefficient; pages may get rendered above and again here;
447         # problem is the backlinks could be wrong in the first pass render
448         # above
449         if (%rendered || @del) {
450                 foreach my $f (@files) {
451                         my $p=pagename($f);
452                         if (exists $depends{$p}) {
453                                 foreach my $file (keys %rendered, @del) {
454                                         next if $f eq $file;
455                                         my $page=pagename($file);
456                                         if (globlist_match($page, $depends{$p})) {
457                                                 debug("rendering $f, which depends on $page");
458                                                 render($f);
459                                                 $rendered{$f}=1;
460                                                 last;
461                                         }
462                                 }
463                         }
464                 }
465                 
466                 my %linkchanged;
467                 foreach my $file (keys %rendered, @del) {
468                         my $page=pagename($file);
469                         
470                         if (exists $links{$page}) {
471                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
472                                         if (length $link &&
473                                             (! exists $oldlinks{$page} ||
474                                              ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
475                                                 $linkchanged{$link}=1;
476                                         }
477                                 }
478                         }
479                         if (exists $oldlinks{$page}) {
480                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
481                                         if (length $link &&
482                                             (! exists $links{$page} || 
483                                              ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
484                                                 $linkchanged{$link}=1;
485                                         }
486                                 }
487                         }
488                 }
489                 foreach my $link (keys %linkchanged) {
490                         my $linkfile=$pagesources{$link};
491                         if (defined $linkfile) {
492                                 debug("rendering $linkfile, to update its backlinks");
493                                 render($linkfile);
494                                 $rendered{$linkfile}=1;
495                         }
496                 }
497         }
498
499         if (@del && exists $hooks{delete}) {
500                 foreach my $id (keys %{$hooks{delete}}) {
501                         $hooks{delete}{$id}{call}->(@del);
502                 }
503         }
504         if (%rendered && exists $hooks{change}) {
505                 foreach my $id (keys %{$hooks{change}}) {
506                         $hooks{change}{$id}{call}->(keys %rendered);
507                 }
508         }
509 } #}}}
510
511 1