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