* Make all templates have a footer div to ease themeing. Required template
[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 my %backlinks;
11 my $backlinks_calculated=0;
12
13 sub calculate_backlinks () { #{{{
14         return if $backlinks_calculated;
15         %backlinks=();
16         foreach my $page (keys %links) {
17                 foreach my $link (@{$links{$page}}) {
18                         my $bestlink=bestlink($page, $link);
19                         if (length $bestlink && $bestlink ne $page) {
20                                 $backlinks{$bestlink}{$page}=1;
21                         }
22                 }
23         }
24         $backlinks_calculated=1;
25 } #}}}
26
27 sub backlinks ($) { #{{{
28         my $page=shift;
29
30         calculate_backlinks();
31
32         my @links;
33         foreach my $p (keys %{$backlinks{$page}}) {
34                 my $href=urlto($p, $page);
35                 
36                 # Trim common dir prefixes from both pages.
37                 my $p_trimmed=$p;
38                 my $page_trimmed=$page;
39                 my $dir;
40                 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
41                         defined $dir &&
42                         $p_trimmed=~s/^\Q$dir\E// &&
43                         $page_trimmed=~s/^\Q$dir\E//;
44                                
45                 push @links, { url => $href, page => pagetitle($p_trimmed) };
46         }
47         @links = sort { $a->{page} cmp $b->{page} } @links;
48
49         return \@links, [] if @links <= $config{numbacklinks} || ! $config{numbacklinks};
50         return [@links[0..$config{numbacklinks}-1]],
51                [@links[$config{numbacklinks}..$#links]];
52 } #}}}
53
54 sub parentlinks ($) { #{{{
55         my $page=shift;
56         
57         my @ret;
58         my $pagelink="";
59         my $path="";
60         my $title=$config{wikiname};
61         
62         return if $page eq 'index'; # toplevel
63         foreach my $dir (split("/", $page)) {
64                 push @ret, { url => urlto($path, $page), page => $title };
65                 $path.="/".$dir;
66                 $title=pagetitle($dir);
67         }
68         return @ret;
69 } #}}}
70
71 sub genpage ($$$) { #{{{
72         my $page=shift;
73         my $content=shift;
74         my $mtime=shift;
75
76         my $template=template("page.tmpl", blind_cache => 1);
77         my $actions=0;
78
79         if (length $config{cgiurl}) {
80                 $template->param(editurl => cgiurl(do => "edit", page => pagetitle($page, 1)));
81                 $template->param(prefsurl => cgiurl(do => "prefs"));
82                 if ($config{rcs}) {
83                         $template->param(recentchangesurl => cgiurl(do => "recentchanges"));
84                 }
85                 $actions++;
86         }
87
88         if (length $config{historyurl}) {
89                 my $u=$config{historyurl};
90                 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
91                 $template->param(historyurl => $u);
92                 $actions++;
93         }
94         if ($config{discussion}) {
95                 my $discussionlink=gettext("discussion");
96                 if ($page !~ /.*\/\Q$discussionlink\E$/ &&
97                    (length $config{cgiurl} ||
98                     exists $links{$page."/".$discussionlink})) {
99                         $template->param(discussionlink => htmllink($page, $page, gettext("Discussion"), noimageinline => 1, forcesubpage => 1));
100                         $actions++;
101                 }
102         }
103
104         if ($actions) {
105                 $template->param(have_actions => 1);
106         }
107
108         my ($backlinks, $more_backlinks)=backlinks($page);
109
110         $template->param(
111                 title => $page eq 'index' 
112                         ? $config{wikiname} 
113                         : pagetitle(basename($page)),
114                 wikiname => $config{wikiname},
115                 parentlinks => [parentlinks($page)],
116                 content => $content,
117                 backlinks => $backlinks,
118                 more_backlinks => $more_backlinks,
119                 mtime => displaytime($mtime),
120                 baseurl => baseurl($page),
121         );
122
123         run_hooks(pagetemplate => sub {
124                 shift->(page => $page, destpage => $page, template => $template);
125         });
126         
127         $content=$template->output;
128
129         run_hooks(format => sub {
130                 $content=shift->(
131                         page => $page,
132                         content => $content,
133                 );
134         });
135
136         return $content;
137 } #}}}
138
139 sub mtime ($) { #{{{
140         my $file=shift;
141         
142         return (stat($file))[9];
143 } #}}}
144
145 sub scan ($) { #{{{
146         my $file=shift;
147
148         my $type=pagetype($file);
149         if (defined $type) {
150                 my $srcfile=srcfile($file);
151                 my $content=readfile($srcfile);
152                 my $page=pagename($file);
153                 will_render($page, htmlpage($page), 1);
154
155                 # Always needs to be done, since filters might add links
156                 # to the content.
157                 $content=filter($page, $content);
158
159                 my @links;
160                 while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
161                         push @links, linkpage($2);
162                 }
163                 if ($config{discussion}) {
164                         # Discussion links are a special case since they're
165                         # not in the text of the page, but on its template.
166                         push @links, $page."/".gettext("discussion");
167                 }
168                 $links{$page}=\@links;
169                 
170                 # Preprocess in scan-only mode.
171                 preprocess($page, $page, $content, 1);
172         }
173         else {
174                 will_render($file, $file, 1);
175         }
176 } #}}}
177
178 sub render ($) { #{{{
179         my $file=shift;
180         
181         my $type=pagetype($file);
182         my $srcfile=srcfile($file);
183         if (defined $type) {
184                 my $content=readfile($srcfile);
185                 my $page=pagename($file);
186                 delete $depends{$page};
187                 will_render($page, htmlpage($page), 1);
188                 
189                 $content=filter($page, $content);
190                 $content=preprocess($page, $page, $content);
191                 $content=linkify($page, $page, $content);
192                 $content=htmlize($page, $type, $content);
193                 
194                 writefile(htmlpage($page), $config{destdir},
195                         genpage($page, $content, mtime($srcfile)));
196         }
197         else {
198                 my $srcfd=readfile($srcfile, 1, 1);
199                 delete $depends{$file};
200                 will_render($file, $file, 1);
201                 writefile($file, $config{destdir}, undef, 1, sub {
202                         my $destfd=shift;
203                         my $cleanup=shift;
204
205                         my $blksize = 16384;
206                         my ($len, $buf, $written);
207                         while ($len = sysread $srcfd, $buf, $blksize) {
208                                 if (! defined $len) {
209                                         next if $! =~ /^Interrupted/;
210                                         error("failed to read $srcfile: $!", $cleanup);
211                                 }
212                                 my $offset = 0;
213                                 while ($len) {
214                                         defined($written = syswrite $destfd, $buf, $len, $offset)
215                                                 or error("failed to write $file: $!", $cleanup);
216                                         $len -= $written;
217                                         $offset += $written;
218                                 }
219                         }
220                 });
221         }
222 } #}}}
223
224 sub prune ($) { #{{{
225         my $file=shift;
226
227         unlink($file);
228         my $dir=dirname($file);
229         while (rmdir($dir)) {
230                 $dir=dirname($dir);
231         }
232 } #}}}
233
234 sub refresh () { #{{{
235         # find existing pages
236         my %exists;
237         my @files;
238         eval q{use File::Find};
239         error($@) if $@;
240         find({
241                 no_chdir => 1,
242                 wanted => sub {
243                         $_=decode_utf8($_);
244                         if (file_pruned($_, $config{srcdir})) {
245                                 $File::Find::prune=1;
246                         }
247                         elsif (! -d $_ && ! -l $_) {
248                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
249                                 if (! defined $f) {
250                                         warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
251                                 }
252                                 else {
253                                         $f=~s/^\Q$config{srcdir}\E\/?//;
254                                         push @files, $f;
255                                         $exists{pagename($f)}=1;
256                                 }
257                         }
258                 },
259         }, $config{srcdir});
260         find({
261                 no_chdir => 1,
262                 wanted => sub {
263                         $_=decode_utf8($_);
264                         if (file_pruned($_, $config{underlaydir})) {
265                                 $File::Find::prune=1;
266                         }
267                         elsif (! -d $_ && ! -l $_) {
268                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
269                                 if (! defined $f) {
270                                         warn(sprintf(gettext("skipping bad filename %s"), $_)."\n");
271                                 }
272                                 else {
273                                         # Don't add pages that are in the
274                                         # srcdir.
275                                         $f=~s/^\Q$config{underlaydir}\E\/?//;
276                                         if (! -e "$config{srcdir}/$f" && 
277                                             ! -l "$config{srcdir}/$f") {
278                                                 my $page=pagename($f);
279                                                 if (! $exists{$page}) {
280                                                         push @files, $f;
281                                                         $exists{$page}=1;
282                                                 }
283                                         }
284                                 }
285                         }
286                 },
287         }, $config{underlaydir});
288
289         my %rendered;
290
291         # check for added or removed pages
292         my @add;
293         foreach my $file (@files) {
294                 my $page=pagename($file);
295                 $pagesources{$page}=$file;
296                 if (! $pagemtime{$page}) {
297                         push @add, $file;
298                         $pagecase{lc $page}=$page;
299                         if ($config{getctime} && -e "$config{srcdir}/$file") {
300                                 $pagectime{$page}=rcs_getctime("$config{srcdir}/$file");
301                         }
302                         elsif (! exists $pagectime{$page}) {
303                                 $pagectime{$page}=mtime(srcfile($file));
304                         }
305                 }
306         }
307         my @del;
308         foreach my $page (keys %pagemtime) {
309                 if (! $exists{$page}) {
310                         debug(sprintf(gettext("removing old page %s"), $page));
311                         push @del, $pagesources{$page};
312                         $links{$page}=[];
313                         $renderedfiles{$page}=[];
314                         $pagemtime{$page}=0;
315                         prune($config{destdir}."/".$_)
316                                 foreach @{$oldrenderedfiles{$page}};
317                         delete $pagesources{$page};
318                 }
319         }
320
321         # find changed and new files
322         my @needsbuild;
323         foreach my $file (@files) {
324                 my $page=pagename($file);
325                 
326                 my $mtime=mtime(srcfile($file));
327                 if (! exists $pagemtime{$page} ||
328                     $mtime > $pagemtime{$page} ||
329                     $forcerebuild{$page}) {
330                         $pagemtime{$page}=$mtime;
331                         push @needsbuild, $file;
332                 }
333         }
334         run_hooks(needsbuild => sub { shift->(\@needsbuild) });
335
336         # scan and rendder files
337         foreach my $file (@needsbuild) {
338                 debug(sprintf(gettext("scanning %s"), $file));
339                 scan($file);
340         }
341         calculate_backlinks();
342         foreach my $file (@needsbuild) {
343                 debug(sprintf(gettext("rendering %s"), $file));
344                 render($file);
345                 $rendered{$file}=1;
346         }
347         
348         # rebuild pages that link to added or removed pages
349         if (@add || @del) {
350                 foreach my $f (@add, @del) {
351                         my $p=pagename($f);
352                         foreach my $page (keys %{$backlinks{$p}}) {
353                                 my $file=$pagesources{$page};
354                                 next if $rendered{$file};
355                                 debug(sprintf(gettext("rendering %s, which links to %s"), $file, $p));
356                                 render($file);
357                                 $rendered{$file}=1;
358                         }
359                 }
360         }
361
362         if (%rendered || @del) {
363                 # rebuild dependant pages
364                 foreach my $f (@files) {
365                         next if $rendered{$f};
366                         my $p=pagename($f);
367                         if (exists $depends{$p}) {
368                                 foreach my $file (keys %rendered, @del) {
369                                         next if $f eq $file;
370                                         my $page=pagename($file);
371                                         if (pagespec_match($page, $depends{$p}, location => $p)) {
372                                                 debug(sprintf(gettext("rendering %s, which depends on %s"), $f, $page));
373                                                 render($f);
374                                                 $rendered{$f}=1;
375                                                 last;
376                                         }
377                                 }
378                         }
379                 }
380                 
381                 # handle backlinks; if a page has added/removed links,
382                 # update the pages it links to
383                 my %linkchanged;
384                 foreach my $file (keys %rendered, @del) {
385                         my $page=pagename($file);
386                         
387                         if (exists $links{$page}) {
388                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
389                                         if (length $link &&
390                                             (! exists $oldlinks{$page} ||
391                                              ! grep { bestlink($page, $_) eq $link } @{$oldlinks{$page}})) {
392                                                 $linkchanged{$link}=1;
393                                         }
394                                 }
395                         }
396                         if (exists $oldlinks{$page}) {
397                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
398                                         if (length $link &&
399                                             (! exists $links{$page} || 
400                                              ! grep { bestlink($page, $_) eq $link } @{$links{$page}})) {
401                                                 $linkchanged{$link}=1;
402                                         }
403                                 }
404                         }
405                 }
406                 foreach my $link (keys %linkchanged) {
407                         my $linkfile=$pagesources{$link};
408                         if (defined $linkfile) {
409                                 next if $rendered{$linkfile};
410                                 debug(sprintf(gettext("rendering %s, to update its backlinks"), $linkfile));
411                                 render($linkfile);
412                                 $rendered{$linkfile}=1;
413                         }
414                 }
415         }
416
417         # remove no longer rendered files
418         foreach my $src (keys %rendered) {
419                 my $page=pagename($src);
420                 foreach my $file (@{$oldrenderedfiles{$page}}) {
421                         if (! grep { $_ eq $file } @{$renderedfiles{$page}}) {
422                                 debug(sprintf(gettext("removing %s, no longer rendered by %s"), $file, $page));
423                                 prune($config{destdir}."/".$file);
424                         }
425                 }
426         }
427
428         if (@del) {
429                 run_hooks(delete => sub { shift->(@del) });
430         }
431         if (%rendered) {
432                 run_hooks(change => sub { shift->(keys %rendered) });
433         }
434 } #}}}
435
436 sub commandline_render () { #{{{
437         loadplugins();
438         checkconfig();
439         lockwiki();
440         loadindex();
441         unlockwiki();
442
443         my $srcfile=possibly_foolish_untaint($config{render});
444         my $file=$srcfile;
445         $file=~s/\Q$config{srcdir}\E\/?//;
446
447         my $type=pagetype($file);
448         die sprintf(gettext("ikiwiki: cannot render %s"), $srcfile)."\n" unless defined $type;
449         my $content=readfile($srcfile);
450         my $page=pagename($file);
451         $pagesources{$page}=$file;
452         $content=filter($page, $content);
453         $content=preprocess($page, $page, $content);
454         $content=linkify($page, $page, $content);
455         $content=htmlize($page, $type, $content);
456
457         print genpage($page, $content, mtime($srcfile));
458         exit 0;
459 } #}}}
460
461 1