* Initial work on internationalization of the program code. po/ikiwiki.pot
[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 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         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(gettext("Must specify url to wiki with --url when using --cgi"));
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(gettext("Error"),
143                         "<p>".gettext("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         if ($link=~s/^\/+//) {
303                 # absolute links
304                 $cwd="";
305         }
306
307         do {
308                 my $l=$cwd;
309                 $l.="/" if length $l;
310                 $l.=$link;
311
312                 if (exists $links{$l}) {
313                         return $l;
314                 }
315                 elsif (exists $pagecase{lc $l}) {
316                         return $pagecase{lc $l};
317                 }
318         } while $cwd=~s!/?[^/]+$!!;
319
320         #print STDERR "warning: page $page, broken link: $link\n";
321         return "";
322 } #}}}
323
324 sub isinlinableimage ($) { #{{{
325         my $file=shift;
326         
327         $file=~/\.(png|gif|jpg|jpeg)$/i;
328 } #}}}
329
330 sub pagetitle ($;$) { #{{{
331         my $page=shift;
332         my $unescaped=shift;
333
334         if ($unescaped) {
335                 $page=~s/__(\d+)__/chr($1)/eg;
336         }
337         else {
338                 $page=~s/__(\d+)__/&#$1;/g;
339         }
340         $page=~y/_/ /;
341
342         return $page;
343 } #}}}
344
345 sub titlepage ($) { #{{{
346         my $title=shift;
347         $title=~y/ /_/;
348         $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
349         return $title;
350 } #}}}
351
352 sub cgiurl (@) { #{{{
353         my %params=@_;
354
355         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
356 } #}}}
357
358 sub baseurl (;$) { #{{{
359         my $page=shift;
360
361         return "$config{url}/" if ! defined $page;
362         
363         $page=~s/[^\/]+$//;
364         $page=~s/[^\/]+\//..\//g;
365         return $page;
366 } #}}}
367
368 sub abs2rel ($$) { #{{{
369         # Work around very innefficient behavior in File::Spec if abs2rel
370         # is passed two relative paths. It's much faster if paths are
371         # absolute! (Debian bug #376658; fixed in debian unstable now)
372         my $path="/".shift;
373         my $base="/".shift;
374
375         require File::Spec;
376         my $ret=File::Spec->abs2rel($path, $base);
377         $ret=~s/^// if defined $ret;
378         return $ret;
379 } #}}}
380
381 sub displaytime ($) { #{{{
382         my $time=shift;
383
384         eval q{use POSIX};
385         error($@) if $@;
386         # strftime doesn't know about encodings, so make sure
387         # its output is properly treated as utf8
388         return decode_utf8(POSIX::strftime(
389                         $config{timeformat}, localtime($time)));
390 } #}}}
391
392 sub htmllink ($$$;$$$) { #{{{
393         my $lpage=shift; # the page doing the linking
394         my $page=shift; # the page that will contain the link (different for inline)
395         my $link=shift;
396         my $noimageinline=shift; # don't turn links into inline html images
397         my $forcesubpage=shift; # force a link to a subpage
398         my $linktext=shift; # set to force the link text to something
399
400         my $bestlink;
401         if (! $forcesubpage) {
402                 $bestlink=bestlink($lpage, $link);
403         }
404         else {
405                 $bestlink="$lpage/".lc($link);
406         }
407
408         $linktext=pagetitle(basename($link)) unless defined $linktext;
409         
410         return "<span class=\"selflink\">$linktext</span>"
411                 if length $bestlink && $page eq $bestlink;
412         
413         if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
414                 $bestlink=htmlpage($bestlink);
415         }
416         if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
417                 return $linktext unless length $config{cgiurl};
418                 return "<span><a href=\"".
419                         cgiurl(do => "create", page => lc($link), from => $page).
420                         "\">?</a>$linktext</span>"
421         }
422         
423         $bestlink=abs2rel($bestlink, dirname($page));
424         
425         if (! $noimageinline && isinlinableimage($bestlink)) {
426                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
427         }
428         return "<a href=\"$bestlink\">$linktext</a>";
429 } #}}}
430
431 sub htmlize ($$$) { #{{{
432         my $page=shift;
433         my $type=shift;
434         my $content=shift;
435
436         if (exists $hooks{htmlize}{$type}) {
437                 $content=$hooks{htmlize}{$type}{call}->(
438                         page => $page,
439                         content => $content,
440                 );
441         }
442         else {
443                 error("htmlization of $type not supported");
444         }
445
446         run_hooks(sanitize => sub {
447                 $content=shift->(
448                         page => $page,
449                         content => $content,
450                 );
451         });
452
453         return $content;
454 } #}}}
455
456 sub linkify ($$$) { #{{{
457         my $lpage=shift; # the page containing the links
458         my $page=shift; # the page the link will end up on (different for inline)
459         my $content=shift;
460
461         $content =~ s{(\\?)$config{wiki_link_regexp}}{
462                 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
463                    : ( $1 ? "[[$3]]" :    htmllink($lpage, $page, titlepage($3)))
464         }eg;
465         
466         return $content;
467 } #}}}
468
469 my %preprocessing;
470 sub preprocess ($$$;$) { #{{{
471         my $page=shift; # the page the data comes from
472         my $destpage=shift; # the page the data will appear in (different for inline)
473         my $content=shift;
474         my $scan=shift;
475
476         my $handle=sub {
477                 my $escape=shift;
478                 my $command=shift;
479                 my $params=shift;
480                 if (length $escape) {
481                         return "[[$command $params]]";
482                 }
483                 elsif (exists $hooks{preprocess}{$command}) {
484                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
485                         # Note: preserve order of params, some plugins may
486                         # consider it significant.
487                         my @params;
488                         while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
489                                 my $key=$1;
490                                 my $val;
491                                 if (defined $2) {
492                                         $val=$2;
493                                         $val=~s/\r\n/\n/mg;
494                                         $val=~s/^\n+//g;
495                                         $val=~s/\n+$//g;
496                                 }
497                                 elsif (defined $3) {
498                                         $val=$3;
499                                 }
500                                 elsif (defined $4) {
501                                         $val=$4;
502                                 }
503
504                                 if (defined $key) {
505                                         push @params, $key, $val;
506                                 }
507                                 else {
508                                         push @params, $val, '';
509                                 }
510                         }
511                         if ($preprocessing{$page}++ > 3) {
512                                 # Avoid loops of preprocessed pages preprocessing
513                                 # other pages that preprocess them, etc.
514                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
515                                         $command, $page, $preprocessing{$page}).
516                                 "]]";
517                         }
518                         my $ret=$hooks{preprocess}{$command}{call}->(
519                                 @params,
520                                 page => $page,
521                                 destpage => $destpage,
522                         );
523                         $preprocessing{$page}--;
524                         return $ret;
525                 }
526                 else {
527                         return "[[$command $params]]";
528                 }
529         };
530         
531         $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
532         return $content;
533 } #}}}
534
535 sub filter ($$) { #{{{
536         my $page=shift;
537         my $content=shift;
538
539         run_hooks(filter => sub {
540                 $content=shift->(page => $page, content => $content);
541         });
542
543         return $content;
544 } #}}}
545
546 sub indexlink () { #{{{
547         return "<a href=\"$config{url}\">$config{wikiname}</a>";
548 } #}}}
549
550 sub lockwiki () { #{{{
551         # Take an exclusive lock on the wiki to prevent multiple concurrent
552         # run issues. The lock will be dropped on program exit.
553         if (! -d $config{wikistatedir}) {
554                 mkdir($config{wikistatedir});
555         }
556         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
557                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
558         if (! flock(WIKILOCK, 2 | 4)) {
559                 debug("wiki seems to be locked, waiting for lock");
560                 my $wait=600; # arbitrary, but don't hang forever to 
561                               # prevent process pileup
562                 for (1..600) {
563                         return if flock(WIKILOCK, 2 | 4);
564                         sleep 1;
565                 }
566                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
567         }
568 } #}}}
569
570 sub unlockwiki () { #{{{
571         close WIKILOCK;
572 } #}}}
573
574 sub loadindex () { #{{{
575         open (IN, "$config{wikistatedir}/index") || return;
576         while (<IN>) {
577                 $_=possibly_foolish_untaint($_);
578                 chomp;
579                 my %items;
580                 $items{link}=[];
581                 $items{dest}=[];
582                 foreach my $i (split(/ /, $_)) {
583                         my ($item, $val)=split(/=/, $i, 2);
584                         push @{$items{$item}}, decode_entities($val);
585                 }
586
587                 next unless exists $items{src}; # skip bad lines for now
588
589                 my $page=pagename($items{src}[0]);
590                 if (! $config{rebuild}) {
591                         $pagesources{$page}=$items{src}[0];
592                         $oldpagemtime{$page}=$items{mtime}[0];
593                         $oldlinks{$page}=[@{$items{link}}];
594                         $links{$page}=[@{$items{link}}];
595                         $depends{$page}=$items{depends}[0] if exists $items{depends};
596                         $renderedfiles{$page}=[@{$items{dest}}];
597                         $oldrenderedfiles{$page}=[@{$items{dest}}];
598                         $pagecase{lc $page}=$page;
599                 }
600                 $pagectime{$page}=$items{ctime}[0];
601         }
602         close IN;
603 } #}}}
604
605 sub saveindex () { #{{{
606         run_hooks(savestate => sub { shift->() });
607
608         if (! -d $config{wikistatedir}) {
609                 mkdir($config{wikistatedir});
610         }
611         open (OUT, ">$config{wikistatedir}/index") || 
612                 error("cannot write to $config{wikistatedir}/index: $!");
613         foreach my $page (keys %oldpagemtime) {
614                 next unless $oldpagemtime{$page};
615                 my $line="mtime=$oldpagemtime{$page} ".
616                         "ctime=$pagectime{$page} ".
617                         "src=$pagesources{$page}";
618                 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
619                 my %count;
620                 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
621                 if (exists $depends{$page}) {
622                         $line.=" depends=".encode_entities($depends{$page}, " \t\n");
623                 }
624                 print OUT $line."\n";
625         }
626         close OUT;
627 } #}}}
628
629 sub template_params (@) { #{{{
630         my $filename=shift;
631         
632         require HTML::Template;
633         return filter => sub {
634                         my $text_ref = shift;
635                         $$text_ref=&Encode::decode_utf8($$text_ref);
636                 },
637                 filename => "$config{templatedir}/$filename",
638                 loop_context_vars => 1,
639                 die_on_bad_params => 0,
640                 @_;
641 } #}}}
642
643 sub template ($;@) { #{{{
644         HTML::Template->new(template_params(@_));
645 } #}}}
646
647 sub misctemplate ($$;@) { #{{{
648         my $title=shift;
649         my $pagebody=shift;
650         
651         my $template=template("misc.tmpl");
652         $template->param(
653                 title => $title,
654                 indexlink => indexlink(),
655                 wikiname => $config{wikiname},
656                 pagebody => $pagebody,
657                 baseurl => baseurl(),
658                 @_,
659         );
660         run_hooks(pagetemplate => sub {
661                 shift->(page => "", destpage => "", template => $template);
662         });
663         return $template->output;
664 }#}}}
665
666 sub hook (@) { # {{{
667         my %param=@_;
668         
669         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
670                 error "hook requires type, call, and id parameters";
671         }
672
673         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
674         
675         $hooks{$param{type}}{$param{id}}=\%param;
676 } # }}}
677
678 sub run_hooks ($$) { # {{{
679         # Calls the given sub for each hook of the given type,
680         # passing it the hook function to call.
681         my $type=shift;
682         my $sub=shift;
683
684         if (exists $hooks{$type}) {
685                 my @deferred;
686                 foreach my $id (keys %{$hooks{$type}}) {
687                         if ($hooks{$type}{$id}{last}) {
688                                 push @deferred, $id;
689                                 next;
690                         }
691                         $sub->($hooks{$type}{$id}{call});
692                 }
693                 foreach my $id (@deferred) {
694                         $sub->($hooks{$type}{$id}{call});
695                 }
696         }
697 } #}}}
698
699 sub globlist_to_pagespec ($) { #{{{
700         my @globlist=split(' ', shift);
701
702         my (@spec, @skip);
703         foreach my $glob (@globlist) {
704                 if ($glob=~/^!(.*)/) {
705                         push @skip, $glob;
706                 }
707                 else {
708                         push @spec, $glob;
709                 }
710         }
711
712         my $spec=join(" or ", @spec);
713         if (@skip) {
714                 my $skip=join(" and ", @skip);
715                 if (length $spec) {
716                         $spec="$skip and ($spec)";
717                 }
718                 else {
719                         $spec=$skip;
720                 }
721         }
722         return $spec;
723 } #}}}
724
725 sub is_globlist ($) { #{{{
726         my $s=shift;
727         $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
728 } #}}}
729
730 sub safequote ($) { #{{{
731         my $s=shift;
732         $s=~s/[{}]//g;
733         return "q{$s}";
734 } #}}}
735
736 sub pagespec_merge ($$) { #{{{
737         my $a=shift;
738         my $b=shift;
739
740         return $a if $a eq $b;
741
742         # Support for old-style GlobLists.
743         if (is_globlist($a)) {
744                 $a=globlist_to_pagespec($a);
745         }
746         if (is_globlist($b)) {
747                 $b=globlist_to_pagespec($b);
748         }
749
750         return "($a) or ($b)";
751 } #}}}
752
753 sub pagespec_translate ($) { #{{{
754         # This assumes that $page is in scope in the function
755         # that evalulates the translated pagespec code.
756         my $spec=shift;
757
758         # Support for old-style GlobLists.
759         if (is_globlist($spec)) {
760                 $spec=globlist_to_pagespec($spec);
761         }
762
763         # Convert spec to perl code.
764         my $code="";
765         while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
766                 my $word=$1;
767                 if (lc $word eq "and") {
768                         $code.=" &&";
769                 }
770                 elsif (lc $word eq "or") {
771                         $code.=" ||";
772                 }
773                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
774                         $code.=" ".$word;
775                 }
776                 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
777                         $code.=" match_$1(\$page, ".safequote($2).")";
778                 }
779                 else {
780                         $code.=" match_glob(\$page, ".safequote($word).")";
781                 }
782         }
783
784         return $code;
785 } #}}}
786
787 sub add_depends ($$) { #{{{
788         my $page=shift;
789         my $pagespec=shift;
790         
791         if (! exists $depends{$page}) {
792                 $depends{$page}=$pagespec;
793         }
794         else {
795                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
796         }
797 } # }}}
798
799 sub file_pruned ($$) { #{{{
800         require File::Spec;
801         my $file=File::Spec->canonpath(shift);
802         my $base=File::Spec->canonpath(shift);
803         $file=~s#^\Q$base\E/*##;
804
805         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
806         $file =~ m/$regexp/;
807 } #}}}
808
809 sub gettext { #{{{
810         # Only use gettext in the rare cases it's needed.
811         # This overrides future calls of this function.
812         if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
813                 eval q{use Locale::gettext};
814                 textdomain('ikiwiki');
815                 return Locale::gettext::gettext(shift);
816         }
817         else {
818                 return shift;
819         }
820 } #}}}
821
822 sub pagespec_match ($$) { #{{{
823         my $page=shift;
824         my $spec=shift;
825
826         return eval pagespec_translate($spec);
827 } #}}}
828
829 sub match_glob ($$) { #{{{
830         my $page=shift;
831         my $glob=shift;
832
833         # turn glob into safe regexp
834         $glob=quotemeta($glob);
835         $glob=~s/\\\*/.*/g;
836         $glob=~s/\\\?/./g;
837
838         return $page=~/^$glob$/i;
839 } #}}}
840
841 sub match_link ($$) { #{{{
842         my $page=shift;
843         my $link=lc(shift);
844
845         my $links = $links{$page} or return undef;
846         foreach my $p (@$links) {
847                 return 1 if lc $p eq $link;
848         }
849         return 0;
850 } #}}}
851
852 sub match_backlink ($$) { #{{{
853         match_link(pop, pop);
854 } #}}}
855
856 sub match_created_before ($$) { #{{{
857         my $page=shift;
858         my $testpage=shift;
859
860         if (exists $pagectime{$testpage}) {
861                 return $pagectime{$page} < $pagectime{$testpage};
862         }
863         else {
864                 return 0;
865         }
866 } #}}}
867
868 sub match_created_after ($$) { #{{{
869         my $page=shift;
870         my $testpage=shift;
871
872         if (exists $pagectime{$testpage}) {
873                 return $pagectime{$page} > $pagectime{$testpage};
874         }
875         else {
876                 return 0;
877         }
878 } #}}}
879
880 sub match_creation_day ($$) { #{{{
881         return ((gmtime($pagectime{shift()}))[3] == shift);
882 } #}}}
883
884 sub match_creation_month ($$) { #{{{
885         return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
886 } #}}}
887
888 sub match_creation_year ($$) { #{{{
889         return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
890 } #}}}
891
892 1