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