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