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