]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
* Add titlepage template for inline plugin.
[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                 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
297         }
298         close OUT || error("failed saving $newfile: $!", $cleanup);
299         rename($newfile, "$destdir/$file") || 
300                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
301 } #}}}
302
303 my %cleared;
304 sub will_render ($$;$) { #{{{
305         my $page=shift;
306         my $dest=shift;
307         my $clear=shift;
308
309         # Important security check.
310         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
311             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
312                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
313         }
314
315         if (! $clear || $cleared{$page}) {
316                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
317         }
318         else {
319                 $renderedfiles{$page}=[$dest];
320                 $cleared{$page}=1;
321         }
322 } #}}}
323
324 sub bestlink ($$) { #{{{
325         my $page=shift;
326         my $link=shift;
327         
328         my $cwd=$page;
329         if ($link=~s/^\/+//) {
330                 # absolute links
331                 $cwd="";
332         }
333
334         do {
335                 my $l=$cwd;
336                 $l.="/" if length $l;
337                 $l.=$link;
338
339                 if (exists $links{$l}) {
340                         return $l;
341                 }
342                 elsif (exists $pagecase{lc $l}) {
343                         return $pagecase{lc $l};
344                 }
345         } while $cwd=~s!/?[^/]+$!!;
346
347         if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
348                 return "$config{userdir}/".lc($link);
349         }
350
351         #print STDERR "warning: page $page, broken link: $link\n";
352         return "";
353 } #}}}
354
355 sub isinlinableimage ($) { #{{{
356         my $file=shift;
357         
358         $file=~/\.(png|gif|jpg|jpeg)$/i;
359 } #}}}
360
361 sub pagetitle ($;$) { #{{{
362         my $page=shift;
363         my $unescaped=shift;
364
365         if ($unescaped) {
366                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
367         }
368         else {
369                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
370         }
371
372         return $page;
373 } #}}}
374
375 sub titlepage ($) { #{{{
376         my $title=shift;
377         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
378         return $title;
379 } #}}}
380
381 sub cgiurl (@) { #{{{
382         my %params=@_;
383
384         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
385 } #}}}
386
387 sub baseurl (;$) { #{{{
388         my $page=shift;
389
390         return "$config{url}/" if ! defined $page;
391         
392         $page=~s/[^\/]+$//;
393         $page=~s/[^\/]+\//..\//g;
394         return $page;
395 } #}}}
396
397 sub abs2rel ($$) { #{{{
398         # Work around very innefficient behavior in File::Spec if abs2rel
399         # is passed two relative paths. It's much faster if paths are
400         # absolute! (Debian bug #376658; fixed in debian unstable now)
401         my $path="/".shift;
402         my $base="/".shift;
403
404         require File::Spec;
405         my $ret=File::Spec->abs2rel($path, $base);
406         $ret=~s/^// if defined $ret;
407         return $ret;
408 } #}}}
409
410 sub displaytime ($) { #{{{
411         my $time=shift;
412
413         eval q{use POSIX};
414         error($@) if $@;
415         # strftime doesn't know about encodings, so make sure
416         # its output is properly treated as utf8
417         return decode_utf8(POSIX::strftime(
418                         $config{timeformat}, localtime($time)));
419 } #}}}
420
421 sub htmllink ($$$;@) { #{{{
422         my $lpage=shift; # the page doing the linking
423         my $page=shift; # the page that will contain the link (different for inline)
424         my $link=shift;
425         my %opts=@_;
426
427         my $bestlink;
428         if (! $opts{forcesubpage}) {
429                 $bestlink=bestlink($lpage, $link);
430         }
431         else {
432                 $bestlink="$lpage/".lc($link);
433         }
434
435         my $linktext;
436         if (defined $opts{linktext}) {
437                 $linktext=$opts{linktext};
438         }
439         else {
440                 $linktext=pagetitle(basename($link));
441         }
442         
443         return "<span class=\"selflink\">$linktext</span>"
444                 if length $bestlink && $page eq $bestlink;
445         
446         if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
447                 $bestlink=htmlpage($bestlink);
448         }
449         if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
450                 return $linktext unless length $config{cgiurl};
451                 return "<span><a href=\"".
452                         cgiurl(do => "create", page => lc($link), from => $page).
453                         "\">?</a>$linktext</span>"
454         }
455         
456         $bestlink=abs2rel($bestlink, dirname($page));
457         
458         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
459                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
460         }
461
462         if (defined $opts{anchor}) {
463                 $bestlink.="#".$opts{anchor};
464         }
465
466         return "<a href=\"$bestlink\">$linktext</a>";
467 } #}}}
468
469 sub htmlize ($$$) { #{{{
470         my $page=shift;
471         my $type=shift;
472         my $content=shift;
473
474         if (exists $hooks{htmlize}{$type}) {
475                 $content=$hooks{htmlize}{$type}{call}->(
476                         page => $page,
477                         content => $content,
478                 );
479         }
480         else {
481                 error("htmlization of $type not supported");
482         }
483
484         run_hooks(sanitize => sub {
485                 $content=shift->(
486                         page => $page,
487                         content => $content,
488                 );
489         });
490
491         return $content;
492 } #}}}
493
494 sub linkify ($$$) { #{{{
495         my $lpage=shift; # the page containing the links
496         my $page=shift; # the page the link will end up on (different for inline)
497         my $content=shift;
498
499         $content =~ s{(\\?)$config{wiki_link_regexp}}{
500                 defined $2
501                         ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), anchor => $4, linktext => pagetitle($2)))
502                         : ( $1 ? "[[$3]]"    : htmllink($lpage, $page, titlepage($3), anchor => $4))
503         }eg;
504         
505         return $content;
506 } #}}}
507
508 my %preprocessing;
509 sub preprocess ($$$;$) { #{{{
510         my $page=shift; # the page the data comes from
511         my $destpage=shift; # the page the data will appear in (different for inline)
512         my $content=shift;
513         my $scan=shift;
514
515         my $handle=sub {
516                 my $escape=shift;
517                 my $command=shift;
518                 my $params=shift;
519                 if (length $escape) {
520                         return "[[$command $params]]";
521                 }
522                 elsif (exists $hooks{preprocess}{$command}) {
523                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
524                         # Note: preserve order of params, some plugins may
525                         # consider it significant.
526                         my @params;
527                         while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
528                                 my $key=$1;
529                                 my $val;
530                                 if (defined $2) {
531                                         $val=$2;
532                                         $val=~s/\r\n/\n/mg;
533                                         $val=~s/^\n+//g;
534                                         $val=~s/\n+$//g;
535                                 }
536                                 elsif (defined $3) {
537                                         $val=$3;
538                                 }
539                                 elsif (defined $4) {
540                                         $val=$4;
541                                 }
542
543                                 if (defined $key) {
544                                         push @params, $key, $val;
545                                 }
546                                 else {
547                                         push @params, $val, '';
548                                 }
549                         }
550                         if ($preprocessing{$page}++ > 3) {
551                                 # Avoid loops of preprocessed pages preprocessing
552                                 # other pages that preprocess them, etc.
553                                 #translators: The first parameter is a
554                                 #translators: preprocessor directive name,
555                                 #translators: the second a page name, the
556                                 #translators: third a number.
557                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
558                                         $command, $page, $preprocessing{$page}).
559                                 "]]";
560                         }
561                         my $ret=$hooks{preprocess}{$command}{call}->(
562                                 @params,
563                                 page => $page,
564                                 destpage => $destpage,
565                         );
566                         $preprocessing{$page}--;
567                         return $ret;
568                 }
569                 else {
570                         return "[[$command $params]]";
571                 }
572         };
573         
574         $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
575         return $content;
576 } #}}}
577
578 sub filter ($$) { #{{{
579         my $page=shift;
580         my $content=shift;
581
582         run_hooks(filter => sub {
583                 $content=shift->(page => $page, content => $content);
584         });
585
586         return $content;
587 } #}}}
588
589 sub indexlink () { #{{{
590         return "<a href=\"$config{url}\">$config{wikiname}</a>";
591 } #}}}
592
593 sub lockwiki () { #{{{
594         # Take an exclusive lock on the wiki to prevent multiple concurrent
595         # run issues. The lock will be dropped on program exit.
596         if (! -d $config{wikistatedir}) {
597                 mkdir($config{wikistatedir});
598         }
599         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
600                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
601         if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
602                 debug("wiki seems to be locked, waiting for lock");
603                 my $wait=600; # arbitrary, but don't hang forever to 
604                               # prevent process pileup
605                 for (1..$wait) {
606                         return if flock(WIKILOCK, 2 | 4);
607                         sleep 1;
608                 }
609                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
610         }
611 } #}}}
612
613 sub unlockwiki () { #{{{
614         close WIKILOCK;
615 } #}}}
616
617 sub commit_hook_enabled () { #{{{
618         open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
619                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
620         if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
621                 close COMMITLOCK;
622                 return 0;
623         }
624         close COMMITLOCK;
625         return 1;
626 } #}}}
627
628 sub disable_commit_hook () { #{{{
629         open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
630                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
631         if (! flock(COMMITLOCK, 2)) { # LOCK_EX
632                 error("failed to get commit lock");
633         }
634 } #}}}
635
636 sub enable_commit_hook () { #{{{
637         close COMMITLOCK;
638 } #}}}
639
640 sub loadindex () { #{{{
641         open (IN, "$config{wikistatedir}/index") || return;
642         while (<IN>) {
643                 $_=possibly_foolish_untaint($_);
644                 chomp;
645                 my %items;
646                 $items{link}=[];
647                 $items{dest}=[];
648                 foreach my $i (split(/ /, $_)) {
649                         my ($item, $val)=split(/=/, $i, 2);
650                         push @{$items{$item}}, decode_entities($val);
651                 }
652
653                 next unless exists $items{src}; # skip bad lines for now
654
655                 my $page=pagename($items{src}[0]);
656                 if (! $config{rebuild}) {
657                         $pagesources{$page}=$items{src}[0];
658                         $oldpagemtime{$page}=$items{mtime}[0];
659                         $oldlinks{$page}=[@{$items{link}}];
660                         $links{$page}=[@{$items{link}}];
661                         $depends{$page}=$items{depends}[0] if exists $items{depends};
662                         $renderedfiles{$page}=[@{$items{dest}}];
663                         $oldrenderedfiles{$page}=[@{$items{dest}}];
664                         $pagecase{lc $page}=$page;
665                 }
666                 $pagectime{$page}=$items{ctime}[0];
667         }
668         close IN;
669 } #}}}
670
671 sub saveindex () { #{{{
672         run_hooks(savestate => sub { shift->() });
673
674         if (! -d $config{wikistatedir}) {
675                 mkdir($config{wikistatedir});
676         }
677         my $newfile="$config{wikistatedir}/index.new";
678         my $cleanup = sub { unlink($newfile) };
679         open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
680         foreach my $page (keys %oldpagemtime) {
681                 next unless $oldpagemtime{$page};
682                 my $line="mtime=$oldpagemtime{$page} ".
683                         "ctime=$pagectime{$page} ".
684                         "src=$pagesources{$page}";
685                 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
686                 my %count;
687                 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
688                 if (exists $depends{$page}) {
689                         $line.=" depends=".encode_entities($depends{$page}, " \t\n");
690                 }
691                 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
692         }
693         close OUT || error("failed saving to $newfile: $!", $cleanup);
694         rename($newfile, "$config{wikistatedir}/index") ||
695                 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
696 } #}}}
697
698 sub template_file ($) { #{{{
699         my $template=shift;
700
701         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
702                 return "$dir/$template" if -e "$dir/$template";
703         }
704         return undef;
705 } #}}}
706
707 sub template_params (@) { #{{{
708         my $filename=template_file(shift);
709
710         if (! defined $filename) {
711                 return if wantarray;
712                 return "";
713         }
714
715         require HTML::Template;
716         my @ret=(
717                 filter => sub {
718                         my $text_ref = shift;
719                         $$text_ref=&Encode::decode_utf8($$text_ref);
720                 },
721                 filename => $filename,
722                 loop_context_vars => 1,
723                 die_on_bad_params => 0,
724                 @_
725         );
726         return wantarray ? @ret : {@ret};
727 } #}}}
728
729 sub template ($;@) { #{{{
730         HTML::Template->new(template_params(@_));
731 } #}}}
732
733 sub misctemplate ($$;@) { #{{{
734         my $title=shift;
735         my $pagebody=shift;
736         
737         my $template=template("misc.tmpl");
738         $template->param(
739                 title => $title,
740                 indexlink => indexlink(),
741                 wikiname => $config{wikiname},
742                 pagebody => $pagebody,
743                 baseurl => baseurl(),
744                 @_,
745         );
746         run_hooks(pagetemplate => sub {
747                 shift->(page => "", destpage => "", template => $template);
748         });
749         return $template->output;
750 }#}}}
751
752 sub hook (@) { # {{{
753         my %param=@_;
754         
755         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
756                 error "hook requires type, call, and id parameters";
757         }
758
759         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
760         
761         $hooks{$param{type}}{$param{id}}=\%param;
762 } # }}}
763
764 sub run_hooks ($$) { # {{{
765         # Calls the given sub for each hook of the given type,
766         # passing it the hook function to call.
767         my $type=shift;
768         my $sub=shift;
769
770         if (exists $hooks{$type}) {
771                 my @deferred;
772                 foreach my $id (keys %{$hooks{$type}}) {
773                         if ($hooks{$type}{$id}{last}) {
774                                 push @deferred, $id;
775                                 next;
776                         }
777                         $sub->($hooks{$type}{$id}{call});
778                 }
779                 foreach my $id (@deferred) {
780                         $sub->($hooks{$type}{$id}{call});
781                 }
782         }
783 } #}}}
784
785 sub globlist_to_pagespec ($) { #{{{
786         my @globlist=split(' ', shift);
787
788         my (@spec, @skip);
789         foreach my $glob (@globlist) {
790                 if ($glob=~/^!(.*)/) {
791                         push @skip, $glob;
792                 }
793                 else {
794                         push @spec, $glob;
795                 }
796         }
797
798         my $spec=join(" or ", @spec);
799         if (@skip) {
800                 my $skip=join(" and ", @skip);
801                 if (length $spec) {
802                         $spec="$skip and ($spec)";
803                 }
804                 else {
805                         $spec=$skip;
806                 }
807         }
808         return $spec;
809 } #}}}
810
811 sub is_globlist ($) { #{{{
812         my $s=shift;
813         $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
814 } #}}}
815
816 sub safequote ($) { #{{{
817         my $s=shift;
818         $s=~s/[{}]//g;
819         return "q{$s}";
820 } #}}}
821
822 sub add_depends ($$) { #{{{
823         my $page=shift;
824         my $pagespec=shift;
825         
826         if (! exists $depends{$page}) {
827                 $depends{$page}=$pagespec;
828         }
829         else {
830                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
831         }
832 } # }}}
833
834 sub file_pruned ($$) { #{{{
835         require File::Spec;
836         my $file=File::Spec->canonpath(shift);
837         my $base=File::Spec->canonpath(shift);
838         $file=~s#^\Q$base\E/*##;
839
840         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
841         $file =~ m/$regexp/;
842 } #}}}
843
844 sub gettext { #{{{
845         # Only use gettext in the rare cases it's needed.
846         if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
847                 if (! $gettext_obj) {
848                         $gettext_obj=eval q{
849                                 use Locale::gettext q{textdomain};
850                                 Locale::gettext->domain('ikiwiki')
851                         };
852                         if ($@) {
853                                 print STDERR "$@";
854                                 $gettext_obj=undef;
855                                 return shift;
856                         }
857                 }
858                 return $gettext_obj->get(shift);
859         }
860         else {
861                 return shift;
862         }
863 } #}}}
864
865 sub pagespec_merge ($$) { #{{{
866         my $a=shift;
867         my $b=shift;
868
869         return $a if $a eq $b;
870
871         # Support for old-style GlobLists.
872         if (is_globlist($a)) {
873                 $a=globlist_to_pagespec($a);
874         }
875         if (is_globlist($b)) {
876                 $b=globlist_to_pagespec($b);
877         }
878
879         return "($a) or ($b)";
880 } #}}}
881
882 sub pagespec_translate ($) { #{{{
883         # This assumes that $page is in scope in the function
884         # that evalulates the translated pagespec code.
885         my $spec=shift;
886
887         # Support for old-style GlobLists.
888         if (is_globlist($spec)) {
889                 $spec=globlist_to_pagespec($spec);
890         }
891
892         # Convert spec to perl code.
893         my $code="";
894         while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
895                 my $word=$1;
896                 if (lc $word eq "and") {
897                         $code.=" &&";
898                 }
899                 elsif (lc $word eq "or") {
900                         $code.=" ||";
901                 }
902                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
903                         $code.=" ".$word;
904                 }
905                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
906                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
907                                 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
908                         }
909                         else {
910                                 $code.=" 0";
911                         }
912                 }
913                 else {
914                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
915                 }
916         }
917
918         return $code;
919 } #}}}
920
921 sub pagespec_match ($$;$) { #{{{
922         my $page=shift;
923         my $spec=shift;
924         my $from=shift;
925
926         return eval pagespec_translate($spec);
927 } #}}}
928
929 package IkiWiki::PageSpec;
930
931 sub match_glob ($$$) { #{{{
932         my $page=shift;
933         my $glob=shift;
934         my $from=shift;
935         if (! defined $from){
936                 $from = "";
937         }
938
939         # relative matching
940         if ($glob =~ m!^\./!) {
941                 $from=~s!/?[^/]+$!!;
942                 $glob=~s!^\./!!;
943                 $glob="$from/$glob" if length $from;
944         }
945
946         # turn glob into safe regexp
947         $glob=quotemeta($glob);
948         $glob=~s/\\\*/.*/g;
949         $glob=~s/\\\?/./g;
950
951         return $page=~/^$glob$/i;
952 } #}}}
953
954 sub match_link ($$) { #{{{
955         my $page=shift;
956         my $link=lc(shift);
957
958         my $links = $IkiWiki::links{$page} or return undef;
959         foreach my $p (@$links) {
960                 return 1 if lc $p eq $link;
961         }
962         return 0;
963 } #}}}
964
965 sub match_backlink ($$) { #{{{
966         match_link(pop, pop);
967 } #}}}
968
969 sub match_created_before ($$) { #{{{
970         my $page=shift;
971         my $testpage=shift;
972
973         if (exists $IkiWiki::pagectime{$testpage}) {
974                 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
975         }
976         else {
977                 return 0;
978         }
979 } #}}}
980
981 sub match_created_after ($$) { #{{{
982         my $page=shift;
983         my $testpage=shift;
984
985         if (exists $IkiWiki::pagectime{$testpage}) {
986                 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
987         }
988         else {
989                 return 0;
990         }
991 } #}}}
992
993 sub match_creation_day ($$) { #{{{
994         return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
995 } #}}}
996
997 sub match_creation_month ($$) { #{{{
998         return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
999 } #}}}
1000
1001 sub match_creation_year ($$) { #{{{
1002         return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);
1003 } #}}}
1004
1005 1