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