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