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