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