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