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