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