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