]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
385d16a56a96e32506dd4e6f8e3da690502b60a7
[ikiwiki.git] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4 use warnings;
5 use strict;
6 use Encode;
7 use HTML::Entities;
8 use open qw{:utf8 :std};
9
10 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
11             %renderedfiles %oldrenderedfiles %pagesources %depends %hooks
12             %forcerebuild $gettext_obj};
13
14 use Exporter q{import};
15 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
16                  bestlink htmllink readfile writefile pagetype srcfile pagename
17                  displaytime will_render gettext
18                  %config %links %renderedfiles %pagesources);
19 our $VERSION = 1.02; # plugin interface version, next is ikiwiki version
20 our $version="1.45";my $installdir="/usr";
21 # Optimisation.
22 use Memoize;
23 memoize("abs2rel");
24 memoize("pagespec_translate");
25 memoize("file_pruned");
26
27 sub defaultconfig () { #{{{
28         wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
29                 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
30                 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
31         wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
32         wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
33         web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
34         verbose => 0,
35         syslog => 0,
36         wikiname => "wiki",
37         default_pageext => "mdwn",
38         cgi => 0,
39         post_commit => 0,
40         rcs => '',
41         notify => 0,
42         url => '',
43         cgiurl => '',
44         historyurl => '',
45         diffurl => '',
46         rss => 0,
47         atom => 0,
48         discussion => 1,
49         rebuild => 0,
50         refresh => 0,
51         getctime => 0,
52         w3mmode => 0,
53         wrapper => undef,
54         wrappermode => undef,
55         svnrepo => undef,
56         svnpath => "trunk",
57         gitorigin_branch => "origin",
58         gitmaster_branch => "master",
59         srcdir => undef,
60         destdir => undef,
61         pingurl => [],
62         templatedir => "$installdir/share/ikiwiki/templates",
63         underlaydir => "$installdir/share/ikiwiki/basewiki",
64         setup => undef,
65         adminuser => undef,
66         adminemail => undef,
67         plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
68                       lockedit conditional}],
69         timeformat => '%c',
70         locale => undef,
71         sslcookie => 0,
72         httpauth => 0,
73         userdir => "",
74 } #}}}
75    
76 sub checkconfig () { #{{{
77         # locale stuff; avoid LC_ALL since it overrides everything
78         if (defined $ENV{LC_ALL}) {
79                 $ENV{LANG} = $ENV{LC_ALL};
80                 delete $ENV{LC_ALL};
81         }
82         if (defined $config{locale}) {
83                 eval q{use POSIX};
84                 error($@) if $@;
85                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
86                         $ENV{LANG}=$config{locale};
87                         $gettext_obj=undef;
88                 }
89         }
90
91         if ($config{w3mmode}) {
92                 eval q{use Cwd q{abs_path}};
93                 error($@) if $@;
94                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
95                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
96                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
97                         unless $config{cgiurl} =~ m!file:///!;
98                 $config{url}="file://".$config{destdir};
99         }
100
101         if ($config{cgi} && ! length $config{url}) {
102                 error(gettext("Must specify url to wiki with --url when using --cgi"));
103         }
104         
105         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
106                 unless exists $config{wikistatedir};
107         
108         if ($config{rcs}) {
109                 eval qq{require IkiWiki::Rcs::$config{rcs}};
110                 if ($@) {
111                         error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
112                 }
113         }
114         else {
115                 require IkiWiki::Rcs::Stub;
116         }
117
118         run_hooks(checkconfig => sub { shift->() });
119 } #}}}
120
121 sub loadplugins () { #{{{
122         loadplugin($_) foreach @{$config{plugin}};
123         
124         run_hooks(getopt => sub { shift->() });
125         if (grep /^-/, @ARGV) {
126                 print STDERR "Unknown option: $_\n"
127                         foreach grep /^-/, @ARGV;
128                 usage();
129         }
130 } #}}}
131
132 sub loadplugin ($) { #{{{
133         my $plugin=shift;
134
135         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
136
137         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
138         eval qq{use $mod};
139         if ($@) {
140                 error("Failed to load plugin $mod: $@");
141         }
142 } #}}}
143
144 sub error ($;$) { #{{{
145         my $message=shift;
146         my $cleaner=shift;
147         if ($config{cgi}) {
148                 print "Content-type: text/html\n\n";
149                 print misctemplate(gettext("Error"),
150                         "<p>".gettext("Error").": $message</p>");
151         }
152         log_message(debug => $message) if $config{syslog};
153         if (defined $cleaner) {
154                 $cleaner->();
155         }
156         die $message."\n";
157 } #}}}
158
159 sub debug ($) { #{{{
160         return unless $config{verbose};
161         log_message(debug => @_);
162 } #}}}
163
164 my $log_open=0;
165 sub log_message ($$) { #{{{
166         my $type=shift;
167
168         if ($config{syslog}) {
169                 require Sys::Syslog;
170                 unless ($log_open) {
171                         Sys::Syslog::setlogsock('unix');
172                         Sys::Syslog::openlog('ikiwiki', '', 'user');
173                         $log_open=1;
174                 }
175                 eval {
176                         Sys::Syslog::syslog($type, "%s", join(" ", @_));
177                 }
178         }
179         elsif (! $config{cgi}) {
180                 print "@_\n";
181         }
182         else {
183                 print STDERR "@_\n";
184         }
185 } #}}}
186
187 sub possibly_foolish_untaint ($) { #{{{
188         my $tainted=shift;
189         my ($untainted)=$tainted=~/(.*)/;
190         return $untainted;
191 } #}}}
192
193 sub basename ($) { #{{{
194         my $file=shift;
195
196         $file=~s!.*/+!!;
197         return $file;
198 } #}}}
199
200 sub dirname ($) { #{{{
201         my $file=shift;
202
203         $file=~s!/*[^/]+$!!;
204         return $file;
205 } #}}}
206
207 sub pagetype ($) { #{{{
208         my $page=shift;
209         
210         if ($page =~ /\.([^.]+)$/) {
211                 return $1 if exists $hooks{htmlize}{$1};
212         }
213         return undef;
214 } #}}}
215
216 sub pagename ($) { #{{{
217         my $file=shift;
218
219         my $type=pagetype($file);
220         my $page=$file;
221         $page=~s/\Q.$type\E*$// if defined $type;
222         return $page;
223 } #}}}
224
225 sub htmlpage ($) { #{{{
226         my $page=shift;
227
228         return $page.".html";
229 } #}}}
230
231 sub srcfile ($) { #{{{
232         my $file=shift;
233
234         return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
235         return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
236         error("internal error: $file cannot be found");
237 } #}}}
238
239 sub readfile ($;$$) { #{{{
240         my $file=shift;
241         my $binary=shift;
242         my $wantfd=shift;
243
244         if (-l $file) {
245                 error("cannot read a symlink ($file)");
246         }
247         
248         local $/=undef;
249         open (IN, $file) || error("failed to read $file: $!");
250         binmode(IN) if ($binary);
251         return \*IN if $wantfd;
252         my $ret=<IN>;
253         close IN || error("failed to read $file: $!");
254         return $ret;
255 } #}}}
256
257 sub writefile ($$$;$$) { #{{{
258         my $file=shift; # can include subdirs
259         my $destdir=shift; # directory to put file in
260         my $content=shift;
261         my $binary=shift;
262         my $writer=shift;
263         
264         my $test=$file;
265         while (length $test) {
266                 if (-l "$destdir/$test") {
267                         error("cannot write to a symlink ($test)");
268                 }
269                 $test=dirname($test);
270         }
271         my $newfile="$destdir/$file.ikiwiki-new";
272         if (-l $newfile) {
273                 error("cannot write to a symlink ($newfile)");
274         }
275
276         my $dir=dirname($newfile);
277         if (! -d $dir) {
278                 my $d="";
279                 foreach my $s (split(m!/+!, $dir)) {
280                         $d.="$s/";
281                         if (! -d $d) {
282                                 mkdir($d) || error("failed to create directory $d: $!");
283                         }
284                 }
285         }
286
287         my $cleanup = sub { unlink($newfile) };
288         open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
289         binmode(OUT) if ($binary);
290         if ($writer) {
291                 $writer->(\*OUT, $cleanup);
292         }
293         else {
294                 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
295         }
296         close OUT || error("failed saving $newfile: $!", $cleanup);
297         rename($newfile, "$destdir/$file") || 
298                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
299 } #}}}
300
301 my %cleared;
302 sub will_render ($$;$) { #{{{
303         my $page=shift;
304         my $dest=shift;
305         my $clear=shift;
306
307         # Important security check.
308         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
309             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
310                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
311         }
312
313         if (! $clear || $cleared{$page}) {
314                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
315         }
316         else {
317                 $renderedfiles{$page}=[$dest];
318                 $cleared{$page}=1;
319         }
320 } #}}}
321
322 sub bestlink ($$) { #{{{
323         my $page=shift;
324         my $link=shift;
325         
326         my $cwd=$page;
327         if ($link=~s/^\/+//) {
328                 # absolute links
329                 $cwd="";
330         }
331
332         do {
333                 my $l=$cwd;
334                 $l.="/" if length $l;
335                 $l.=$link;
336
337                 if (exists $links{$l}) {
338                         return $l;
339                 }
340                 elsif (exists $pagecase{lc $l}) {
341                         return $pagecase{lc $l};
342                 }
343         } while $cwd=~s!/?[^/]+$!!;
344
345         if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
346                 return "$config{userdir}/".lc($link);
347         }
348
349         #print STDERR "warning: page $page, broken link: $link\n";
350         return "";
351 } #}}}
352
353 sub isinlinableimage ($) { #{{{
354         my $file=shift;
355         
356         $file=~/\.(png|gif|jpg|jpeg)$/i;
357 } #}}}
358
359 sub pagetitle ($;$) { #{{{
360         my $page=shift;
361         my $unescaped=shift;
362
363         if ($unescaped) {
364                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
365         }
366         else {
367                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
368         }
369
370         return $page;
371 } #}}}
372
373 sub titlepage ($) { #{{{
374         my $title=shift;
375         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
376         return $title;
377 } #}}}
378
379 sub linkpage ($) { #{{{
380         my $link=shift;
381         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
382         return $link;
383 } #}}}
384
385 sub cgiurl (@) { #{{{
386         my %params=@_;
387
388         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
389 } #}}}
390
391 sub baseurl (;$) { #{{{
392         my $page=shift;
393
394         return "$config{url}/" if ! defined $page;
395         
396         $page=~s/[^\/]+$//;
397         $page=~s/[^\/]+\//..\//g;
398         return $page;
399 } #}}}
400
401 sub abs2rel ($$) { #{{{
402         # Work around very innefficient behavior in File::Spec if abs2rel
403         # is passed two relative paths. It's much faster if paths are
404         # absolute! (Debian bug #376658; fixed in debian unstable now)
405         my $path="/".shift;
406         my $base="/".shift;
407
408         require File::Spec;
409         my $ret=File::Spec->abs2rel($path, $base);
410         $ret=~s/^// if defined $ret;
411         return $ret;
412 } #}}}
413
414 sub displaytime ($) { #{{{
415         my $time=shift;
416
417         eval q{use POSIX};
418         error($@) if $@;
419         # strftime doesn't know about encodings, so make sure
420         # its output is properly treated as utf8
421         return decode_utf8(POSIX::strftime(
422                         $config{timeformat}, localtime($time)));
423 } #}}}
424
425 sub htmllink ($$$;@) { #{{{
426         my $lpage=shift; # the page doing the linking
427         my $page=shift; # the page that will contain the link (different for inline)
428         my $link=shift;
429         my %opts=@_;
430
431 print STDERR "bestlink $lpage $link\n" if $lpage eq "roadmap" && $link =~/rcs/;
432
433         my $bestlink;
434         if (! $opts{forcesubpage}) {
435                 $bestlink=bestlink($lpage, $link);
436         }
437         else {
438                 $bestlink="$lpage/".lc($link);
439         }
440
441         my $linktext;
442         if (defined $opts{linktext}) {
443                 $linktext=$opts{linktext};
444         }
445         else {
446                 $linktext=pagetitle(basename($link));
447         }
448         
449         return "<span class=\"selflink\">$linktext</span>"
450                 if length $bestlink && $page eq $bestlink;
451         
452         if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
453                 $bestlink=htmlpage($bestlink);
454         }
455         if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
456                 return $linktext unless length $config{cgiurl};
457                 return "<span><a href=\"".
458                         cgiurl(do => "create", page => lc($link), from => $page).
459                         "\">?</a>$linktext</span>"
460         }
461         
462         $bestlink=abs2rel($bestlink, dirname($page));
463         
464         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
465                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
466         }
467
468         if (defined $opts{anchor}) {
469                 $bestlink.="#".$opts{anchor};
470         }
471
472         return "<a href=\"$bestlink\">$linktext</a>";
473 } #}}}
474
475 sub htmlize ($$$) { #{{{
476         my $page=shift;
477         my $type=shift;
478         my $content=shift;
479
480         if (exists $hooks{htmlize}{$type}) {
481                 $content=$hooks{htmlize}{$type}{call}->(
482                         page => $page,
483                         content => $content,
484                 );
485         }
486         else {
487                 error("htmlization of $type not supported");
488         }
489
490         run_hooks(sanitize => sub {
491                 $content=shift->(
492                         page => $page,
493                         content => $content,
494                 );
495         });
496
497         return $content;
498 } #}}}
499
500 sub linkify ($$$) { #{{{
501         my $lpage=shift; # the page containing the links
502         my $page=shift; # the page the link will end up on (different for inline)
503         my $content=shift;
504
505         $content =~ s{(\\?)$config{wiki_link_regexp}}{
506                 defined $2
507                         ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4, linktext => pagetitle($2)))
508                         : ( $1 ? "[[$3]]"    : htmllink($lpage, $page, linkpage($3), anchor => $4))
509         }eg;
510         
511         return $content;
512 } #}}}
513
514 my %preprocessing;
515 our $preprocess_preview=0;
516 sub preprocess ($$$;$$) { #{{{
517         my $page=shift; # the page the data comes from
518         my $destpage=shift; # the page the data will appear in (different for inline)
519         my $content=shift;
520         my $scan=shift;
521         my $preview=shift;
522
523         # Using local because it needs to be set within any nested calls
524         # of this function.
525         local $preprocess_preview=$preview if defined $preview;
526
527         my $handle=sub {
528                 my $escape=shift;
529                 my $command=shift;
530                 my $params=shift;
531                 if (length $escape) {
532                         return "[[$command $params]]";
533                 }
534                 elsif (exists $hooks{preprocess}{$command}) {
535                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
536                         # Note: preserve order of params, some plugins may
537                         # consider it significant.
538                         my @params;
539                         while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
540                                 my $key=$1;
541                                 my $val;
542                                 if (defined $2) {
543                                         $val=$2;
544                                         $val=~s/\r\n/\n/mg;
545                                         $val=~s/^\n+//g;
546                                         $val=~s/\n+$//g;
547                                 }
548                                 elsif (defined $3) {
549                                         $val=$3;
550                                 }
551                                 elsif (defined $4) {
552                                         $val=$4;
553                                 }
554
555                                 if (defined $key) {
556                                         push @params, $key, $val;
557                                 }
558                                 else {
559                                         push @params, $val, '';
560                                 }
561                         }
562                         if ($preprocessing{$page}++ > 3) {
563                                 # Avoid loops of preprocessed pages preprocessing
564                                 # other pages that preprocess them, etc.
565                                 #translators: The first parameter is a
566                                 #translators: preprocessor directive name,
567                                 #translators: the second a page name, the
568                                 #translators: third a number.
569                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
570                                         $command, $page, $preprocessing{$page}).
571                                 "]]";
572                         }
573                         my $ret=$hooks{preprocess}{$command}{call}->(
574                                 @params,
575                                 page => $page,
576                                 destpage => $destpage,
577                                 preview => $preprocess_preview,
578                         );
579                         $preprocessing{$page}--;
580                         return $ret;
581                 }
582                 else {
583                         return "[[$command $params]]";
584                 }
585         };
586         
587         $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
588         return $content;
589 } #}}}
590
591 sub filter ($$) { #{{{
592         my $page=shift;
593         my $content=shift;
594
595         run_hooks(filter => sub {
596                 $content=shift->(page => $page, content => $content);
597         });
598
599         return $content;
600 } #}}}
601
602 sub indexlink () { #{{{
603         return "<a href=\"$config{url}\">$config{wikiname}</a>";
604 } #}}}
605
606 sub lockwiki () { #{{{
607         # Take an exclusive lock on the wiki to prevent multiple concurrent
608         # run issues. The lock will be dropped on program exit.
609         if (! -d $config{wikistatedir}) {
610                 mkdir($config{wikistatedir});
611         }
612         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
613                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
614         if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
615                 debug("wiki seems to be locked, waiting for lock");
616                 my $wait=600; # arbitrary, but don't hang forever to 
617                               # prevent process pileup
618                 for (1..$wait) {
619                         return if flock(WIKILOCK, 2 | 4);
620                         sleep 1;
621                 }
622                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
623         }
624 } #}}}
625
626 sub unlockwiki () { #{{{
627         close WIKILOCK;
628 } #}}}
629
630 sub commit_hook_enabled () { #{{{
631         open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
632                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
633         if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
634                 close COMMITLOCK;
635                 return 0;
636         }
637         close COMMITLOCK;
638         return 1;
639 } #}}}
640
641 sub disable_commit_hook () { #{{{
642         open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
643                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
644         if (! flock(COMMITLOCK, 2)) { # LOCK_EX
645                 error("failed to get commit lock");
646         }
647 } #}}}
648
649 sub enable_commit_hook () { #{{{
650         close COMMITLOCK;
651 } #}}}
652
653 sub loadindex () { #{{{
654         open (IN, "$config{wikistatedir}/index") || return;
655         while (<IN>) {
656                 $_=possibly_foolish_untaint($_);
657                 chomp;
658                 my %items;
659                 $items{link}=[];
660                 $items{dest}=[];
661                 foreach my $i (split(/ /, $_)) {
662                         my ($item, $val)=split(/=/, $i, 2);
663                         push @{$items{$item}}, decode_entities($val);
664                 }
665
666                 next unless exists $items{src}; # skip bad lines for now
667
668                 my $page=pagename($items{src}[0]);
669                 if (! $config{rebuild}) {
670                         $pagesources{$page}=$items{src}[0];
671                         $oldpagemtime{$page}=$items{mtime}[0];
672                         $oldlinks{$page}=[@{$items{link}}];
673                         $links{$page}=[@{$items{link}}];
674                         $depends{$page}=$items{depends}[0] if exists $items{depends};
675                         $renderedfiles{$page}=[@{$items{dest}}];
676                         $oldrenderedfiles{$page}=[@{$items{dest}}];
677                         $pagecase{lc $page}=$page;
678                 }
679                 $pagectime{$page}=$items{ctime}[0];
680         }
681         close IN;
682 } #}}}
683
684 sub saveindex () { #{{{
685         run_hooks(savestate => sub { shift->() });
686
687         if (! -d $config{wikistatedir}) {
688                 mkdir($config{wikistatedir});
689         }
690         my $newfile="$config{wikistatedir}/index.new";
691         my $cleanup = sub { unlink($newfile) };
692         open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
693         foreach my $page (keys %oldpagemtime) {
694                 next unless $oldpagemtime{$page};
695                 my $line="mtime=$oldpagemtime{$page} ".
696                         "ctime=$pagectime{$page} ".
697                         "src=$pagesources{$page}";
698                 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
699                 my %count;
700                 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
701                 if (exists $depends{$page}) {
702                         $line.=" depends=".encode_entities($depends{$page}, " \t\n");
703                 }
704                 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
705         }
706         close OUT || error("failed saving to $newfile: $!", $cleanup);
707         rename($newfile, "$config{wikistatedir}/index") ||
708                 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
709 } #}}}
710
711 sub template_file ($) { #{{{
712         my $template=shift;
713
714         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
715                 return "$dir/$template" if -e "$dir/$template";
716         }
717         return undef;
718 } #}}}
719
720 sub template_params (@) { #{{{
721         my $filename=template_file(shift);
722
723         if (! defined $filename) {
724                 return if wantarray;
725                 return "";
726         }
727
728         require HTML::Template;
729         my @ret=(
730                 filter => sub {
731                         my $text_ref = shift;
732                         $$text_ref=&Encode::decode_utf8($$text_ref);
733                 },
734                 filename => $filename,
735                 loop_context_vars => 1,
736                 die_on_bad_params => 0,
737                 @_
738         );
739         return wantarray ? @ret : {@ret};
740 } #}}}
741
742 sub template ($;@) { #{{{
743         HTML::Template->new(template_params(@_));
744 } #}}}
745
746 sub misctemplate ($$;@) { #{{{
747         my $title=shift;
748         my $pagebody=shift;
749         
750         my $template=template("misc.tmpl");
751         $template->param(
752                 title => $title,
753                 indexlink => indexlink(),
754                 wikiname => $config{wikiname},
755                 pagebody => $pagebody,
756                 baseurl => baseurl(),
757                 @_,
758         );
759         run_hooks(pagetemplate => sub {
760                 shift->(page => "", destpage => "", template => $template);
761         });
762         return $template->output;
763 }#}}}
764
765 sub hook (@) { # {{{
766         my %param=@_;
767         
768         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
769                 error "hook requires type, call, and id parameters";
770         }
771
772         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
773         
774         $hooks{$param{type}}{$param{id}}=\%param;
775 } # }}}
776
777 sub run_hooks ($$) { # {{{
778         # Calls the given sub for each hook of the given type,
779         # passing it the hook function to call.
780         my $type=shift;
781         my $sub=shift;
782
783         if (exists $hooks{$type}) {
784                 my @deferred;
785                 foreach my $id (keys %{$hooks{$type}}) {
786                         if ($hooks{$type}{$id}{last}) {
787                                 push @deferred, $id;
788                                 next;
789                         }
790                         $sub->($hooks{$type}{$id}{call});
791                 }
792                 foreach my $id (@deferred) {
793                         $sub->($hooks{$type}{$id}{call});
794                 }
795         }
796 } #}}}
797
798 sub globlist_to_pagespec ($) { #{{{
799         my @globlist=split(' ', shift);
800
801         my (@spec, @skip);
802         foreach my $glob (@globlist) {
803                 if ($glob=~/^!(.*)/) {
804                         push @skip, $glob;
805                 }
806                 else {
807                         push @spec, $glob;
808                 }
809         }
810
811         my $spec=join(" or ", @spec);
812         if (@skip) {
813                 my $skip=join(" and ", @skip);
814                 if (length $spec) {
815                         $spec="$skip and ($spec)";
816                 }
817                 else {
818                         $spec=$skip;
819                 }
820         }
821         return $spec;
822 } #}}}
823
824 sub is_globlist ($) { #{{{
825         my $s=shift;
826         $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
827 } #}}}
828
829 sub safequote ($) { #{{{
830         my $s=shift;
831         $s=~s/[{}]//g;
832         return "q{$s}";
833 } #}}}
834
835 sub add_depends ($$) { #{{{
836         my $page=shift;
837         my $pagespec=shift;
838         
839         if (! exists $depends{$page}) {
840                 $depends{$page}=$pagespec;
841         }
842         else {
843                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
844         }
845 } # }}}
846
847 sub file_pruned ($$) { #{{{
848         require File::Spec;
849         my $file=File::Spec->canonpath(shift);
850         my $base=File::Spec->canonpath(shift);
851         $file=~s#^\Q$base\E/*##;
852
853         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
854         $file =~ m/$regexp/;
855 } #}}}
856
857 sub gettext { #{{{
858         # Only use gettext in the rare cases it's needed.
859         if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
860                 if (! $gettext_obj) {
861                         $gettext_obj=eval q{
862                                 use Locale::gettext q{textdomain};
863                                 Locale::gettext->domain('ikiwiki')
864                         };
865                         if ($@) {
866                                 print STDERR "$@";
867                                 $gettext_obj=undef;
868                                 return shift;
869                         }
870                 }
871                 return $gettext_obj->get(shift);
872         }
873         else {
874                 return shift;
875         }
876 } #}}}
877
878 sub pagespec_merge ($$) { #{{{
879         my $a=shift;
880         my $b=shift;
881
882         return $a if $a eq $b;
883
884         # Support for old-style GlobLists.
885         if (is_globlist($a)) {
886                 $a=globlist_to_pagespec($a);
887         }
888         if (is_globlist($b)) {
889                 $b=globlist_to_pagespec($b);
890         }
891
892         return "($a) or ($b)";
893 } #}}}
894
895 sub pagespec_translate ($) { #{{{
896         # This assumes that $page is in scope in the function
897         # that evalulates the translated pagespec code.
898         my $spec=shift;
899
900         # Support for old-style GlobLists.
901         if (is_globlist($spec)) {
902                 $spec=globlist_to_pagespec($spec);
903         }
904
905         # Convert spec to perl code.
906         my $code="";
907         while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
908                 my $word=$1;
909                 if (lc $word eq "and") {
910                         $code.=" &&";
911                 }
912                 elsif (lc $word eq "or") {
913                         $code.=" ||";
914                 }
915                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
916                         $code.=" ".$word;
917                 }
918                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
919                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
920                                 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
921                         }
922                         else {
923                                 $code.=" 0";
924                         }
925                 }
926                 else {
927                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
928                 }
929         }
930
931         return $code;
932 } #}}}
933
934 sub pagespec_match ($$;$) { #{{{
935         my $page=shift;
936         my $spec=shift;
937         my $from=shift;
938
939         return eval pagespec_translate($spec);
940 } #}}}
941
942 package IkiWiki::PageSpec;
943
944 sub match_glob ($$$) { #{{{
945         my $page=shift;
946         my $glob=shift;
947         my $from=shift;
948         if (! defined $from){
949                 $from = "";
950         }
951
952         # relative matching
953         if ($glob =~ m!^\./!) {
954                 $from=~s!/?[^/]+$!!;
955                 $glob=~s!^\./!!;
956                 $glob="$from/$glob" if length $from;
957         }
958
959         # turn glob into safe regexp
960         $glob=quotemeta($glob);
961         $glob=~s/\\\*/.*/g;
962         $glob=~s/\\\?/./g;
963
964         return $page=~/^$glob$/i;
965 } #}}}
966
967 sub match_link ($$) { #{{{
968         my $page=shift;
969         my $link=lc(shift);
970
971         my $links = $IkiWiki::links{$page} or return undef;
972         foreach my $p (@$links) {
973                 return 1 if lc $p eq $link;
974         }
975         return 0;
976 } #}}}
977
978 sub match_backlink ($$) { #{{{
979         match_link(pop, pop);
980 } #}}}
981
982 sub match_created_before ($$) { #{{{
983         my $page=shift;
984         my $testpage=shift;
985
986         if (exists $IkiWiki::pagectime{$testpage}) {
987                 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
988         }
989         else {
990                 return 0;
991         }
992 } #}}}
993
994 sub match_created_after ($$) { #{{{
995         my $page=shift;
996         my $testpage=shift;
997
998         if (exists $IkiWiki::pagectime{$testpage}) {
999                 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1000         }
1001         else {
1002                 return 0;
1003         }
1004 } #}}}
1005
1006 sub match_creation_day ($$) { #{{{
1007         return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1008 } #}}}
1009
1010 sub match_creation_month ($$) { #{{{
1011         return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1012 } #}}}
1013
1014 sub match_creation_year ($$) { #{{{
1015         return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);
1016 } #}}}
1017
1018 1