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