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