pedigree rename to parentlinks: rename/adapt everything
[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
552         if (! length $to) {
553                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
554         }
555
556         if (! $destsources{$to}) {
557                 $to=htmlpage($to);
558         }
559
560         my $link = abs2rel($to, dirname(htmlpage($from)));
561
562         return beautify_urlpath($link);
563 } #}}}
564
565 sub htmllink ($$$;@) { #{{{
566         my $lpage=shift; # the page doing the linking
567         my $page=shift; # the page that will contain the link (different for inline)
568         my $link=shift;
569         my %opts=@_;
570
571         $link=~s/\/$//;
572
573         my $bestlink;
574         if (! $opts{forcesubpage}) {
575                 $bestlink=bestlink($lpage, $link);
576         }
577         else {
578                 $bestlink="$lpage/".lc($link);
579         }
580
581         my $linktext;
582         if (defined $opts{linktext}) {
583                 $linktext=$opts{linktext};
584         }
585         else {
586                 $linktext=pagetitle(basename($link));
587         }
588         
589         return "<span class=\"selflink\">$linktext</span>"
590                 if length $bestlink && $page eq $bestlink &&
591                    ! defined $opts{anchor};
592         
593         if (! $destsources{$bestlink}) {
594                 $bestlink=htmlpage($bestlink);
595
596                 if (! $destsources{$bestlink}) {
597                         return $linktext unless length $config{cgiurl};
598                         return "<span class=\"createlink\"><a href=\"".
599                                 cgiurl(
600                                         do => "create",
601                                         page => lc($link),
602                                         from => $lpage
603                                 ).
604                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
605                 }
606         }
607         
608         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
609         $bestlink=beautify_urlpath($bestlink);
610         
611         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
612                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
613         }
614
615         if (defined $opts{anchor}) {
616                 $bestlink.="#".$opts{anchor};
617         }
618
619         my @attrs;
620         if (defined $opts{rel}) {
621                 push @attrs, ' rel="'.$opts{rel}.'"';
622         }
623         if (defined $opts{class}) {
624                 push @attrs, ' class="'.$opts{class}.'"';
625         }
626
627         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
628 } #}}}
629
630 sub userlink ($) { #{{{
631         my $user=shift;
632
633         my $oiduser=eval { openiduser($user) };
634         if (defined $oiduser) {
635                 return "<a href=\"$user\">$oiduser</a>";
636         }
637         else {
638                 eval q{use CGI 'escapeHTML'};
639                 error($@) if $@;
640
641                 return htmllink("", "", escapeHTML(
642                         length $config{userdir} ? $config{userdir}."/".$user : $user
643                 ), noimageinline => 1);
644         }
645 } #}}}
646
647 sub htmlize ($$$$) { #{{{
648         my $page=shift;
649         my $destpage=shift;
650         my $type=shift;
651         my $content=shift;
652         
653         my $oneline = $content !~ /\n/;
654
655         if (exists $hooks{htmlize}{$type}) {
656                 $content=$hooks{htmlize}{$type}{call}->(
657                         page => $page,
658                         content => $content,
659                 );
660         }
661         else {
662                 error("htmlization of $type not supported");
663         }
664
665         run_hooks(sanitize => sub {
666                 $content=shift->(
667                         page => $page,
668                         destpage => $destpage,
669                         content => $content,
670                 );
671         });
672         
673         if ($oneline) {
674                 # hack to get rid of enclosing junk added by markdown
675                 # and other htmlizers
676                 $content=~s/^<p>//i;
677                 $content=~s/<\/p>$//i;
678                 chomp $content;
679         }
680
681         return $content;
682 } #}}}
683
684 sub linkify ($$$) { #{{{
685         my $page=shift;
686         my $destpage=shift;
687         my $content=shift;
688
689         run_hooks(linkify => sub {
690                 $content=shift->(
691                         page => $page,
692                         destpage => $destpage,
693                         content => $content,
694                 );
695         });
696         
697         return $content;
698 } #}}}
699
700 our %preprocessing;
701 our $preprocess_preview=0;
702 sub preprocess ($$$;$$) { #{{{
703         my $page=shift; # the page the data comes from
704         my $destpage=shift; # the page the data will appear in (different for inline)
705         my $content=shift;
706         my $scan=shift;
707         my $preview=shift;
708
709         # Using local because it needs to be set within any nested calls
710         # of this function.
711         local $preprocess_preview=$preview if defined $preview;
712
713         my $handle=sub {
714                 my $escape=shift;
715                 my $prefix=shift;
716                 my $command=shift;
717                 my $params=shift;
718                 if (length $escape) {
719                         return "[[$prefix$command $params]]";
720                 }
721                 elsif (exists $hooks{preprocess}{$command}) {
722                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
723                         # Note: preserve order of params, some plugins may
724                         # consider it significant.
725                         my @params;
726                         while ($params =~ m{
727                                 (?:([-\w]+)=)?          # 1: named parameter key?
728                                 (?:
729                                         """(.*?)"""     # 2: triple-quoted value
730                                 |
731                                         "([^"]+)"       # 3: single-quoted value
732                                 |
733                                         (\S+)           # 4: unquoted value
734                                 )
735                                 (?:\s+|$)               # delimiter to next param
736                         }sgx) {
737                                 my $key=$1;
738                                 my $val;
739                                 if (defined $2) {
740                                         $val=$2;
741                                         $val=~s/\r\n/\n/mg;
742                                         $val=~s/^\n+//g;
743                                         $val=~s/\n+$//g;
744                                 }
745                                 elsif (defined $3) {
746                                         $val=$3;
747                                 }
748                                 elsif (defined $4) {
749                                         $val=$4;
750                                 }
751
752                                 if (defined $key) {
753                                         push @params, $key, $val;
754                                 }
755                                 else {
756                                         push @params, $val, '';
757                                 }
758                         }
759                         if ($preprocessing{$page}++ > 3) {
760                                 # Avoid loops of preprocessed pages preprocessing
761                                 # other pages that preprocess them, etc.
762                                 #translators: The first parameter is a
763                                 #translators: preprocessor directive name,
764                                 #translators: the second a page name, the
765                                 #translators: third a number.
766                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
767                                         $command, $page, $preprocessing{$page}).
768                                 "]]";
769                         }
770                         my $ret;
771                         if (! $scan) {
772                                 $ret=$hooks{preprocess}{$command}{call}->(
773                                         @params,
774                                         page => $page,
775                                         destpage => $destpage,
776                                         preview => $preprocess_preview,
777                                 );
778                         }
779                         else {
780                                 # use void context during scan pass
781                                 $hooks{preprocess}{$command}{call}->(
782                                         @params,
783                                         page => $page,
784                                         destpage => $destpage,
785                                         preview => $preprocess_preview,
786                                 );
787                                 $ret="";
788                         }
789                         $preprocessing{$page}--;
790                         return $ret;
791                 }
792                 else {
793                         return "[[$prefix$command $params]]";
794                 }
795         };
796         
797         my $regex;
798         if ($config{prefix_directives}) {
799                 $regex = qr{
800                         (\\?)           # 1: escape?
801                         \[\[(!)         # directive open; 2: prefix
802                         ([-\w]+)        # 3: command
803                         (               # 4: the parameters..
804                                 \s+     # Must have space if parameters present
805                                 (?:
806                                         (?:[-\w]+=)?            # named parameter key?
807                                         (?:
808                                                 """.*?"""       # triple-quoted value
809                                                 |
810                                                 "[^"]+"         # single-quoted value
811                                                 |
812                                                 [^\s\]]+        # unquoted value
813                                         )
814                                         \s*                     # whitespace or end
815                                                                 # of directive
816                                 )
817                         *)?             # 0 or more parameters
818                         \]\]            # directive closed
819                 }sx;
820         } else {
821                 $regex = qr{
822                         (\\?)           # 1: escape?
823                         \[\[(!?)        # directive open; 2: optional prefix
824                         ([-\w]+)        # 3: command
825                         \s+
826                         (               # 4: the parameters..
827                                 (?:
828                                         (?:[-\w]+=)?            # named parameter key?
829                                         (?:
830                                                 """.*?"""       # triple-quoted value
831                                                 |
832                                                 "[^"]+"         # single-quoted value
833                                                 |
834                                                 [^\s\]]+        # unquoted value
835                                         )
836                                         \s*                     # whitespace or end
837                                                                 # of directive
838                                 )
839                         *)              # 0 or more parameters
840                         \]\]            # directive closed
841                 }sx;
842         }
843
844         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
845         return $content;
846 } #}}}
847
848 sub filter ($$$) { #{{{
849         my $page=shift;
850         my $destpage=shift;
851         my $content=shift;
852
853         run_hooks(filter => sub {
854                 $content=shift->(page => $page, destpage => $destpage, 
855                         content => $content);
856         });
857
858         return $content;
859 } #}}}
860
861 sub indexlink () { #{{{
862         return "<a href=\"$config{url}\">$config{wikiname}</a>";
863 } #}}}
864
865 my $wikilock;
866
867 sub lockwiki (;$) { #{{{
868         my $wait=@_ ? shift : 1;
869         # Take an exclusive lock on the wiki to prevent multiple concurrent
870         # run issues. The lock will be dropped on program exit.
871         if (! -d $config{wikistatedir}) {
872                 mkdir($config{wikistatedir});
873         }
874         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
875                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
876         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
877                 if ($wait) {
878                         debug("wiki seems to be locked, waiting for lock");
879                         my $wait=600; # arbitrary, but don't hang forever to 
880                                       # prevent process pileup
881                         for (1..$wait) {
882                                 return if flock($wikilock, 2 | 4);
883                                 sleep 1;
884                         }
885                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
886                 }
887                 else {
888                         return 0;
889                 }
890         }
891         return 1;
892 } #}}}
893
894 sub unlockwiki () { #{{{
895         return close($wikilock) if $wikilock;
896         return;
897 } #}}}
898
899 my $commitlock;
900
901 sub commit_hook_enabled () { #{{{
902         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
903                 error("cannot write to $config{wikistatedir}/commitlock: $!");
904         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
905                 close($commitlock) || error("failed closing commitlock: $!");
906                 return 0;
907         }
908         close($commitlock) || error("failed closing commitlock: $!");
909         return 1;
910 } #}}}
911
912 sub disable_commit_hook () { #{{{
913         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
914                 error("cannot write to $config{wikistatedir}/commitlock: $!");
915         if (! flock($commitlock, 2)) { # LOCK_EX
916                 error("failed to get commit lock");
917         }
918         return 1;
919 } #}}}
920
921 sub enable_commit_hook () { #{{{
922         return close($commitlock) if $commitlock;
923         return;
924 } #}}}
925
926 sub loadindex () { #{{{
927         %oldrenderedfiles=%pagectime=();
928         if (! $config{rebuild}) {
929                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
930                 %destsources=%renderedfiles=%pagecase=%pagestate=();
931         }
932         my $in;
933         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
934                 if (-e "$config{wikistatedir}/index") {
935                         system("ikiwiki-transition", "indexdb", $config{srcdir});
936                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
937                 }
938                 else {
939                         return;
940                 }
941         }
942         my $ret=Storable::fd_retrieve($in);
943         if (! defined $ret) {
944                 return 0;
945         }
946         my %index=%$ret;
947         foreach my $src (keys %index) {
948                 my %d=%{$index{$src}};
949                 my $page=pagename($src);
950                 $pagectime{$page}=$d{ctime};
951                 if (! $config{rebuild}) {
952                         $pagesources{$page}=$src;
953                         $pagemtime{$page}=$d{mtime};
954                         $renderedfiles{$page}=$d{dest};
955                         if (exists $d{links} && ref $d{links}) {
956                                 $links{$page}=$d{links};
957                                 $oldlinks{$page}=[@{$d{links}}];
958                         }
959                         if (exists $d{depends}) {
960                                 $depends{$page}=$d{depends};
961                         }
962                         if (exists $d{state}) {
963                                 $pagestate{$page}=$d{state};
964                         }
965                 }
966                 $oldrenderedfiles{$page}=[@{$d{dest}}];
967         }
968         foreach my $page (keys %pagesources) {
969                 $pagecase{lc $page}=$page;
970         }
971         foreach my $page (keys %renderedfiles) {
972                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
973         }
974         return close($in);
975 } #}}}
976
977 sub saveindex () { #{{{
978         run_hooks(savestate => sub { shift->() });
979
980         my %hookids;
981         foreach my $type (keys %hooks) {
982                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
983         }
984         my @hookids=keys %hookids;
985
986         if (! -d $config{wikistatedir}) {
987                 mkdir($config{wikistatedir});
988         }
989         my $newfile="$config{wikistatedir}/indexdb.new";
990         my $cleanup = sub { unlink($newfile) };
991         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
992         my %index;
993         foreach my $page (keys %pagemtime) {
994                 next unless $pagemtime{$page};
995                 my $src=$pagesources{$page};
996
997                 $index{$src}={
998                         ctime => $pagectime{$page},
999                         mtime => $pagemtime{$page},
1000                         dest => $renderedfiles{$page},
1001                         links => $links{$page},
1002                 };
1003
1004                 if (exists $depends{$page}) {
1005                         $index{$src}{depends} = $depends{$page};
1006                 }
1007
1008                 if (exists $pagestate{$page}) {
1009                         foreach my $id (@hookids) {
1010                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1011                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1012                                 }
1013                         }
1014                 }
1015         }
1016         my $ret=Storable::nstore_fd(\%index, $out);
1017         return if ! defined $ret || ! $ret;
1018         close $out || error("failed saving to $newfile: $!", $cleanup);
1019         rename($newfile, "$config{wikistatedir}/indexdb") ||
1020                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1021         
1022         return 1;
1023 } #}}}
1024
1025 sub template_file ($) { #{{{
1026         my $template=shift;
1027
1028         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1029                 return "$dir/$template" if -e "$dir/$template";
1030         }
1031         return;
1032 } #}}}
1033
1034 sub template_params (@) { #{{{
1035         my $filename=template_file(shift);
1036
1037         if (! defined $filename) {
1038                 return if wantarray;
1039                 return "";
1040         }
1041
1042         my @ret=(
1043                 filter => sub {
1044                         my $text_ref = shift;
1045                         ${$text_ref} = decode_utf8(${$text_ref});
1046                 },
1047                 filename => $filename,
1048                 loop_context_vars => 1,
1049                 die_on_bad_params => 0,
1050                 @_
1051         );
1052         return wantarray ? @ret : {@ret};
1053 } #}}}
1054
1055 sub template ($;@) { #{{{
1056         require HTML::Template;
1057         return HTML::Template->new(template_params(@_));
1058 } #}}}
1059
1060 sub misctemplate ($$;@) { #{{{
1061         my $title=shift;
1062         my $pagebody=shift;
1063         
1064         my $template=template("misc.tmpl");
1065         $template->param(
1066                 title => $title,
1067                 indexlink => indexlink(),
1068                 wikiname => $config{wikiname},
1069                 pagebody => $pagebody,
1070                 baseurl => baseurl(),
1071                 @_,
1072         );
1073         run_hooks(pagetemplate => sub {
1074                 shift->(page => "", destpage => "", template => $template);
1075         });
1076         return $template->output;
1077 }#}}}
1078
1079 sub hook (@) { # {{{
1080         my %param=@_;
1081         
1082         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1083                 error 'hook requires type, call, and id parameters';
1084         }
1085
1086         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1087         
1088         $hooks{$param{type}}{$param{id}}=\%param;
1089         return 1;
1090 } # }}}
1091
1092 sub run_hooks ($$) { # {{{
1093         # Calls the given sub for each hook of the given type,
1094         # passing it the hook function to call.
1095         my $type=shift;
1096         my $sub=shift;
1097
1098         if (exists $hooks{$type}) {
1099                 my @deferred;
1100                 foreach my $id (keys %{$hooks{$type}}) {
1101                         if ($hooks{$type}{$id}{last}) {
1102                                 push @deferred, $id;
1103                                 next;
1104                         }
1105                         $sub->($hooks{$type}{$id}{call});
1106                 }
1107                 foreach my $id (@deferred) {
1108                         $sub->($hooks{$type}{$id}{call});
1109                 }
1110         }
1111
1112         return 1;
1113 } #}}}
1114
1115 sub globlist_to_pagespec ($) { #{{{
1116         my @globlist=split(' ', shift);
1117
1118         my (@spec, @skip);
1119         foreach my $glob (@globlist) {
1120                 if ($glob=~/^!(.*)/) {
1121                         push @skip, $glob;
1122                 }
1123                 else {
1124                         push @spec, $glob;
1125                 }
1126         }
1127
1128         my $spec=join(' or ', @spec);
1129         if (@skip) {
1130                 my $skip=join(' and ', @skip);
1131                 if (length $spec) {
1132                         $spec="$skip and ($spec)";
1133                 }
1134                 else {
1135                         $spec=$skip;
1136                 }
1137         }
1138         return $spec;
1139 } #}}}
1140
1141 sub is_globlist ($) { #{{{
1142         my $s=shift;
1143         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1144 } #}}}
1145
1146 sub safequote ($) { #{{{
1147         my $s=shift;
1148         $s=~s/[{}]//g;
1149         return "q{$s}";
1150 } #}}}
1151
1152 sub add_depends ($$) { #{{{
1153         my $page=shift;
1154         my $pagespec=shift;
1155         
1156         return unless pagespec_valid($pagespec);
1157
1158         if (! exists $depends{$page}) {
1159                 $depends{$page}=$pagespec;
1160         }
1161         else {
1162                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1163         }
1164
1165         return 1;
1166 } # }}}
1167
1168 sub file_pruned ($$) { #{{{
1169         require File::Spec;
1170         my $file=File::Spec->canonpath(shift);
1171         my $base=File::Spec->canonpath(shift);
1172         $file =~ s#^\Q$base\E/+##;
1173
1174         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1175         return $file =~ m/$regexp/ && $file ne $base;
1176 } #}}}
1177
1178 sub gettext { #{{{
1179         # Only use gettext in the rare cases it's needed.
1180         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1181             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1182             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1183                 if (! $gettext_obj) {
1184                         $gettext_obj=eval q{
1185                                 use Locale::gettext q{textdomain};
1186                                 Locale::gettext->domain('ikiwiki')
1187                         };
1188                         if ($@) {
1189                                 print STDERR "$@";
1190                                 $gettext_obj=undef;
1191                                 return shift;
1192                         }
1193                 }
1194                 return $gettext_obj->get(shift);
1195         }
1196         else {
1197                 return shift;
1198         }
1199 } #}}}
1200
1201 sub yesno ($) { #{{{
1202         my $val=shift;
1203
1204         return (defined $val && lc($val) eq gettext("yes"));
1205 } #}}}
1206
1207 sub pagespec_merge ($$) { #{{{
1208         my $a=shift;
1209         my $b=shift;
1210
1211         return $a if $a eq $b;
1212
1213         # Support for old-style GlobLists.
1214         if (is_globlist($a)) {
1215                 $a=globlist_to_pagespec($a);
1216         }
1217         if (is_globlist($b)) {
1218                 $b=globlist_to_pagespec($b);
1219         }
1220
1221         return "($a) or ($b)";
1222 } #}}}
1223
1224 sub pagespec_translate ($) { #{{{
1225         my $spec=shift;
1226
1227         # Support for old-style GlobLists.
1228         if (is_globlist($spec)) {
1229                 $spec=globlist_to_pagespec($spec);
1230         }
1231
1232         # Convert spec to perl code.
1233         my $code="";
1234         while ($spec=~m{
1235                 \s*             # ignore whitespace
1236                 (               # 1: match a single word
1237                         \!              # !
1238                 |
1239                         \(              # (
1240                 |
1241                         \)              # )
1242                 |
1243                         \w+\([^\)]*\)   # command(params)
1244                 |
1245                         [^\s()]+        # any other text
1246                 )
1247                 \s*             # ignore whitespace
1248         }igx) {
1249                 my $word=$1;
1250                 if (lc $word eq 'and') {
1251                         $code.=' &&';
1252                 }
1253                 elsif (lc $word eq 'or') {
1254                         $code.=' ||';
1255                 }
1256                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1257                         $code.=' '.$word;
1258                 }
1259                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1260                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1261                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1262                         }
1263                         else {
1264                                 $code.=' 0';
1265                         }
1266                 }
1267                 else {
1268                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1269                 }
1270         }
1271
1272         if (! length $code) {
1273                 $code=0;
1274         }
1275
1276         no warnings;
1277         return eval 'sub { my $page=shift; '.$code.' }';
1278 } #}}}
1279
1280 sub pagespec_match ($$;@) { #{{{
1281         my $page=shift;
1282         my $spec=shift;
1283         my @params=@_;
1284
1285         # Backwards compatability with old calling convention.
1286         if (@params == 1) {
1287                 unshift @params, 'location';
1288         }
1289
1290         my $sub=pagespec_translate($spec);
1291         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1292         return $sub->($page, @params);
1293 } #}}}
1294
1295 sub pagespec_valid ($) { #{{{
1296         my $spec=shift;
1297
1298         my $sub=pagespec_translate($spec);
1299         return ! $@;
1300 } #}}}
1301         
1302 sub glob2re ($) { #{{{
1303         my $re=quotemeta(shift);
1304         $re=~s/\\\*/.*/g;
1305         $re=~s/\\\?/./g;
1306         return $re;
1307 } #}}}
1308
1309 package IkiWiki::FailReason;
1310
1311 use overload ( #{{{
1312         '""'    => sub { ${$_[0]} },
1313         '0+'    => sub { 0 },
1314         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1315         fallback => 1,
1316 ); #}}}
1317
1318 sub new { #{{{
1319         my $class = shift;
1320         my $value = shift;
1321         return bless \$value, $class;
1322 } #}}}
1323
1324 package IkiWiki::SuccessReason;
1325
1326 use overload ( #{{{
1327         '""'    => sub { ${$_[0]} },
1328         '0+'    => sub { 1 },
1329         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
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::PageSpec;
1340
1341 sub match_glob ($$;@) { #{{{
1342         my $page=shift;
1343         my $glob=shift;
1344         my %params=@_;
1345         
1346         my $from=exists $params{location} ? $params{location} : '';
1347         
1348         # relative matching
1349         if ($glob =~ m!^\./!) {
1350                 $from=~s#/?[^/]+$##;
1351                 $glob=~s#^\./##;
1352                 $glob="$from/$glob" if length $from;
1353         }
1354
1355         my $regexp=IkiWiki::glob2re($glob);
1356         if ($page=~/^$regexp$/i) {
1357                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1358                         return IkiWiki::SuccessReason->new("$glob matches $page");
1359                 }
1360                 else {
1361                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1362                 }
1363         }
1364         else {
1365                 return IkiWiki::FailReason->new("$glob does not match $page");
1366         }
1367 } #}}}
1368
1369 sub match_internal ($$;@) { #{{{
1370         return match_glob($_[0], $_[1], @_, internal => 1)
1371 } #}}}
1372
1373 sub match_link ($$;@) { #{{{
1374         my $page=shift;
1375         my $link=lc(shift);
1376         my %params=@_;
1377
1378         my $from=exists $params{location} ? $params{location} : '';
1379
1380         # relative matching
1381         if ($link =~ m!^\.! && defined $from) {
1382                 $from=~s#/?[^/]+$##;
1383                 $link=~s#^\./##;
1384                 $link="$from/$link" if length $from;
1385         }
1386
1387         my $links = $IkiWiki::links{$page};
1388         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1389         my $bestlink = IkiWiki::bestlink($from, $link);
1390         foreach my $p (@{$links}) {
1391                 if (length $bestlink) {
1392                         return IkiWiki::SuccessReason->new("$page links to $link")
1393                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1394                 }
1395                 else {
1396                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1397                                 if match_glob($p, $link, %params);
1398                 }
1399         }
1400         return IkiWiki::FailReason->new("$page does not link to $link");
1401 } #}}}
1402
1403 sub match_backlink ($$;@) { #{{{
1404         return match_link($_[1], $_[0], @_);
1405 } #}}}
1406
1407 sub match_created_before ($$;@) { #{{{
1408         my $page=shift;
1409         my $testpage=shift;
1410
1411         if (exists $IkiWiki::pagectime{$testpage}) {
1412                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1413                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1414                 }
1415                 else {
1416                         return IkiWiki::FailReason->new("$page not created before $testpage");
1417                 }
1418         }
1419         else {
1420                 return IkiWiki::FailReason->new("$testpage has no ctime");
1421         }
1422 } #}}}
1423
1424 sub match_created_after ($$;@) { #{{{
1425         my $page=shift;
1426         my $testpage=shift;
1427
1428         if (exists $IkiWiki::pagectime{$testpage}) {
1429                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1430                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1431                 }
1432                 else {
1433                         return IkiWiki::FailReason->new("$page not created after $testpage");
1434                 }
1435         }
1436         else {
1437                 return IkiWiki::FailReason->new("$testpage has no ctime");
1438         }
1439 } #}}}
1440
1441 sub match_creation_day ($$;@) { #{{{
1442         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1443                 return IkiWiki::SuccessReason->new('creation_day matched');
1444         }
1445         else {
1446                 return IkiWiki::FailReason->new('creation_day did not match');
1447         }
1448 } #}}}
1449
1450 sub match_creation_month ($$;@) { #{{{
1451         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1452                 return IkiWiki::SuccessReason->new('creation_month matched');
1453         }
1454         else {
1455                 return IkiWiki::FailReason->new('creation_month did not match');
1456         }
1457 } #}}}
1458
1459 sub match_creation_year ($$;@) { #{{{
1460         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1461                 return IkiWiki::SuccessReason->new('creation_year matched');
1462         }
1463         else {
1464                 return IkiWiki::FailReason->new('creation_year did not match');
1465         }
1466 } #}}}
1467
1468 1