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