]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
Split out error messages from editpage.tmpl into several separate templates.
[ikiwiki.git] / 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=eval {
773                                         $hooks{preprocess}{$command}{call}->(
774                                                 @params,
775                                                 page => $page,
776                                                 destpage => $destpage,
777                                                 preview => $preprocess_preview,
778                                         );
779                                 };
780                                 if ($@) {
781                                         chomp $@;
782                                         $ret="[[!$command <span class=\"error\">".
783                                                 gettext("Error").": $@"."</span>]]";
784                                 }
785                         }
786                         else {
787                                 # use void context during scan pass
788                                 eval {
789                                         $hooks{preprocess}{$command}{call}->(
790                                                 @params,
791                                                 page => $page,
792                                                 destpage => $destpage,
793                                                 preview => $preprocess_preview,
794                                         );
795                                 };
796                                 $ret="";
797                         }
798                         $preprocessing{$page}--;
799                         return $ret;
800                 }
801                 else {
802                         return "[[$prefix$command $params]]";
803                 }
804         };
805         
806         my $regex;
807         if ($config{prefix_directives}) {
808                 $regex = qr{
809                         (\\?)           # 1: escape?
810                         \[\[(!)         # directive open; 2: prefix
811                         ([-\w]+)        # 3: command
812                         (               # 4: the parameters..
813                                 \s+     # Must have space if parameters present
814                                 (?:
815                                         (?:[-\w]+=)?            # named parameter key?
816                                         (?:
817                                                 """.*?"""       # triple-quoted value
818                                                 |
819                                                 "[^"]+"         # single-quoted value
820                                                 |
821                                                 [^\s\]]+        # unquoted value
822                                         )
823                                         \s*                     # whitespace or end
824                                                                 # of directive
825                                 )
826                         *)?             # 0 or more parameters
827                         \]\]            # directive closed
828                 }sx;
829         }
830         else {
831                 $regex = qr{
832                         (\\?)           # 1: escape?
833                         \[\[(!?)        # directive open; 2: optional prefix
834                         ([-\w]+)        # 3: command
835                         \s+
836                         (               # 4: the parameters..
837                                 (?:
838                                         (?:[-\w]+=)?            # named parameter key?
839                                         (?:
840                                                 """.*?"""       # triple-quoted value
841                                                 |
842                                                 "[^"]+"         # single-quoted value
843                                                 |
844                                                 [^\s\]]+        # unquoted value
845                                         )
846                                         \s*                     # whitespace or end
847                                                                 # of directive
848                                 )
849                         *)              # 0 or more parameters
850                         \]\]            # directive closed
851                 }sx;
852         }
853
854         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
855         return $content;
856 } #}}}
857
858 sub filter ($$$) { #{{{
859         my $page=shift;
860         my $destpage=shift;
861         my $content=shift;
862
863         run_hooks(filter => sub {
864                 $content=shift->(page => $page, destpage => $destpage, 
865                         content => $content);
866         });
867
868         return $content;
869 } #}}}
870
871 sub indexlink () { #{{{
872         return "<a href=\"$config{url}\">$config{wikiname}</a>";
873 } #}}}
874
875 my $wikilock;
876
877 sub lockwiki (;$) { #{{{
878         my $wait=@_ ? shift : 1;
879         # Take an exclusive lock on the wiki to prevent multiple concurrent
880         # run issues. The lock will be dropped on program exit.
881         if (! -d $config{wikistatedir}) {
882                 mkdir($config{wikistatedir});
883         }
884         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
885                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
886         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
887                 if ($wait) {
888                         debug("wiki seems to be locked, waiting for lock");
889                         my $wait=600; # arbitrary, but don't hang forever to 
890                                       # prevent process pileup
891                         for (1..$wait) {
892                                 return if flock($wikilock, 2 | 4);
893                                 sleep 1;
894                         }
895                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
896                 }
897                 else {
898                         return 0;
899                 }
900         }
901         return 1;
902 } #}}}
903
904 sub unlockwiki () { #{{{
905         return close($wikilock) if $wikilock;
906         return;
907 } #}}}
908
909 my $commitlock;
910
911 sub commit_hook_enabled () { #{{{
912         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
913                 error("cannot write to $config{wikistatedir}/commitlock: $!");
914         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
915                 close($commitlock) || error("failed closing commitlock: $!");
916                 return 0;
917         }
918         close($commitlock) || error("failed closing commitlock: $!");
919         return 1;
920 } #}}}
921
922 sub disable_commit_hook () { #{{{
923         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
924                 error("cannot write to $config{wikistatedir}/commitlock: $!");
925         if (! flock($commitlock, 2)) { # LOCK_EX
926                 error("failed to get commit lock");
927         }
928         return 1;
929 } #}}}
930
931 sub enable_commit_hook () { #{{{
932         return close($commitlock) if $commitlock;
933         return;
934 } #}}}
935
936 sub loadindex () { #{{{
937         %oldrenderedfiles=%pagectime=();
938         if (! $config{rebuild}) {
939                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
940                 %destsources=%renderedfiles=%pagecase=%pagestate=();
941         }
942         my $in;
943         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
944                 if (-e "$config{wikistatedir}/index") {
945                         system("ikiwiki-transition", "indexdb", $config{srcdir});
946                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
947                 }
948                 else {
949                         return;
950                 }
951         }
952         my $ret=Storable::fd_retrieve($in);
953         if (! defined $ret) {
954                 return 0;
955         }
956         my %index=%$ret;
957         foreach my $src (keys %index) {
958                 my %d=%{$index{$src}};
959                 my $page=pagename($src);
960                 $pagectime{$page}=$d{ctime};
961                 if (! $config{rebuild}) {
962                         $pagesources{$page}=$src;
963                         $pagemtime{$page}=$d{mtime};
964                         $renderedfiles{$page}=$d{dest};
965                         if (exists $d{links} && ref $d{links}) {
966                                 $links{$page}=$d{links};
967                                 $oldlinks{$page}=[@{$d{links}}];
968                         }
969                         if (exists $d{depends}) {
970                                 $depends{$page}=$d{depends};
971                         }
972                         if (exists $d{state}) {
973                                 $pagestate{$page}=$d{state};
974                         }
975                 }
976                 $oldrenderedfiles{$page}=[@{$d{dest}}];
977         }
978         foreach my $page (keys %pagesources) {
979                 $pagecase{lc $page}=$page;
980         }
981         foreach my $page (keys %renderedfiles) {
982                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
983         }
984         return close($in);
985 } #}}}
986
987 sub saveindex () { #{{{
988         run_hooks(savestate => sub { shift->() });
989
990         my %hookids;
991         foreach my $type (keys %hooks) {
992                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
993         }
994         my @hookids=keys %hookids;
995
996         if (! -d $config{wikistatedir}) {
997                 mkdir($config{wikistatedir});
998         }
999         my $newfile="$config{wikistatedir}/indexdb.new";
1000         my $cleanup = sub { unlink($newfile) };
1001         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1002         my %index;
1003         foreach my $page (keys %pagemtime) {
1004                 next unless $pagemtime{$page};
1005                 my $src=$pagesources{$page};
1006
1007                 $index{$src}={
1008                         ctime => $pagectime{$page},
1009                         mtime => $pagemtime{$page},
1010                         dest => $renderedfiles{$page},
1011                         links => $links{$page},
1012                 };
1013
1014                 if (exists $depends{$page}) {
1015                         $index{$src}{depends} = $depends{$page};
1016                 }
1017
1018                 if (exists $pagestate{$page}) {
1019                         foreach my $id (@hookids) {
1020                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1021                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1022                                 }
1023                         }
1024                 }
1025         }
1026         my $ret=Storable::nstore_fd(\%index, $out);
1027         return if ! defined $ret || ! $ret;
1028         close $out || error("failed saving to $newfile: $!", $cleanup);
1029         rename($newfile, "$config{wikistatedir}/indexdb") ||
1030                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1031         
1032         return 1;
1033 } #}}}
1034
1035 sub template_file ($) { #{{{
1036         my $template=shift;
1037
1038         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1039                 return "$dir/$template" if -e "$dir/$template";
1040         }
1041         return;
1042 } #}}}
1043
1044 sub template_params (@) { #{{{
1045         my $filename=template_file(shift);
1046
1047         if (! defined $filename) {
1048                 return if wantarray;
1049                 return "";
1050         }
1051
1052         my @ret=(
1053                 filter => sub {
1054                         my $text_ref = shift;
1055                         ${$text_ref} = decode_utf8(${$text_ref});
1056                 },
1057                 filename => $filename,
1058                 loop_context_vars => 1,
1059                 die_on_bad_params => 0,
1060                 @_
1061         );
1062         return wantarray ? @ret : {@ret};
1063 } #}}}
1064
1065 sub template ($;@) { #{{{
1066         require HTML::Template;
1067         return HTML::Template->new(template_params(@_));
1068 } #}}}
1069
1070 sub misctemplate ($$;@) { #{{{
1071         my $title=shift;
1072         my $pagebody=shift;
1073         
1074         my $template=template("misc.tmpl");
1075         $template->param(
1076                 title => $title,
1077                 indexlink => indexlink(),
1078                 wikiname => $config{wikiname},
1079                 pagebody => $pagebody,
1080                 baseurl => baseurl(),
1081                 @_,
1082         );
1083         run_hooks(pagetemplate => sub {
1084                 shift->(page => "", destpage => "", template => $template);
1085         });
1086         return $template->output;
1087 }#}}}
1088
1089 sub hook (@) { # {{{
1090         my %param=@_;
1091         
1092         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1093                 error 'hook requires type, call, and id parameters';
1094         }
1095
1096         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1097         
1098         $hooks{$param{type}}{$param{id}}=\%param;
1099         return 1;
1100 } # }}}
1101
1102 sub run_hooks ($$) { # {{{
1103         # Calls the given sub for each hook of the given type,
1104         # passing it the hook function to call.
1105         my $type=shift;
1106         my $sub=shift;
1107
1108         if (exists $hooks{$type}) {
1109                 my @deferred;
1110                 foreach my $id (keys %{$hooks{$type}}) {
1111                         if ($hooks{$type}{$id}{last}) {
1112                                 push @deferred, $id;
1113                                 next;
1114                         }
1115                         $sub->($hooks{$type}{$id}{call});
1116                 }
1117                 foreach my $id (@deferred) {
1118                         $sub->($hooks{$type}{$id}{call});
1119                 }
1120         }
1121
1122         return 1;
1123 } #}}}
1124
1125 sub globlist_to_pagespec ($) { #{{{
1126         my @globlist=split(' ', shift);
1127
1128         my (@spec, @skip);
1129         foreach my $glob (@globlist) {
1130                 if ($glob=~/^!(.*)/) {
1131                         push @skip, $glob;
1132                 }
1133                 else {
1134                         push @spec, $glob;
1135                 }
1136         }
1137
1138         my $spec=join(' or ', @spec);
1139         if (@skip) {
1140                 my $skip=join(' and ', @skip);
1141                 if (length $spec) {
1142                         $spec="$skip and ($spec)";
1143                 }
1144                 else {
1145                         $spec=$skip;
1146                 }
1147         }
1148         return $spec;
1149 } #}}}
1150
1151 sub is_globlist ($) { #{{{
1152         my $s=shift;
1153         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1154 } #}}}
1155
1156 sub safequote ($) { #{{{
1157         my $s=shift;
1158         $s=~s/[{}]//g;
1159         return "q{$s}";
1160 } #}}}
1161
1162 sub add_depends ($$) { #{{{
1163         my $page=shift;
1164         my $pagespec=shift;
1165         
1166         return unless pagespec_valid($pagespec);
1167
1168         if (! exists $depends{$page}) {
1169                 $depends{$page}=$pagespec;
1170         }
1171         else {
1172                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1173         }
1174
1175         return 1;
1176 } # }}}
1177
1178 sub file_pruned ($$) { #{{{
1179         require File::Spec;
1180         my $file=File::Spec->canonpath(shift);
1181         my $base=File::Spec->canonpath(shift);
1182         $file =~ s#^\Q$base\E/+##;
1183
1184         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1185         return $file =~ m/$regexp/ && $file ne $base;
1186 } #}}}
1187
1188 sub gettext { #{{{
1189         # Only use gettext in the rare cases it's needed.
1190         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1191             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1192             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1193                 if (! $gettext_obj) {
1194                         $gettext_obj=eval q{
1195                                 use Locale::gettext q{textdomain};
1196                                 Locale::gettext->domain('ikiwiki')
1197                         };
1198                         if ($@) {
1199                                 print STDERR "$@";
1200                                 $gettext_obj=undef;
1201                                 return shift;
1202                         }
1203                 }
1204                 return $gettext_obj->get(shift);
1205         }
1206         else {
1207                 return shift;
1208         }
1209 } #}}}
1210
1211 sub yesno ($) { #{{{
1212         my $val=shift;
1213
1214         return (defined $val && lc($val) eq gettext("yes"));
1215 } #}}}
1216
1217 sub pagespec_merge ($$) { #{{{
1218         my $a=shift;
1219         my $b=shift;
1220
1221         return $a if $a eq $b;
1222
1223         # Support for old-style GlobLists.
1224         if (is_globlist($a)) {
1225                 $a=globlist_to_pagespec($a);
1226         }
1227         if (is_globlist($b)) {
1228                 $b=globlist_to_pagespec($b);
1229         }
1230
1231         return "($a) or ($b)";
1232 } #}}}
1233
1234 sub pagespec_translate ($) { #{{{
1235         my $spec=shift;
1236
1237         # Support for old-style GlobLists.
1238         if (is_globlist($spec)) {
1239                 $spec=globlist_to_pagespec($spec);
1240         }
1241
1242         # Convert spec to perl code.
1243         my $code="";
1244         while ($spec=~m{
1245                 \s*             # ignore whitespace
1246                 (               # 1: match a single word
1247                         \!              # !
1248                 |
1249                         \(              # (
1250                 |
1251                         \)              # )
1252                 |
1253                         \w+\([^\)]*\)   # command(params)
1254                 |
1255                         [^\s()]+        # any other text
1256                 )
1257                 \s*             # ignore whitespace
1258         }igx) {
1259                 my $word=$1;
1260                 if (lc $word eq 'and') {
1261                         $code.=' &&';
1262                 }
1263                 elsif (lc $word eq 'or') {
1264                         $code.=' ||';
1265                 }
1266                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1267                         $code.=' '.$word;
1268                 }
1269                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1270                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1271                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1272                         }
1273                         else {
1274                                 $code.=' 0';
1275                         }
1276                 }
1277                 else {
1278                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1279                 }
1280         }
1281
1282         if (! length $code) {
1283                 $code=0;
1284         }
1285
1286         no warnings;
1287         return eval 'sub { my $page=shift; '.$code.' }';
1288 } #}}}
1289
1290 sub pagespec_match ($$;@) { #{{{
1291         my $page=shift;
1292         my $spec=shift;
1293         my @params=@_;
1294
1295         # Backwards compatability with old calling convention.
1296         if (@params == 1) {
1297                 unshift @params, 'location';
1298         }
1299
1300         my $sub=pagespec_translate($spec);
1301         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1302         return $sub->($page, @params);
1303 } #}}}
1304
1305 sub pagespec_valid ($) { #{{{
1306         my $spec=shift;
1307
1308         my $sub=pagespec_translate($spec);
1309         return ! $@;
1310 } #}}}
1311         
1312 sub glob2re ($) { #{{{
1313         my $re=quotemeta(shift);
1314         $re=~s/\\\*/.*/g;
1315         $re=~s/\\\?/./g;
1316         return $re;
1317 } #}}}
1318
1319 package IkiWiki::FailReason;
1320
1321 use overload ( #{{{
1322         '""'    => sub { ${$_[0]} },
1323         '0+'    => sub { 0 },
1324         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1325         fallback => 1,
1326 ); #}}}
1327
1328 sub new { #{{{
1329         my $class = shift;
1330         my $value = shift;
1331         return bless \$value, $class;
1332 } #}}}
1333
1334 package IkiWiki::SuccessReason;
1335
1336 use overload ( #{{{
1337         '""'    => sub { ${$_[0]} },
1338         '0+'    => sub { 1 },
1339         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1340         fallback => 1,
1341 ); #}}}
1342
1343 sub new { #{{{
1344         my $class = shift;
1345         my $value = shift;
1346         return bless \$value, $class;
1347 }; #}}}
1348
1349 package IkiWiki::PageSpec;
1350
1351 sub match_glob ($$;@) { #{{{
1352         my $page=shift;
1353         my $glob=shift;
1354         my %params=@_;
1355         
1356         my $from=exists $params{location} ? $params{location} : '';
1357         
1358         # relative matching
1359         if ($glob =~ m!^\./!) {
1360                 $from=~s#/?[^/]+$##;
1361                 $glob=~s#^\./##;
1362                 $glob="$from/$glob" if length $from;
1363         }
1364
1365         my $regexp=IkiWiki::glob2re($glob);
1366         if ($page=~/^$regexp$/i) {
1367                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1368                         return IkiWiki::SuccessReason->new("$glob matches $page");
1369                 }
1370                 else {
1371                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1372                 }
1373         }
1374         else {
1375                 return IkiWiki::FailReason->new("$glob does not match $page");
1376         }
1377 } #}}}
1378
1379 sub match_internal ($$;@) { #{{{
1380         return match_glob($_[0], $_[1], @_, internal => 1)
1381 } #}}}
1382
1383 sub match_link ($$;@) { #{{{
1384         my $page=shift;
1385         my $link=lc(shift);
1386         my %params=@_;
1387
1388         my $from=exists $params{location} ? $params{location} : '';
1389
1390         # relative matching
1391         if ($link =~ m!^\.! && defined $from) {
1392                 $from=~s#/?[^/]+$##;
1393                 $link=~s#^\./##;
1394                 $link="$from/$link" if length $from;
1395         }
1396
1397         my $links = $IkiWiki::links{$page};
1398         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1399         my $bestlink = IkiWiki::bestlink($from, $link);
1400         foreach my $p (@{$links}) {
1401                 if (length $bestlink) {
1402                         return IkiWiki::SuccessReason->new("$page links to $link")
1403                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1404                 }
1405                 else {
1406                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1407                                 if match_glob($p, $link, %params);
1408                 }
1409         }
1410         return IkiWiki::FailReason->new("$page does not link to $link");
1411 } #}}}
1412
1413 sub match_backlink ($$;@) { #{{{
1414         return match_link($_[1], $_[0], @_);
1415 } #}}}
1416
1417 sub match_created_before ($$;@) { #{{{
1418         my $page=shift;
1419         my $testpage=shift;
1420
1421         if (exists $IkiWiki::pagectime{$testpage}) {
1422                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1423                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1424                 }
1425                 else {
1426                         return IkiWiki::FailReason->new("$page not created before $testpage");
1427                 }
1428         }
1429         else {
1430                 return IkiWiki::FailReason->new("$testpage has no ctime");
1431         }
1432 } #}}}
1433
1434 sub match_created_after ($$;@) { #{{{
1435         my $page=shift;
1436         my $testpage=shift;
1437
1438         if (exists $IkiWiki::pagectime{$testpage}) {
1439                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1440                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1441                 }
1442                 else {
1443                         return IkiWiki::FailReason->new("$page not created after $testpage");
1444                 }
1445         }
1446         else {
1447                 return IkiWiki::FailReason->new("$testpage has no ctime");
1448         }
1449 } #}}}
1450
1451 sub match_creation_day ($$;@) { #{{{
1452         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1453                 return IkiWiki::SuccessReason->new('creation_day matched');
1454         }
1455         else {
1456                 return IkiWiki::FailReason->new('creation_day did not match');
1457         }
1458 } #}}}
1459
1460 sub match_creation_month ($$;@) { #{{{
1461         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1462                 return IkiWiki::SuccessReason->new('creation_month matched');
1463         }
1464         else {
1465                 return IkiWiki::FailReason->new('creation_month did not match');
1466         }
1467 } #}}}
1468
1469 sub match_creation_year ($$;@) { #{{{
1470         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1471                 return IkiWiki::SuccessReason->new('creation_year matched');
1472         }
1473         else {
1474                 return IkiWiki::FailReason->new('creation_year did not match');
1475         }
1476 } #}}}
1477
1478 1