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