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