]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki/Render.pm
add dep on libtimedate-perl for str2time
[ikiwiki.git] / 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(srcfile($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         if ($config{hyperestraier}) {
218                 $template->param(hyperestraierurl => cgiurl());
219         }
220
221         if ($config{rss} && $inlinepages{$page}) {
222                 $template->param(rssurl => rsspage(basename($page)));
223         }
224         
225         $template->param(
226                 title => $title,
227                 wikiname => $config{wikiname},
228                 parentlinks => [parentlinks($page)],
229                 content => $content,
230                 backlinks => [backlinks($page)],
231                 discussionlink => htmllink($page, "Discussion", 1, 1),
232                 mtime => scalar(gmtime($mtime)),
233                 styleurl => styleurl($page),
234         );
235         
236         return $template->output;
237 } #}}}
238
239 sub date_822 ($) { #{{{
240         my $time=shift;
241
242         eval q{use POSIX};
243         return POSIX::strftime("%a, %d %b %Y %H:%M:%S %z", localtime($time));
244 } #}}}
245
246 sub absolute_urls ($$) { #{{{
247         # sucky sub because rss sucks
248         my $content=shift;
249         my $url=shift;
250
251         $url=~s/[^\/]+$//;
252         
253         $content=~s/<a\s+href="(?!http:\/\/)([^"]+)"/<a href="$url$1"/ig;
254         $content=~s/<img\s+src="(?!http:\/\/)([^"]+)"/<img src="$url$1"/ig;
255         return $content;
256 } #}}}
257
258 sub genrss ($$$) { #{{{
259         my $content=shift;
260         my $page=shift;
261         my $mtime=shift;
262         
263         my $url="$config{url}/".htmlpage($page);
264         
265         my $template=HTML::Template->new(blind_cache => 1,
266                 filename => "$config{templatedir}/rsspage.tmpl");
267         
268         my @items;
269         my $isblog=0;
270         my $gen_blog=sub {
271                 my $parentpage=shift;
272                 my %params=@_;
273                 
274                 if (! exists $params{show}) {
275                         $params{show}=10;
276                 }
277                 if (! exists $params{pages}) {
278                         return "";
279                 }
280                 
281                 $isblog=1;
282                 foreach my $page (blog_list($params{pages}, $params{show})) {
283                         next if $page eq $parentpage;
284                         push @items, {
285                                 itemtitle => pagetitle(basename($page)),
286                                 itemurl => "$config{url}/$renderedfiles{$page}",
287                                 itempubdate => date_822($pagectime{$page}),
288                                 itemcontent => absolute_urls(get_inline_content($parentpage, $page), $url),
289                         } if exists $renderedfiles{$page};
290                 }
291                 
292                 return "";
293         };
294         
295         $content = postprocess($page, $content, inline => $gen_blog);
296
297         $template->param(
298                 title => $config{wikiname},
299                 pageurl => $url,
300                 items => \@items,
301         );
302         
303         return $template->output;
304 } #}}}
305
306 sub check_overwrite ($$) { #{{{
307         # Important security check. Make sure to call this before saving
308         # any files to the source directory.
309         my $dest=shift;
310         my $src=shift;
311         
312         if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
313                 error("$dest already exists and was rendered from ".
314                         join(" ",(grep { $renderedfiles{$_} eq $dest } keys
315                                 %renderedfiles)).
316                         ", before, so not rendering from $src");
317         }
318 } #}}}
319
320 sub mtime ($) { #{{{
321         my $file=shift;
322         
323         return (stat($file))[9];
324 } #}}}
325
326 sub findlinks ($$) { #{{{
327         my $content=shift;
328         my $page=shift;
329
330         my @links;
331         while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
332                 push @links, titlepage($2);
333         }
334         # Discussion links are a special case since they're not in the text
335         # of the page, but on its template.
336         return @links, "$page/discussion";
337 } #}}}
338
339 sub render ($) { #{{{
340         my $file=shift;
341         
342         my $type=pagetype($file);
343         my $srcfile=srcfile($file);
344         my $content=readfile($srcfile);
345         if ($type ne 'unknown') {
346                 my $page=pagename($file);
347                 
348                 $links{$page}=[findlinks($content, $page)];
349                 delete $inlinepages{$page};
350                 
351                 $content=linkify($content, $page);
352                 $content=htmlize($type, $content);
353                 
354                 check_overwrite("$config{destdir}/".htmlpage($page), $page);
355                 writefile(htmlpage($page), $config{destdir},
356                         genpage($content, $page, mtime($srcfile)));
357                 $oldpagemtime{$page}=time;
358                 $renderedfiles{$page}=htmlpage($page);
359
360                 # TODO: should really add this to renderedfiles and call
361                 # check_overwrite, as above, but currently renderedfiles
362                 # only supports listing one file per page.
363                 if ($config{rss} && exists $inlinepages{$page}) {
364                         writefile(rsspage($page), $config{destdir},
365                                 genrss($content, $page, mtime($srcfile)));
366                 }
367         }
368         else {
369                 $links{$file}=[];
370                 check_overwrite("$config{destdir}/$file", $file);
371                 writefile($file, $config{destdir}, $content);
372                 $oldpagemtime{$file}=time;
373                 $renderedfiles{$file}=$file;
374         }
375 } #}}}
376
377 sub prune ($) { #{{{
378         my $file=shift;
379
380         unlink($file);
381         my $dir=dirname($file);
382         while (rmdir($dir)) {
383                 $dir=dirname($dir);
384         }
385 } #}}}
386
387 sub estcfg () { #{{{
388         my $estdir="$config{wikistatedir}/hyperestraier";
389         my $cgi=basename($config{cgiurl});
390         $cgi=~s/\..*$//;
391         open(TEMPLATE, ">$estdir/$cgi.tmpl") ||
392                 error("write $estdir/$cgi.tmpl: $!");
393         print TEMPLATE misctemplate("search", 
394                 "<!--ESTFORM-->\n\n<!--ESTRESULT-->\n\n<!--ESTINFO-->\n\n");
395         close TEMPLATE;
396         open(TEMPLATE, ">$estdir/$cgi.conf") ||
397                 error("write $estdir/$cgi.conf: $!");
398         my $template=HTML::Template->new(
399                 filename => "$config{templatedir}/estseek.conf"
400         );
401         eval q{use Cwd 'abs_path'};
402         $template->param(
403                 index => $estdir,
404                 tmplfile => "$estdir/$cgi.tmpl",
405                 destdir => abs_path($config{destdir}),
406                 url => $config{url},
407         );
408         print TEMPLATE $template->output;
409         close TEMPLATE;
410         $cgi="$estdir/".basename($config{cgiurl});
411         unlink($cgi);
412         symlink("/usr/lib/estraier/estseek.cgi", $cgi) ||
413                 error("symlink $cgi: $!");
414 } # }}}
415
416 sub estcmd ($;@) { #{{{
417         my @params=split(' ', shift);
418         push @params, "-cl", "$config{wikistatedir}/hyperestraier";
419         if (@_) {
420                 push @params, "-";
421         }
422         
423         my $pid=open(CHILD, "|-");
424         if ($pid) {
425                 # parent
426                 foreach (@_) {
427                         print CHILD "$_\n";
428                 }
429                 close(CHILD) || error("estcmd @params exited nonzero: $?");
430         }
431         else {
432                 # child
433                 open(STDOUT, "/dev/null"); # shut it up (closing won't work)
434                 exec("estcmd", @params) || error("can't run estcmd");
435         }
436 } #}}}
437
438 sub refresh () { #{{{
439         # find existing pages
440         my %exists;
441         my @files;
442         eval q{use File::Find};
443         find({
444                 no_chdir => 1,
445                 wanted => sub {
446                         if (/$config{wiki_file_prune_regexp}/) {
447                                 $File::Find::prune=1;
448                         }
449                         elsif (! -d $_ && ! -l $_) {
450                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
451                                 if (! defined $f) {
452                                         warn("skipping bad filename $_\n");
453                                 }
454                                 else {
455                                         $f=~s/^\Q$config{srcdir}\E\/?//;
456                                         push @files, $f;
457                                         $exists{pagename($f)}=1;
458                                 }
459                         }
460                 },
461         }, $config{srcdir});
462         find({
463                 no_chdir => 1,
464                 wanted => sub {
465                         if (/$config{wiki_file_prune_regexp}/) {
466                                 $File::Find::prune=1;
467                         }
468                         elsif (! -d $_ && ! -l $_) {
469                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
470                                 if (! defined $f) {
471                                         warn("skipping bad filename $_\n");
472                                 }
473                                 else {
474                                         # Don't add files that are in the
475                                         # srcdir.
476                                         $f=~s/^\Q$config{underlaydir}\E\/?//;
477                                         if (! -e "$config{srcdir}/$f" && 
478                                             ! -l "$config{srcdir}/$f") {
479                                                 push @files, $f;
480                                                 $exists{pagename($f)}=1;
481                                         }
482                                 }
483                         }
484                 },
485         }, $config{underlaydir});
486
487         my %rendered;
488
489         # check for added or removed pages
490         my @add;
491         foreach my $file (@files) {
492                 my $page=pagename($file);
493                 if (! $oldpagemtime{$page}) {
494                         debug("new page $page") unless exists $pagectime{$page};
495                         push @add, $file;
496                         $links{$page}=[];
497                         $pagesources{$page}=$file;
498                         $pagectime{$page}=mtime(srcfile($file))
499                                 unless exists $pagectime{$page};
500                 }
501         }
502         my @del;
503         foreach my $page (keys %oldpagemtime) {
504                 if (! $exists{$page}) {
505                         debug("removing old page $page");
506                         push @del, $pagesources{$page};
507                         prune($config{destdir}."/".$renderedfiles{$page});
508                         delete $renderedfiles{$page};
509                         $oldpagemtime{$page}=0;
510                         delete $pagesources{$page};
511                 }
512         }
513         
514         # render any updated files
515         foreach my $file (@files) {
516                 my $page=pagename($file);
517                 
518                 if (! exists $oldpagemtime{$page} ||
519                     mtime(srcfile($file)) > $oldpagemtime{$page}) {
520                         debug("rendering changed file $file");
521                         render($file);
522                         $rendered{$file}=1;
523                 }
524         }
525         
526         # if any files were added or removed, check to see if each page
527         # needs an update due to linking to them or inlining them.
528         # TODO: inefficient; pages may get rendered above and again here;
529         # problem is the bestlink may have changed and we won't know until
530         # now
531         if (@add || @del) {
532 FILE:           foreach my $file (@files) {
533                         my $page=pagename($file);
534                         foreach my $f (@add, @del) {
535                                 my $p=pagename($f);
536                                 foreach my $link (@{$links{$page}}) {
537                                         if (bestlink($page, $link) eq $p) {
538                                                 debug("rendering $file, which links to $p");
539                                                 render($file);
540                                                 $rendered{$file}=1;
541                                                 next FILE;
542                                         }
543                                 }
544                         }
545                 }
546         }
547
548         # Handle backlinks; if a page has added/removed links, update the
549         # pages it links to. Also handle inlining here.
550         # TODO: inefficient; pages may get rendered above and again here;
551         # problem is the backlinks could be wrong in the first pass render
552         # above
553         if (%rendered || @del) {
554                 foreach my $f (@files) {
555                         my $p=pagename($f);
556                         if (exists $inlinepages{$p}) {
557                                 foreach my $file (keys %rendered, @del) {
558                                         my $page=pagename($file);
559                                         if (globlist_match($page, $inlinepages{$p})) {
560                                                 debug("rendering $f, which inlines $page");
561                                                 render($f);
562                                                 $rendered{$f}=1;
563                                                 last;
564                                         }
565                                 }
566                         }
567                 }
568                 
569                 my %linkchanged;
570                 foreach my $file (keys %rendered, @del) {
571                         my $page=pagename($file);
572                         
573                         if (exists $links{$page}) {
574                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
575                                         if (length $link &&
576                                             ! exists $oldlinks{$page} ||
577                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
578                                                 $linkchanged{$link}=1;
579                                         }
580                                 }
581                         }
582                         if (exists $oldlinks{$page}) {
583                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
584                                         if (length $link &&
585                                             ! exists $links{$page} ||
586                                             ! grep { $_ eq $link } @{$links{$page}}) {
587                                                 $linkchanged{$link}=1;
588                                         }
589                                 }
590                         }
591                 }
592                 foreach my $link (keys %linkchanged) {
593                         my $linkfile=$pagesources{$link};
594                         if (defined $linkfile) {
595                                 debug("rendering $linkfile, to update its backlinks");
596                                 render($linkfile);
597                                 $rendered{$linkfile}=1;
598                         }
599                 }
600         }
601
602         if ($config{hyperestraier} && (%rendered || @del)) {
603                 debug("updating hyperestraier search index");
604                 if (%rendered) {
605                         estcmd("gather -cm -bc -cl -sd", 
606                                 map { $config{destdir}."/".$renderedfiles{pagename($_)} }
607                                 keys %rendered);
608                 }
609                 if (@del) {
610                         estcmd("purge -cl");
611                 }
612                 
613                 debug("generating hyperestraier cgi config");
614                 estcfg();
615         }
616 } #}}}
617
618 1