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