]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
response
[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 URI::Escape q{uri_escape_utf8};
9 use POSIX;
10 use Storable;
11 use open qw{:utf8 :std};
12
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14             %pagestate %renderedfiles %oldrenderedfiles %pagesources
15             %destsources %depends %hooks %forcerebuild $gettext_obj};
16
17 use Exporter q{import};
18 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
19                  bestlink htmllink readfile writefile pagetype srcfile pagename
20                  displaytime will_render gettext urlto targetpage
21                  add_underlay
22                  %config %links %pagestate %renderedfiles
23                  %pagesources %destsources);
24 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
25 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
26 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
27
28 # Optimisation.
29 use Memoize;
30 memoize("abs2rel");
31 memoize("pagespec_translate");
32 memoize("file_pruned");
33
34 sub defaultconfig () { #{{{
35         return
36         wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
37                 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
38                 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
39                 qr/(^|\/)_MTN\//,
40                 qr/\.dpkg-tmp$/],
41         wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
42         web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
43         verbose => 0,
44         syslog => 0,
45         wikiname => "wiki",
46         default_pageext => "mdwn",
47         htmlext => "html",
48         cgi => 0,
49         post_commit => 0,
50         rcs => '',
51         url => '',
52         cgiurl => '',
53         historyurl => '',
54         diffurl => '',
55         rss => 0,
56         atom => 0,
57         allowrss => 0,
58         allowatom => 0,
59         discussion => 1,
60         rebuild => 0,
61         refresh => 0,
62         getctime => 0,
63         w3mmode => 0,
64         wrapper => undef,
65         wrappermode => undef,
66         svnpath => "trunk",
67         gitorigin_branch => "origin",
68         gitmaster_branch => "master",
69         srcdir => undef,
70         destdir => undef,
71         pingurl => [],
72         templatedir => "$installdir/share/ikiwiki/templates",
73         underlaydir => "$installdir/share/ikiwiki/basewiki",
74         underlaydirs => [],
75         setup => undef,
76         adminuser => undef,
77         adminemail => undef,
78         plugin => [qw{mdwn link inline htmlscrubber passwordauth openid
79                         signinedit lockedit conditional recentchanges}],
80         libdir => undef,
81         timeformat => '%c',
82         locale => undef,
83         sslcookie => 0,
84         httpauth => 0,
85         userdir => "",
86         usedirs => 1,
87         numbacklinks => 10,
88         account_creation_password => "",
89         prefix_directives => 0,
90         hardlink => 0,
91         cgi_disable_uploads => 1,
92 } #}}}
93
94 sub checkconfig () { #{{{
95         # locale stuff; avoid LC_ALL since it overrides everything
96         if (defined $ENV{LC_ALL}) {
97                 $ENV{LANG} = $ENV{LC_ALL};
98                 delete $ENV{LC_ALL};
99         }
100         if (defined $config{locale}) {
101                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
102                         $ENV{LANG}=$config{locale};
103                         $gettext_obj=undef;
104                 }
105         }
106
107         if (ref $config{ENV} eq 'HASH') {
108                 foreach my $val (keys %{$config{ENV}}) {
109                         $ENV{$val}=$config{ENV}{$val};
110                 }
111         }
112
113         if ($config{w3mmode}) {
114                 eval q{use Cwd q{abs_path}};
115                 error($@) if $@;
116                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
117                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
118                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
119                         unless $config{cgiurl} =~ m!file:///!;
120                 $config{url}="file://".$config{destdir};
121         }
122
123         if ($config{cgi} && ! length $config{url}) {
124                 error(gettext("Must specify url to wiki with --url when using --cgi"));
125         }
126         
127         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
128                 unless exists $config{wikistatedir};
129         
130         if ($config{rcs}) {
131                 eval qq{use IkiWiki::Rcs::$config{rcs}};
132                 if ($@) {
133                         error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
134                 }
135         }
136         else {
137                 require IkiWiki::Rcs::Stub;
138         }
139
140         if (exists $config{umask}) {
141                 umask(possibly_foolish_untaint($config{umask}));
142         }
143
144         run_hooks(checkconfig => sub { shift->() });
145
146         return 1;
147 } #}}}
148
149 sub loadplugins () { #{{{
150         if (defined $config{libdir}) {
151                 unshift @INC, possibly_foolish_untaint($config{libdir});
152         }
153
154         loadplugin($_) foreach @{$config{plugin}};
155
156         run_hooks(getopt => sub { shift->() });
157         if (grep /^-/, @ARGV) {
158                 print STDERR "Unknown option: $_\n"
159                         foreach grep /^-/, @ARGV;
160                 usage();
161         }
162
163         return 1;
164 } #}}}
165
166 sub loadplugin ($) { #{{{
167         my $plugin=shift;
168
169         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
170
171         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
172                          "$installdir/lib/ikiwiki") {
173                 if (defined $dir && -x "$dir/plugins/$plugin") {
174                         require IkiWiki::Plugin::external;
175                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
176                         return 1;
177                 }
178         }
179
180         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
181         eval qq{use $mod};
182         if ($@) {
183                 error("Failed to load plugin $mod: $@");
184         }
185         return 1;
186 } #}}}
187
188 sub error ($;$) { #{{{
189         my $message=shift;
190         my $cleaner=shift;
191         if ($config{cgi}) {
192                 print "Content-type: text/html\n\n";
193                 print misctemplate(gettext("Error"),
194                         "<p>".gettext("Error").": $message</p>");
195         }
196         log_message('err' => $message) if $config{syslog};
197         if (defined $cleaner) {
198                 $cleaner->();
199         }
200         die $message."\n";
201 } #}}}
202
203 sub debug ($) { #{{{
204         return unless $config{verbose};
205         return log_message(debug => @_);
206 } #}}}
207
208 my $log_open=0;
209 sub log_message ($$) { #{{{
210         my $type=shift;
211
212         if ($config{syslog}) {
213                 require Sys::Syslog;
214                 if (! $log_open) {
215                         Sys::Syslog::setlogsock('unix');
216                         Sys::Syslog::openlog('ikiwiki', '', 'user');
217                         $log_open=1;
218                 }
219                 return eval {
220                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
221                 };
222         }
223         elsif (! $config{cgi}) {
224                 return print "@_\n";
225         }
226         else {
227                 return print STDERR "@_\n";
228         }
229 } #}}}
230
231 sub possibly_foolish_untaint ($) { #{{{
232         my $tainted=shift;
233         my ($untainted)=$tainted=~/(.*)/s;
234         return $untainted;
235 } #}}}
236
237 sub basename ($) { #{{{
238         my $file=shift;
239
240         $file=~s!.*/+!!;
241         return $file;
242 } #}}}
243
244 sub dirname ($) { #{{{
245         my $file=shift;
246
247         $file=~s!/*[^/]+$!!;
248         return $file;
249 } #}}}
250
251 sub pagetype ($) { #{{{
252         my $page=shift;
253         
254         if ($page =~ /\.([^.]+)$/) {
255                 return $1 if exists $hooks{htmlize}{$1};
256         }
257         return;
258 } #}}}
259
260 sub isinternal ($) { #{{{
261         my $page=shift;
262         return exists $pagesources{$page} &&
263                 $pagesources{$page} =~ /\._([^.]+)$/;
264 } #}}}
265
266 sub pagename ($) { #{{{
267         my $file=shift;
268
269         my $type=pagetype($file);
270         my $page=$file;
271         $page=~s/\Q.$type\E*$// if defined $type;
272         return $page;
273 } #}}}
274
275 sub targetpage ($$) { #{{{
276         my $page=shift;
277         my $ext=shift;
278         
279         if (! $config{usedirs} || $page =~ /^index$/ ) {
280                 return $page.".".$ext;
281         } else {
282                 return $page."/index.".$ext;
283         }
284 } #}}}
285
286 sub htmlpage ($) { #{{{
287         my $page=shift;
288         
289         return targetpage($page, $config{htmlext});
290 } #}}}
291
292 sub srcfile_stat { #{{{
293         my $file=shift;
294         my $nothrow=shift;
295
296         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
297         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
298                 return "$dir/$file", stat(_) if -e "$dir/$file";
299         }
300         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
301         return;
302 } #}}}
303
304 sub srcfile ($;$) { #{{{
305         return (srcfile_stat(@_))[0];
306 } #}}}
307
308 sub add_underlay ($) { #{{{
309         my $dir=shift;
310
311         if ($dir=~/^\//) {
312                 unshift @{$config{underlaydirs}}, $dir;
313         }
314         else {
315                 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
316         }
317
318         return 1;
319 } #}}}
320
321 sub readfile ($;$$) { #{{{
322         my $file=shift;
323         my $binary=shift;
324         my $wantfd=shift;
325
326         if (-l $file) {
327                 error("cannot read a symlink ($file)");
328         }
329         
330         local $/=undef;
331         open (my $in, "<", $file) || error("failed to read $file: $!");
332         binmode($in) if ($binary);
333         return \*$in if $wantfd;
334         my $ret=<$in>;
335         close $in || error("failed to read $file: $!");
336         return $ret;
337 } #}}}
338
339 sub prep_writefile ($$) {
340         my $file=shift;
341         my $destdir=shift;
342         
343         my $test=$file;
344         while (length $test) {
345                 if (-l "$destdir/$test") {
346                         error("cannot write to a symlink ($test)");
347                 }
348                 $test=dirname($test);
349         }
350
351         my $dir=dirname("$destdir/$file");
352         if (! -d $dir) {
353                 my $d="";
354                 foreach my $s (split(m!/+!, $dir)) {
355                         $d.="$s/";
356                         if (! -d $d) {
357                                 mkdir($d) || error("failed to create directory $d: $!");
358                         }
359                 }
360         }
361
362         return 1;
363 }
364
365 sub writefile ($$$;$$) { #{{{
366         my $file=shift; # can include subdirs
367         my $destdir=shift; # directory to put file in
368         my $content=shift;
369         my $binary=shift;
370         my $writer=shift;
371         
372         prep_writefile($file, $destdir);
373         
374         my $newfile="$destdir/$file.ikiwiki-new";
375         if (-l $newfile) {
376                 error("cannot write to a symlink ($newfile)");
377         }
378         
379         my $cleanup = sub { unlink($newfile) };
380         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
381         binmode($out) if ($binary);
382         if ($writer) {
383                 $writer->(\*$out, $cleanup);
384         }
385         else {
386                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
387         }
388         close $out || error("failed saving $newfile: $!", $cleanup);
389         rename($newfile, "$destdir/$file") || 
390                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
391
392         return 1;
393 } #}}}
394
395 my %cleared;
396 sub will_render ($$;$) { #{{{
397         my $page=shift;
398         my $dest=shift;
399         my $clear=shift;
400
401         # Important security check.
402         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
403             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
404                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
405         }
406
407         if (! $clear || $cleared{$page}) {
408                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
409         }
410         else {
411                 foreach my $old (@{$renderedfiles{$page}}) {
412                         delete $destsources{$old};
413                 }
414                 $renderedfiles{$page}=[$dest];
415                 $cleared{$page}=1;
416         }
417         $destsources{$dest}=$page;
418
419         return 1;
420 } #}}}
421
422 sub bestlink ($$) { #{{{
423         my $page=shift;
424         my $link=shift;
425         
426         my $cwd=$page;
427         if ($link=~s/^\/+//) {
428                 # absolute links
429                 $cwd="";
430         }
431         $link=~s/\/$//;
432
433         do {
434                 my $l=$cwd;
435                 $l.="/" if length $l;
436                 $l.=$link;
437
438                 if (exists $links{$l}) {
439                         return $l;
440                 }
441                 elsif (exists $pagecase{lc $l}) {
442                         return $pagecase{lc $l};
443                 }
444         } while $cwd=~s!/?[^/]+$!!;
445
446         if (length $config{userdir}) {
447                 my $l = "$config{userdir}/".lc($link);
448                 if (exists $links{$l}) {
449                         return $l;
450                 }
451                 elsif (exists $pagecase{lc $l}) {
452                         return $pagecase{lc $l};
453                 }
454         }
455
456         #print STDERR "warning: page $page, broken link: $link\n";
457         return "";
458 } #}}}
459
460 sub isinlinableimage ($) { #{{{
461         my $file=shift;
462         
463         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
464 } #}}}
465
466 sub pagetitle ($;$) { #{{{
467         my $page=shift;
468         my $unescaped=shift;
469
470         if ($unescaped) {
471                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
472         }
473         else {
474                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
475         }
476
477         return $page;
478 } #}}}
479
480 sub titlepage ($) { #{{{
481         my $title=shift;
482         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
483         return $title;
484 } #}}}
485
486 sub linkpage ($) { #{{{
487         my $link=shift;
488         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
489         return $link;
490 } #}}}
491
492 sub cgiurl (@) { #{{{
493         my %params=@_;
494
495         return $config{cgiurl}."?".
496                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
497 } #}}}
498
499 sub baseurl (;$) { #{{{
500         my $page=shift;
501
502         return "$config{url}/" if ! defined $page;
503         
504         $page=htmlpage($page);
505         $page=~s/[^\/]+$//;
506         $page=~s/[^\/]+\//..\//g;
507         return $page;
508 } #}}}
509
510 sub abs2rel ($$) { #{{{
511         # Work around very innefficient behavior in File::Spec if abs2rel
512         # is passed two relative paths. It's much faster if paths are
513         # absolute! (Debian bug #376658; fixed in debian unstable now)
514         my $path="/".shift;
515         my $base="/".shift;
516
517         require File::Spec;
518         my $ret=File::Spec->abs2rel($path, $base);
519         $ret=~s/^// if defined $ret;
520         return $ret;
521 } #}}}
522
523 sub displaytime ($;$) { #{{{
524         my $time=shift;
525         my $format=shift;
526         if (! defined $format) {
527                 $format=$config{timeformat};
528         }
529
530         # strftime doesn't know about encodings, so make sure
531         # its output is properly treated as utf8
532         return decode_utf8(POSIX::strftime($format, localtime($time)));
533 } #}}}
534
535 sub beautify_url ($) { #{{{
536         my $url=shift;
537
538         if ($config{usedirs}) {
539                 $url =~ s!/index.$config{htmlext}$!/!;
540         }
541         $url =~ s!^$!./!; # Browsers don't like empty links...
542
543         return $url;
544 } #}}}
545
546 sub urlto ($$) { #{{{
547         my $to=shift;
548         my $from=shift;
549
550         if (! length $to) {
551                 return beautify_url(baseurl($from)."index.$config{htmlext}");
552         }
553
554         if (! $destsources{$to}) {
555                 $to=htmlpage($to);
556         }
557
558         my $link = abs2rel($to, dirname(htmlpage($from)));
559
560         return beautify_url($link);
561 } #}}}
562
563 sub htmllink ($$$;@) { #{{{
564         my $lpage=shift; # the page doing the linking
565         my $page=shift; # the page that will contain the link (different for inline)
566         my $link=shift;
567         my %opts=@_;
568
569         $link=~s/\/$//;
570
571         my $bestlink;
572         if (! $opts{forcesubpage}) {
573                 $bestlink=bestlink($lpage, $link);
574         }
575         else {
576                 $bestlink="$lpage/".lc($link);
577         }
578
579         my $linktext;
580         if (defined $opts{linktext}) {
581                 $linktext=$opts{linktext};
582         }
583         else {
584                 $linktext=pagetitle(basename($link));
585         }
586         
587         return "<span class=\"selflink\">$linktext</span>"
588                 if length $bestlink && $page eq $bestlink &&
589                    ! defined $opts{anchor};
590         
591         if (! $destsources{$bestlink}) {
592                 $bestlink=htmlpage($bestlink);
593
594                 if (! $destsources{$bestlink}) {
595                         return $linktext unless length $config{cgiurl};
596                         return "<span class=\"createlink\"><a href=\"".
597                                 cgiurl(
598                                         do => "create",
599                                         page => pagetitle(lc($link), 1),
600                                         from => $lpage
601                                 ).
602                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
603                 }
604         }
605         
606         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
607         $bestlink=beautify_url($bestlink);
608         
609         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
610                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
611         }
612
613         if (defined $opts{anchor}) {
614                 $bestlink.="#".$opts{anchor};
615         }
616
617         my @attrs;
618         if (defined $opts{rel}) {
619                 push @attrs, ' rel="'.$opts{rel}.'"';
620         }
621         if (defined $opts{class}) {
622                 push @attrs, ' class="'.$opts{class}.'"';
623         }
624
625         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
626 } #}}}
627
628 sub userlink ($) { #{{{
629         my $user=shift;
630
631         my $oiduser=eval { openiduser($user) };
632         if (defined $oiduser) {
633                 return "<a href=\"$user\">$oiduser</a>";
634         }
635         else {
636                 eval q{use CGI 'escapeHTML'};
637                 error($@) if $@;
638
639                 return htmllink("", "", escapeHTML(
640                         length $config{userdir} ? $config{userdir}."/".$user : $user
641                 ), noimageinline => 1);
642         }
643 } #}}}
644
645 sub htmlize ($$$$) { #{{{
646         my $page=shift;
647         my $destpage=shift;
648         my $type=shift;
649         my $content=shift;
650         
651         my $oneline = $content !~ /\n/;
652
653         if (exists $hooks{htmlize}{$type}) {
654                 $content=$hooks{htmlize}{$type}{call}->(
655                         page => $page,
656                         content => $content,
657                 );
658         }
659         else {
660                 error("htmlization of $type not supported");
661         }
662
663         run_hooks(sanitize => sub {
664                 $content=shift->(
665                         page => $page,
666                         destpage => $destpage,
667                         content => $content,
668                 );
669         });
670         
671         if ($oneline) {
672                 # hack to get rid of enclosing junk added by markdown
673                 # and other htmlizers
674                 $content=~s/^<p>//i;
675                 $content=~s/<\/p>$//i;
676                 chomp $content;
677         }
678
679         return $content;
680 } #}}}
681
682 sub linkify ($$$) { #{{{
683         my $page=shift;
684         my $destpage=shift;
685         my $content=shift;
686
687         run_hooks(linkify => sub {
688                 $content=shift->(
689                         page => $page,
690                         destpage => $destpage,
691                         content => $content,
692                 );
693         });
694         
695         return $content;
696 } #}}}
697
698 our %preprocessing;
699 our $preprocess_preview=0;
700 sub preprocess ($$$;$$) { #{{{
701         my $page=shift; # the page the data comes from
702         my $destpage=shift; # the page the data will appear in (different for inline)
703         my $content=shift;
704         my $scan=shift;
705         my $preview=shift;
706
707         # Using local because it needs to be set within any nested calls
708         # of this function.
709         local $preprocess_preview=$preview if defined $preview;
710
711         my $handle=sub {
712                 my $escape=shift;
713                 my $prefix=shift;
714                 my $command=shift;
715                 my $params=shift;
716                 if (length $escape) {
717                         return "[[$prefix$command $params]]";
718                 }
719                 elsif (exists $hooks{preprocess}{$command}) {
720                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
721                         # Note: preserve order of params, some plugins may
722                         # consider it significant.
723                         my @params;
724                         while ($params =~ m{
725                                 (?:([-\w]+)=)?          # 1: named parameter key?
726                                 (?:
727                                         """(.*?)"""     # 2: triple-quoted value
728                                 |
729                                         "([^"]+)"       # 3: single-quoted value
730                                 |
731                                         (\S+)           # 4: unquoted value
732                                 )
733                                 (?:\s+|$)               # delimiter to next param
734                         }sgx) {
735                                 my $key=$1;
736                                 my $val;
737                                 if (defined $2) {
738                                         $val=$2;
739                                         $val=~s/\r\n/\n/mg;
740                                         $val=~s/^\n+//g;
741                                         $val=~s/\n+$//g;
742                                 }
743                                 elsif (defined $3) {
744                                         $val=$3;
745                                 }
746                                 elsif (defined $4) {
747                                         $val=$4;
748                                 }
749
750                                 if (defined $key) {
751                                         push @params, $key, $val;
752                                 }
753                                 else {
754                                         push @params, $val, '';
755                                 }
756                         }
757                         if ($preprocessing{$page}++ > 3) {
758                                 # Avoid loops of preprocessed pages preprocessing
759                                 # other pages that preprocess them, etc.
760                                 #translators: The first parameter is a
761                                 #translators: preprocessor directive name,
762                                 #translators: the second a page name, the
763                                 #translators: third a number.
764                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
765                                         $command, $page, $preprocessing{$page}).
766                                 "]]";
767                         }
768                         my $ret;
769                         if (! $scan) {
770                                 $ret=$hooks{preprocess}{$command}{call}->(
771                                         @params,
772                                         page => $page,
773                                         destpage => $destpage,
774                                         preview => $preprocess_preview,
775                                 );
776                         }
777                         else {
778                                 # use void context during scan pass
779                                 $hooks{preprocess}{$command}{call}->(
780                                         @params,
781                                         page => $page,
782                                         destpage => $destpage,
783                                         preview => $preprocess_preview,
784                                 );
785                                 $ret="";
786                         }
787                         $preprocessing{$page}--;
788                         return $ret;
789                 }
790                 else {
791                         return "[[$prefix$command $params]]";
792                 }
793         };
794         
795         my $regex;
796         if ($config{prefix_directives}) {
797                 $regex = qr{
798                         (\\?)           # 1: escape?
799                         \[\[(!)         # directive open; 2: prefix
800                         ([-\w]+)        # 3: command
801                         (               # 4: the parameters..
802                                 \s+     # Must have space if parameters present
803                                 (?:
804                                         (?:[-\w]+=)?            # named parameter key?
805                                         (?:
806                                                 """.*?"""       # triple-quoted value
807                                                 |
808                                                 "[^"]+"         # single-quoted value
809                                                 |
810                                                 [^\s\]]+        # unquoted value
811                                         )
812                                         \s*                     # whitespace or end
813                                                                 # of directive
814                                 )
815                         *)?             # 0 or more parameters
816                         \]\]            # directive closed
817                 }sx;
818         } else {
819                 $regex = qr{
820                         (\\?)           # 1: escape?
821                         \[\[(!?)        # directive open; 2: optional prefix
822                         ([-\w]+)        # 3: command
823                         \s+
824                         (               # 4: the parameters..
825                                 (?:
826                                         (?:[-\w]+=)?            # named parameter key?
827                                         (?:
828                                                 """.*?"""       # triple-quoted value
829                                                 |
830                                                 "[^"]+"         # single-quoted value
831                                                 |
832                                                 [^\s\]]+        # unquoted value
833                                         )
834                                         \s*                     # whitespace or end
835                                                                 # of directive
836                                 )
837                         *)              # 0 or more parameters
838                         \]\]            # directive closed
839                 }sx;
840         }
841
842         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
843         return $content;
844 } #}}}
845
846 sub filter ($$$) { #{{{
847         my $page=shift;
848         my $destpage=shift;
849         my $content=shift;
850
851         run_hooks(filter => sub {
852                 $content=shift->(page => $page, destpage => $destpage, 
853                         content => $content);
854         });
855
856         return $content;
857 } #}}}
858
859 sub indexlink () { #{{{
860         return "<a href=\"$config{url}\">$config{wikiname}</a>";
861 } #}}}
862
863 my $wikilock;
864
865 sub lockwiki (;$) { #{{{
866         my $wait=@_ ? shift : 1;
867         # Take an exclusive lock on the wiki to prevent multiple concurrent
868         # run issues. The lock will be dropped on program exit.
869         if (! -d $config{wikistatedir}) {
870                 mkdir($config{wikistatedir});
871         }
872         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
873                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
874         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
875                 if ($wait) {
876                         debug("wiki seems to be locked, waiting for lock");
877                         my $wait=600; # arbitrary, but don't hang forever to 
878                                       # prevent process pileup
879                         for (1..$wait) {
880                                 return if flock($wikilock, 2 | 4);
881                                 sleep 1;
882                         }
883                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
884                 }
885                 else {
886                         return 0;
887                 }
888         }
889         return 1;
890 } #}}}
891
892 sub unlockwiki () { #{{{
893         return close($wikilock) if $wikilock;
894         return;
895 } #}}}
896
897 my $commitlock;
898
899 sub commit_hook_enabled () { #{{{
900         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
901                 error("cannot write to $config{wikistatedir}/commitlock: $!");
902         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
903                 close($commitlock) || error("failed closing commitlock: $!");
904                 return 0;
905         }
906         close($commitlock) || error("failed closing commitlock: $!");
907         return 1;
908 } #}}}
909
910 sub disable_commit_hook () { #{{{
911         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
912                 error("cannot write to $config{wikistatedir}/commitlock: $!");
913         if (! flock($commitlock, 2)) { # LOCK_EX
914                 error("failed to get commit lock");
915         }
916         return 1;
917 } #}}}
918
919 sub enable_commit_hook () { #{{{
920         return close($commitlock) if $commitlock;
921         return;
922 } #}}}
923
924 sub loadindex () { #{{{
925         %oldrenderedfiles=%pagectime=();
926         if (! $config{rebuild}) {
927                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
928                 %destsources=%renderedfiles=%pagecase=%pagestate=();
929         }
930         my $in;
931         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
932                 if (-e "$config{wikistatedir}/index") {
933                         system("ikiwiki-transition", "indexdb", $config{srcdir});
934                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
935                 }
936                 else {
937                         return;
938                 }
939         }
940         my $ret=Storable::fd_retrieve($in);
941         if (! defined $ret) {
942                 return 0;
943         }
944         my %index=%$ret;
945         foreach my $src (keys %index) {
946                 my %d=%{$index{$src}};
947                 my $page=pagename($src);
948                 $pagectime{$page}=$d{ctime};
949                 if (! $config{rebuild}) {
950                         $pagesources{$page}=$src;
951                         $pagemtime{$page}=$d{mtime};
952                         $renderedfiles{$page}=$d{dest};
953                         if (exists $d{links} && ref $d{links}) {
954                                 $links{$page}=$d{links};
955                                 $oldlinks{$page}=[@{$d{links}}];
956                         }
957                         if (exists $d{depends}) {
958                                 $depends{$page}=$d{depends};
959                         }
960                         if (exists $d{state}) {
961                                 $pagestate{$page}=$d{state};
962                         }
963                 }
964                 $oldrenderedfiles{$page}=[@{$d{dest}}];
965         }
966         foreach my $page (keys %pagesources) {
967                 $pagecase{lc $page}=$page;
968         }
969         foreach my $page (keys %renderedfiles) {
970                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
971         }
972         return close($in);
973 } #}}}
974
975 sub saveindex () { #{{{
976         run_hooks(savestate => sub { shift->() });
977
978         my %hookids;
979         foreach my $type (keys %hooks) {
980                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
981         }
982         my @hookids=keys %hookids;
983
984         if (! -d $config{wikistatedir}) {
985                 mkdir($config{wikistatedir});
986         }
987         my $newfile="$config{wikistatedir}/indexdb.new";
988         my $cleanup = sub { unlink($newfile) };
989         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
990         my %index;
991         foreach my $page (keys %pagemtime) {
992                 next unless $pagemtime{$page};
993                 my $src=$pagesources{$page};
994
995                 $index{$src}={
996                         ctime => $pagectime{$page},
997                         mtime => $pagemtime{$page},
998                         dest => $renderedfiles{$page},
999                         links => $links{$page},
1000                 };
1001
1002                 if (exists $depends{$page}) {
1003                         $index{$src}{depends} = $depends{$page};
1004                 }
1005
1006                 if (exists $pagestate{$page}) {
1007                         foreach my $id (@hookids) {
1008                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1009                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1010                                 }
1011                         }
1012                 }
1013         }
1014         my $ret=Storable::nstore_fd(\%index, $out);
1015         return if ! defined $ret || ! $ret;
1016         close $out || error("failed saving to $newfile: $!", $cleanup);
1017         rename($newfile, "$config{wikistatedir}/indexdb") ||
1018                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1019         
1020         return 1;
1021 } #}}}
1022
1023 sub template_file ($) { #{{{
1024         my $template=shift;
1025
1026         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1027                 return "$dir/$template" if -e "$dir/$template";
1028         }
1029         return;
1030 } #}}}
1031
1032 sub template_params (@) { #{{{
1033         my $filename=template_file(shift);
1034
1035         if (! defined $filename) {
1036                 return if wantarray;
1037                 return "";
1038         }
1039
1040         my @ret=(
1041                 filter => sub {
1042                         my $text_ref = shift;
1043                         ${$text_ref} = decode_utf8(${$text_ref});
1044                 },
1045                 filename => $filename,
1046                 loop_context_vars => 1,
1047                 die_on_bad_params => 0,
1048                 @_
1049         );
1050         return wantarray ? @ret : {@ret};
1051 } #}}}
1052
1053 sub template ($;@) { #{{{
1054         require HTML::Template;
1055         return HTML::Template->new(template_params(@_));
1056 } #}}}
1057
1058 sub misctemplate ($$;@) { #{{{
1059         my $title=shift;
1060         my $pagebody=shift;
1061         
1062         my $template=template("misc.tmpl");
1063         $template->param(
1064                 title => $title,
1065                 indexlink => indexlink(),
1066                 wikiname => $config{wikiname},
1067                 pagebody => $pagebody,
1068                 baseurl => baseurl(),
1069                 @_,
1070         );
1071         run_hooks(pagetemplate => sub {
1072                 shift->(page => "", destpage => "", template => $template);
1073         });
1074         return $template->output;
1075 }#}}}
1076
1077 sub hook (@) { # {{{
1078         my %param=@_;
1079         
1080         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1081                 error 'hook requires type, call, and id parameters';
1082         }
1083
1084         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1085         
1086         $hooks{$param{type}}{$param{id}}=\%param;
1087         return 1;
1088 } # }}}
1089
1090 sub run_hooks ($$) { # {{{
1091         # Calls the given sub for each hook of the given type,
1092         # passing it the hook function to call.
1093         my $type=shift;
1094         my $sub=shift;
1095
1096         if (exists $hooks{$type}) {
1097                 my @deferred;
1098                 foreach my $id (keys %{$hooks{$type}}) {
1099                         if ($hooks{$type}{$id}{last}) {
1100                                 push @deferred, $id;
1101                                 next;
1102                         }
1103                         $sub->($hooks{$type}{$id}{call});
1104                 }
1105                 foreach my $id (@deferred) {
1106                         $sub->($hooks{$type}{$id}{call});
1107                 }
1108         }
1109
1110         return 1;
1111 } #}}}
1112
1113 sub globlist_to_pagespec ($) { #{{{
1114         my @globlist=split(' ', shift);
1115
1116         my (@spec, @skip);
1117         foreach my $glob (@globlist) {
1118                 if ($glob=~/^!(.*)/) {
1119                         push @skip, $glob;
1120                 }
1121                 else {
1122                         push @spec, $glob;
1123                 }
1124         }
1125
1126         my $spec=join(' or ', @spec);
1127         if (@skip) {
1128                 my $skip=join(' and ', @skip);
1129                 if (length $spec) {
1130                         $spec="$skip and ($spec)";
1131                 }
1132                 else {
1133                         $spec=$skip;
1134                 }
1135         }
1136         return $spec;
1137 } #}}}
1138
1139 sub is_globlist ($) { #{{{
1140         my $s=shift;
1141         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1142 } #}}}
1143
1144 sub safequote ($) { #{{{
1145         my $s=shift;
1146         $s=~s/[{}]//g;
1147         return "q{$s}";
1148 } #}}}
1149
1150 sub add_depends ($$) { #{{{
1151         my $page=shift;
1152         my $pagespec=shift;
1153         
1154         return unless pagespec_valid($pagespec);
1155
1156         if (! exists $depends{$page}) {
1157                 $depends{$page}=$pagespec;
1158         }
1159         else {
1160                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1161         }
1162
1163         return 1;
1164 } # }}}
1165
1166 sub file_pruned ($$) { #{{{
1167         require File::Spec;
1168         my $file=File::Spec->canonpath(shift);
1169         my $base=File::Spec->canonpath(shift);
1170         $file =~ s#^\Q$base\E/+##;
1171
1172         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1173         return $file =~ m/$regexp/ && $file ne $base;
1174 } #}}}
1175
1176 sub gettext { #{{{
1177         # Only use gettext in the rare cases it's needed.
1178         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1179             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1180             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1181                 if (! $gettext_obj) {
1182                         $gettext_obj=eval q{
1183                                 use Locale::gettext q{textdomain};
1184                                 Locale::gettext->domain('ikiwiki')
1185                         };
1186                         if ($@) {
1187                                 print STDERR "$@";
1188                                 $gettext_obj=undef;
1189                                 return shift;
1190                         }
1191                 }
1192                 return $gettext_obj->get(shift);
1193         }
1194         else {
1195                 return shift;
1196         }
1197 } #}}}
1198
1199 sub pagespec_merge ($$) { #{{{
1200         my $a=shift;
1201         my $b=shift;
1202
1203         return $a if $a eq $b;
1204
1205         # Support for old-style GlobLists.
1206         if (is_globlist($a)) {
1207                 $a=globlist_to_pagespec($a);
1208         }
1209         if (is_globlist($b)) {
1210                 $b=globlist_to_pagespec($b);
1211         }
1212
1213         return "($a) or ($b)";
1214 } #}}}
1215
1216 sub pagespec_translate ($) { #{{{
1217         my $spec=shift;
1218
1219         # Support for old-style GlobLists.
1220         if (is_globlist($spec)) {
1221                 $spec=globlist_to_pagespec($spec);
1222         }
1223
1224         # Convert spec to perl code.
1225         my $code="";
1226         while ($spec=~m{
1227                 \s*             # ignore whitespace
1228                 (               # 1: match a single word
1229                         \!              # !
1230                 |
1231                         \(              # (
1232                 |
1233                         \)              # )
1234                 |
1235                         \w+\([^\)]*\)   # command(params)
1236                 |
1237                         [^\s()]+        # any other text
1238                 )
1239                 \s*             # ignore whitespace
1240         }igx) {
1241                 my $word=$1;
1242                 if (lc $word eq 'and') {
1243                         $code.=' &&';
1244                 }
1245                 elsif (lc $word eq 'or') {
1246                         $code.=' ||';
1247                 }
1248                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1249                         $code.=' '.$word;
1250                 }
1251                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1252                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1253                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1254                         }
1255                         else {
1256                                 $code.=' 0';
1257                         }
1258                 }
1259                 else {
1260                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1261                 }
1262         }
1263
1264         if (! length $code) {
1265                 $code=0;
1266         }
1267
1268         no warnings;
1269         return eval 'sub { my $page=shift; '.$code.' }';
1270 } #}}}
1271
1272 sub pagespec_match ($$;@) { #{{{
1273         my $page=shift;
1274         my $spec=shift;
1275         my @params=@_;
1276
1277         # Backwards compatability with old calling convention.
1278         if (@params == 1) {
1279                 unshift @params, 'location';
1280         }
1281
1282         my $sub=pagespec_translate($spec);
1283         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1284         return $sub->($page, @params);
1285 } #}}}
1286
1287 sub pagespec_valid ($) { #{{{
1288         my $spec=shift;
1289
1290         my $sub=pagespec_translate($spec);
1291         return ! $@;
1292 } #}}}
1293         
1294 sub glob2re ($) { #{{{
1295         my $re=quotemeta(shift);
1296         $re=~s/\\\*/.*/g;
1297         $re=~s/\\\?/./g;
1298         return $re;
1299 } #}}}
1300
1301 package IkiWiki::FailReason;
1302
1303 use overload ( #{{{
1304         '""'    => sub { ${$_[0]} },
1305         '0+'    => sub { 0 },
1306         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1307         fallback => 1,
1308 ); #}}}
1309
1310 sub new { #{{{
1311         my $class = shift;
1312         my $value = shift;
1313         return bless \$value, $class;
1314 } #}}}
1315
1316 package IkiWiki::SuccessReason;
1317
1318 use overload ( #{{{
1319         '""'    => sub { ${$_[0]} },
1320         '0+'    => sub { 1 },
1321         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1322         fallback => 1,
1323 ); #}}}
1324
1325 sub new { #{{{
1326         my $class = shift;
1327         my $value = shift;
1328         return bless \$value, $class;
1329 }; #}}}
1330
1331 package IkiWiki::PageSpec;
1332
1333 sub match_glob ($$;@) { #{{{
1334         my $page=shift;
1335         my $glob=shift;
1336         my %params=@_;
1337         
1338         my $from=exists $params{location} ? $params{location} : '';
1339         
1340         # relative matching
1341         if ($glob =~ m!^\./!) {
1342                 $from=~s#/?[^/]+$##;
1343                 $glob=~s#^\./##;
1344                 $glob="$from/$glob" if length $from;
1345         }
1346
1347         my $regexp=IkiWiki::glob2re($glob);
1348         if ($page=~/^$regexp$/i) {
1349                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1350                         return IkiWiki::SuccessReason->new("$glob matches $page");
1351                 }
1352                 else {
1353                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1354                 }
1355         }
1356         else {
1357                 return IkiWiki::FailReason->new("$glob does not match $page");
1358         }
1359 } #}}}
1360
1361 sub match_internal ($$;@) { #{{{
1362         return match_glob($_[0], $_[1], @_, internal => 1)
1363 } #}}}
1364
1365 sub match_link ($$;@) { #{{{
1366         my $page=shift;
1367         my $link=lc(shift);
1368         my %params=@_;
1369
1370         my $from=exists $params{location} ? $params{location} : '';
1371
1372         # relative matching
1373         if ($link =~ m!^\.! && defined $from) {
1374                 $from=~s#/?[^/]+$##;
1375                 $link=~s#^\./##;
1376                 $link="$from/$link" if length $from;
1377         }
1378
1379         my $links = $IkiWiki::links{$page};
1380         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1381         my $bestlink = IkiWiki::bestlink($from, $link);
1382         foreach my $p (@{$links}) {
1383                 if (length $bestlink) {
1384                         return IkiWiki::SuccessReason->new("$page links to $link")
1385                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1386                 }
1387                 else {
1388                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1389                                 if match_glob($p, $link, %params);
1390                 }
1391         }
1392         return IkiWiki::FailReason->new("$page does not link to $link");
1393 } #}}}
1394
1395 sub match_backlink ($$;@) { #{{{
1396         return match_link($_[1], $_[0], @_);
1397 } #}}}
1398
1399 sub match_created_before ($$;@) { #{{{
1400         my $page=shift;
1401         my $testpage=shift;
1402
1403         if (exists $IkiWiki::pagectime{$testpage}) {
1404                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1405                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1406                 }
1407                 else {
1408                         return IkiWiki::FailReason->new("$page not created before $testpage");
1409                 }
1410         }
1411         else {
1412                 return IkiWiki::FailReason->new("$testpage has no ctime");
1413         }
1414 } #}}}
1415
1416 sub match_created_after ($$;@) { #{{{
1417         my $page=shift;
1418         my $testpage=shift;
1419
1420         if (exists $IkiWiki::pagectime{$testpage}) {
1421                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1422                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1423                 }
1424                 else {
1425                         return IkiWiki::FailReason->new("$page not created after $testpage");
1426                 }
1427         }
1428         else {
1429                 return IkiWiki::FailReason->new("$testpage has no ctime");
1430         }
1431 } #}}}
1432
1433 sub match_creation_day ($$;@) { #{{{
1434         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1435                 return IkiWiki::SuccessReason->new('creation_day matched');
1436         }
1437         else {
1438                 return IkiWiki::FailReason->new('creation_day did not match');
1439         }
1440 } #}}}
1441
1442 sub match_creation_month ($$;@) { #{{{
1443         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1444                 return IkiWiki::SuccessReason->new('creation_month matched');
1445         }
1446         else {
1447                 return IkiWiki::FailReason->new('creation_month did not match');
1448         }
1449 } #}}}
1450
1451 sub match_creation_year ($$;@) { #{{{
1452         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1453                 return IkiWiki::SuccessReason->new('creation_year matched');
1454         }
1455         else {
1456                 return IkiWiki::FailReason->new('creation_year did not match');
1457         }
1458 } #}}}
1459
1460 1