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