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