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