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