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