add archive pages and fix some bugs
[ikiwiki] / IkiWiki / Render.pm
1 package IkiWiki;
2
3 use warnings;
4 use strict;
5 use File::Spec;
6
7 sub linkify ($$) { #{{{
8         my $content=shift;
9         my $page=shift;
10
11         $content =~ s{(\\?)$config{wiki_link_regexp}}{
12                 $1 ? "[[$2]]" : htmllink($page, $2)
13         }eg;
14         
15         return $content;
16 } #}}}
17
18 sub htmlize ($$) { #{{{
19         my $type=shift;
20         my $content=shift;
21         
22         if (! $INC{"/usr/bin/markdown"}) {
23                 no warnings 'once';
24                 $blosxom::version="is a proper perl module too much to ask?";
25                 use warnings 'all';
26                 do "/usr/bin/markdown";
27         }
28         
29         if ($type eq '.mdwn') {
30                 return Markdown::Markdown($content);
31         }
32         else {
33                 error("htmlization of $type not supported");
34         }
35 } #}}}
36
37 sub backlinks ($) { #{{{
38         my $page=shift;
39
40         my @links;
41         foreach my $p (keys %links) {
42                 next if bestlink($page, $p) eq $page;
43                 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
44                         my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
45                         
46                         # Trim common dir prefixes from both pages.
47                         my $p_trimmed=$p;
48                         my $page_trimmed=$page;
49                         my $dir;
50                         1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
51                                 defined $dir &&
52                                 $p_trimmed=~s/^\Q$dir\E// &&
53                                 $page_trimmed=~s/^\Q$dir\E//;
54                                        
55                         push @links, { url => $href, page => $p_trimmed };
56                 }
57         }
58
59         return sort { $a->{page} cmp $b->{page} } @links;
60 } #}}}
61
62 sub parentlinks ($) { #{{{
63         my $page=shift;
64         
65         my @ret;
66         my $pagelink="";
67         my $path="";
68         my $skip=1;
69         foreach my $dir (reverse split("/", $page)) {
70                 if (! $skip) {
71                         $path.="../";
72                         unshift @ret, { url => "$path$dir.html", page => $dir };
73                 }
74                 else {
75                         $skip=0;
76                 }
77         }
78         unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
79         return @ret;
80 } #}}}
81
82 sub rsspage ($) { #{{{
83         my $page=shift;
84
85         return $page.".rss";
86 } #}}}
87
88 sub postprocess { #{{{
89         # Takes content to postprocess followed by a list of postprocessor
90         # commands and subroutine references to run for the commands.
91         my $page=shift;
92         my $content=shift;
93         my %commands=@_;
94         
95         my $handle=sub {
96                 my $escape=shift;
97                 my $command=shift;
98                 my $params=shift;
99                 if (length $escape) {
100                         "[[$command $params]]";
101                 }
102                 elsif (exists $commands{$command}) {
103                         my %params;
104                         while ($params =~ /(\w+)=\"([^"]+)"(\s+|$)/g) {
105                                 $params{$1}=$2;
106                         }
107                         $commands{$command}->($page, %params);
108                 }
109                 else {
110                         "[[bad directive $command]]";
111                 }
112         };
113         
114         $content =~ s{(\\?)$config{wiki_processor_regexp}}{$handle->($1, $2, $3)}eg;
115         return $content;
116 } #}}}
117
118 sub blog_list ($$) { #{{{
119         my $globlist=shift;
120         my $maxitems=shift;
121         
122         my @list;
123         foreach my $page (keys %pagesources) {
124                 if (globlist_match($page, $globlist)) {
125                         push @list, $page;
126                 }
127         }
128
129         @list=sort { $pagectime{$b} <=> $pagectime{$a} } @list;
130         return @list if ! $maxitems || @list <= $maxitems;
131         return @list[0..$maxitems - 1];
132 } #}}}
133
134 sub get_inline_content ($$) { #{{{
135         my $parentpage=shift;
136         my $page=shift;
137         
138         my $file=$pagesources{$page};
139         my $type=pagetype($file);
140         if ($type ne 'unknown') {
141                 return htmlize($type, linkify(readfile("$config{srcdir}/$file"), $parentpage));
142         }
143         else {
144                 return "";
145         }
146 } #}}}
147
148 sub postprocess_html_inline { #{{{
149         my $parentpage=shift;
150         my %params=@_;
151         
152         if (! exists $params{pages}) {
153                 return "";
154         }
155         if (! exists $params{archive}) {
156                 $params{archive}="no";
157         }
158         if (! exists $params{show} && $params{archive} eq "no") {
159                 $params{show}=10;
160         }
161         $inlinepages{$parentpage}=$params{pages};
162                 
163         my $template=HTML::Template->new(blind_cache => 1,
164                 filename => (($params{archive} eq "no") 
165                                 ? "$config{templatedir}/inlinepage.tmpl"
166                                 : "$config{templatedir}/inlinepagetitle.tmpl"));
167         
168         my $ret="";
169         foreach my $page (blog_list($params{pages}, $params{show})) {
170                 next if $page eq $parentpage;
171                 $template->param(pagelink => htmllink($parentpage, $page));
172                 $template->param(content => get_inline_content($parentpage, $page))
173                         if $params{archive} eq "no";
174                 $template->param(ctime => scalar(gmtime($pagectime{$page})));
175                 $ret.=$template->output;
176         }
177         
178         return $ret;
179 } #}}}
180
181 sub genpage ($$$) { #{{{
182         my $content=shift;
183         my $page=shift;
184         my $mtime=shift;
185
186         $content = postprocess($page, $content, inline => \&postprocess_html_inline);
187         
188         my $title=pagetitle(basename($page));
189         
190         my $template=HTML::Template->new(blind_cache => 1,
191                 filename => "$config{templatedir}/page.tmpl");
192         
193         if (length $config{cgiurl}) {
194                 $template->param(editurl => "$config{cgiurl}?do=edit&page=$page");
195                 $template->param(prefsurl => "$config{cgiurl}?do=prefs");
196                 if ($config{rcs}) {
197                         $template->param(recentchangesurl => "$config{cgiurl}?do=recentchanges");
198                 }
199         }
200
201         if (length $config{historyurl}) {
202                 my $u=$config{historyurl};
203                 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
204                 $template->param(historyurl => $u);
205         }
206
207         if ($config{rss}) {
208                 $template->param(rssurl => rsspage($page));
209         }
210         
211         $template->param(
212                 title => $title,
213                 wikiname => $config{wikiname},
214                 parentlinks => [parentlinks($page)],
215                 content => $content,
216                 backlinks => [backlinks($page)],
217                 discussionlink => htmllink($page, "Discussion", 1, 1),
218                 mtime => scalar(gmtime($mtime)),
219         );
220         
221         return $template->output;
222 } #}}}
223
224 sub date_822 ($) { #{{{
225         my $time=shift;
226
227         eval q{use POSIX};
228         return POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
229 } #}}}
230
231 sub absolute_urls ($$) { #{{{
232         # sucky sub because rss sucks
233         my $content=shift;
234         my $url=shift;
235
236         $url=~s/[^\/]+$//;
237         
238         $content=~s/<a\s+href="(?!http:\/\/)([^"]+)"/<a href="$url$1"/ig;
239         $content=~s/<img\s+src="(?!http:\/\/)([^"]+)"/<img src="$url$1"/ig;
240         return $content;
241 } #}}}zo
242
243 sub genrss ($$$) { #{{{
244         my $content=shift;
245         my $page=shift;
246         my $mtime=shift;
247         
248         my $url="$config{url}/".htmlpage($page);
249         
250         my $template=HTML::Template->new(blind_cache => 1,
251                 filename => "$config{templatedir}/rsspage.tmpl");
252         
253         my @items;
254         my $isblog=0;
255         my $gen_blog=sub {
256                 my $parentpage=shift;
257                 my %params=@_;
258                 
259                 return "" if exists $params{archive} && $params{archive} eq 'yes';
260                 
261                 if (! exists $params{show}) {
262                         $params{show}=10;
263                 }
264                 if (! exists $params{pages}) {
265                         return "";
266                 }
267                 $inlinepages{$parentpage}=$params{pages};
268                 
269                 $isblog=1;
270                 foreach my $page (blog_list($params{pages}, $params{show})) {
271                         next if $page eq $parentpage;
272                         push @items, {
273                                 itemtitle => pagetitle(basename($page)),
274                                 itemurl => "$config{url}/$renderedfiles{$page}",
275                                 itempubdate => date_822($pagectime{$page}),
276                                 itemcontent => absolute_urls(get_inline_content($parentpage, $page), $url),
277                         } if exists $renderedfiles{$page};
278                 }
279                 
280                 return "";
281         };
282         
283         $content = postprocess($page, $content, inline => $gen_blog);
284
285         # Regular page gets a feed that is updated every time the
286         # page is changed, so the mtime is encoded in the guid.
287         push @items, {
288                 itemtitle => pagetitle(basename($page)),
289                 itemguid => "$url?mtime=$mtime",
290                 itemurl => $url,
291                 itempubdate => date_822($mtime),
292                 itemcontent => absolute_urls($content, $url),
293         } unless $isblog;
294         
295         $template->param(
296                 title => $config{wikiname},
297                 pageurl => $url,
298                 items => \@items,
299         );
300         
301         return $template->output;
302 } #}}}
303
304 sub check_overwrite ($$) { #{{{
305         # Important security check. Make sure to call this before saving
306         # any files to the source directory.
307         my $dest=shift;
308         my $src=shift;
309         
310         if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
311                 error("$dest already exists and was rendered from ".
312                         join(" ",(grep { $renderedfiles{$_} eq $dest } keys
313                                 %renderedfiles)).
314                         ", before, so not rendering from $src");
315         }
316 } #}}}
317
318 sub mtime ($) { #{{{
319         my $page=shift;
320         
321         return (stat($page))[9];
322 } #}}}
323
324 sub findlinks ($$) { #{{{
325         my $content=shift;
326         my $page=shift;
327
328         my @links;
329         while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
330                 push @links, lc($1);
331         }
332         # Discussion links are a special case since they're not in the text
333         # of the page, but on its template.
334         return @links, "$page/discussion";
335 } #}}}
336
337 sub render ($) { #{{{
338         my $file=shift;
339         
340         my $type=pagetype($file);
341         my $content=readfile("$config{srcdir}/$file");
342         if ($type ne 'unknown') {
343                 my $page=pagename($file);
344                 
345                 $links{$page}=[findlinks($content, $page)];
346                 delete $inlinepages{$page};
347                 
348                 $content=linkify($content, $page);
349                 $content=htmlize($type, $content);
350                 
351                 check_overwrite("$config{destdir}/".htmlpage($page), $page);
352                 writefile("$config{destdir}/".htmlpage($page),
353                         genpage($content, $page, mtime("$config{srcdir}/$file")));
354                 $oldpagemtime{$page}=time;
355                 $renderedfiles{$page}=htmlpage($page);
356
357                 # TODO: should really add this to renderedfiles and call
358                 # check_overwrite, as above, but currently renderedfiles
359                 # only supports listing one file per page.
360                 if ($config{rss}) {
361                         writefile("$config{destdir}/".rsspage($page),
362                                 genrss($content, $page, mtime("$config{srcdir}/$file")));
363                 }
364         }
365         else {
366                 $links{$file}=[];
367                 check_overwrite("$config{destdir}/$file", $file);
368                 writefile("$config{destdir}/$file", $content);
369                 $oldpagemtime{$file}=time;
370                 $renderedfiles{$file}=$file;
371         }
372 } #}}}
373
374 sub prune ($) { #{{{
375         my $file=shift;
376
377         unlink($file);
378         my $dir=dirname($file);
379         while (rmdir($dir)) {
380                 $dir=dirname($dir);
381         }
382 } #}}}
383
384 sub refresh () { #{{{
385         # find existing pages
386         my %exists;
387         my @files;
388         eval q{use File::Find};
389         find({
390                 no_chdir => 1,
391                 wanted => sub {
392                         if (/$config{wiki_file_prune_regexp}/) {
393                                 no warnings 'once';
394                                 $File::Find::prune=1;
395                                 use warnings "all";
396                         }
397                         elsif (! -d $_ && ! -l $_) {
398                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
399                                 if (! defined $f) {
400                                         warn("skipping bad filename $_\n");
401                                 }
402                                 else {
403                                         $f=~s/^\Q$config{srcdir}\E\/?//;
404                                         push @files, $f;
405                                         $exists{pagename($f)}=1;
406                                 }
407                         }
408                 },
409         }, $config{srcdir});
410
411         my %rendered;
412
413         # check for added or removed pages
414         my @add;
415         foreach my $file (@files) {
416                 my $page=pagename($file);
417                 if (! $oldpagemtime{$page}) {
418                         debug("new page $page") unless exists $pagectime{$page};
419                         push @add, $file;
420                         $links{$page}=[];
421                         $pagesources{$page}=$file;
422                         $pagectime{$page}=time unless exists $pagectime{$page};
423                 }
424         }
425         my @del;
426         foreach my $page (keys %oldpagemtime) {
427                 if (! $exists{$page}) {
428                         debug("removing old page $page");
429                         push @del, $pagesources{$page};
430                         prune($config{destdir}."/".$renderedfiles{$page});
431                         delete $renderedfiles{$page};
432                         $oldpagemtime{$page}=0;
433                         delete $pagesources{$page};
434                 }
435         }
436         
437         # render any updated files
438         foreach my $file (@files) {
439                 my $page=pagename($file);
440                 
441                 if (! exists $oldpagemtime{$page} ||
442                     mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
443                         debug("rendering changed file $file");
444                         render($file);
445                         $rendered{$file}=1;
446                 }
447         }
448         
449         # if any files were added or removed, check to see if each page
450         # needs an update due to linking to them or inlining them.
451         # TODO: inefficient; pages may get rendered above and again here;
452         # problem is the bestlink may have changed and we won't know until
453         # now
454         if (@add || @del) {
455 FILE:           foreach my $file (@files) {
456                         my $page=pagename($file);
457                         foreach my $f (@add, @del) {
458                                 my $p=pagename($f);
459                                 foreach my $link (@{$links{$page}}) {
460                                         if (bestlink($page, $link) eq $p) {
461                                                 debug("rendering $file, which links to $p");
462                                                 render($file);
463                                                 $rendered{$file}=1;
464                                                 next FILE;
465                                         }
466                                 }
467                         }
468                 }
469         }
470
471         # Handle backlinks; if a page has added/removed links, update the
472         # pages it links to. Also handle inlining here.
473         # TODO: inefficient; pages may get rendered above and again here;
474         # problem is the backlinks could be wrong in the first pass render
475         # above
476         if (%rendered || @del) {
477                 my %linkchanged;
478                 foreach my $file (keys %rendered, @del) {
479                         my $page=pagename($file);
480                         
481                         foreach my $f (@files) {
482                                 my $p=pagename($f);
483                                 if (exists $inlinepages{$p} && 
484                                     globlist_match($page, $inlinepages{$p})) {
485                                         debug("rendering $f, which inlines $page");
486                                         render($f);
487                                         next;
488                                 }
489                         }
490                         
491                         if (exists $links{$page}) {
492                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
493                                         if (length $link &&
494                                             ! exists $oldlinks{$page} ||
495                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
496                                                 $linkchanged{$link}=1;
497                                         }
498                                 }
499                         }
500                         if (exists $oldlinks{$page}) {
501                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
502                                         if (length $link &&
503                                             ! exists $links{$page} ||
504                                             ! grep { $_ eq $link } @{$links{$page}}) {
505                                                 $linkchanged{$link}=1;
506                                         }
507                                 }
508                         }
509                 }
510                 foreach my $link (keys %linkchanged) {
511                         my $linkfile=$pagesources{$link};
512                         if (defined $linkfile) {
513                                 debug("rendering $linkfile, to update its backlinks");
514                                 render($linkfile);
515                         }
516                 }
517         }
518 } #}}}
519
520 1