]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
ikiwiki-mass-rebuild: Fix tty hijacking vulnerability by using su. (Once su's related...
[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         foreach my $plugin (@{$config{plugin}}) {
155                 loadplugin($plugin);
156         }
158         run_hooks(getopt => sub { shift->() });
159         if (grep /^-/, @ARGV) {
160                 print STDERR "Unknown option: $_\n"
161                         foreach grep /^-/, @ARGV;
162                 usage();
163         }
165         return 1;
166 } #}}}
168 sub loadplugin ($) { #{{{
169         my $plugin=shift;
171         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
173         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
174                          "$installdir/lib/ikiwiki") {
175                 if (defined $dir && -x "$dir/plugins/$plugin") {
176                         require IkiWiki::Plugin::external;
177                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
178                         return 1;
179                 }
180         }
182         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
183         eval qq{use $mod};
184         if ($@) {
185                 error("Failed to load plugin $mod: $@");
186         }
187         return 1;
188 } #}}}
190 sub error ($;$) { #{{{
191         my $message=shift;
192         my $cleaner=shift;
193         if ($config{cgi}) {
194                 print "Content-type: text/html\n\n";
195                 print misctemplate(gettext("Error"),
196                         "<p>".gettext("Error").": $message</p>");
197         }
198         log_message('err' => $message) if $config{syslog};
199         if (defined $cleaner) {
200                 $cleaner->();
201         }
202         die $message."\n";
203 } #}}}
205 sub debug ($) { #{{{
206         return unless $config{verbose};
207         return log_message(debug => @_);
208 } #}}}
210 my $log_open=0;
211 sub log_message ($$) { #{{{
212         my $type=shift;
214         if ($config{syslog}) {
215                 require Sys::Syslog;
216                 if (! $log_open) {
217                         Sys::Syslog::setlogsock('unix');
218                         Sys::Syslog::openlog('ikiwiki', '', 'user');
219                         $log_open=1;
220                 }
221                 return eval {
222                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
223                 };
224         }
225         elsif (! $config{cgi}) {
226                 return print "@_\n";
227         }
228         else {
229                 return print STDERR "@_\n";
230         }
231 } #}}}
233 sub possibly_foolish_untaint ($) { #{{{
234         my $tainted=shift;
235         my ($untainted)=$tainted=~/(.*)/s;
236         return $untainted;
237 } #}}}
239 sub basename ($) { #{{{
240         my $file=shift;
242         $file=~s!.*/+!!;
243         return $file;
244 } #}}}
246 sub dirname ($) { #{{{
247         my $file=shift;
249         $file=~s!/*[^/]+$!!;
250         return $file;
251 } #}}}
253 sub pagetype ($) { #{{{
254         my $page=shift;
255         
256         if ($page =~ /\.([^.]+)$/) {
257                 return $1 if exists $hooks{htmlize}{$1};
258         }
259         return;
260 } #}}}
262 sub isinternal ($) { #{{{
263         my $page=shift;
264         return exists $pagesources{$page} &&
265                 $pagesources{$page} =~ /\._([^.]+)$/;
266 } #}}}
268 sub pagename ($) { #{{{
269         my $file=shift;
271         my $type=pagetype($file);
272         my $page=$file;
273         $page=~s/\Q.$type\E*$// if defined $type;
274         return $page;
275 } #}}}
277 sub targetpage ($$) { #{{{
278         my $page=shift;
279         my $ext=shift;
280         
281         if (! $config{usedirs} || $page =~ /^index$/ ) {
282                 return $page.".".$ext;
283         } else {
284                 return $page."/index.".$ext;
285         }
286 } #}}}
288 sub htmlpage ($) { #{{{
289         my $page=shift;
290         
291         return targetpage($page, $config{htmlext});
292 } #}}}
294 sub srcfile_stat { #{{{
295         my $file=shift;
296         my $nothrow=shift;
298         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
299         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
300                 return "$dir/$file", stat(_) if -e "$dir/$file";
301         }
302         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
303         return;
304 } #}}}
306 sub srcfile ($;$) { #{{{
307         return (srcfile_stat(@_))[0];
308 } #}}}
310 sub add_underlay ($) { #{{{
311         my $dir=shift;
313         if ($dir=~/^\//) {
314                 unshift @{$config{underlaydirs}}, $dir;
315         }
316         else {
317                 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
318         }
320         return 1;
321 } #}}}
323 sub readfile ($;$$) { #{{{
324         my $file=shift;
325         my $binary=shift;
326         my $wantfd=shift;
328         if (-l $file) {
329                 error("cannot read a symlink ($file)");
330         }
331         
332         local $/=undef;
333         open (my $in, "<", $file) || error("failed to read $file: $!");
334         binmode($in) if ($binary);
335         return \*$in if $wantfd;
336         my $ret=<$in>;
337         # check for invalid utf-8, and toss it back to avoid crashes
338         if (! utf8::valid($ret)) {
339                 $ret=encode_utf8($ret);
340         }
341         close $in || error("failed to read $file: $!");
342         return $ret;
343 } #}}}
345 sub prep_writefile ($$) {
346         my $file=shift;
347         my $destdir=shift;
348         
349         my $test=$file;
350         while (length $test) {
351                 if (-l "$destdir/$test") {
352                         error("cannot write to a symlink ($test)");
353                 }
354                 $test=dirname($test);
355         }
357         my $dir=dirname("$destdir/$file");
358         if (! -d $dir) {
359                 my $d="";
360                 foreach my $s (split(m!/+!, $dir)) {
361                         $d.="$s/";
362                         if (! -d $d) {
363                                 mkdir($d) || error("failed to create directory $d: $!");
364                         }
365                 }
366         }
368         return 1;
371 sub writefile ($$$;$$) { #{{{
372         my $file=shift; # can include subdirs
373         my $destdir=shift; # directory to put file in
374         my $content=shift;
375         my $binary=shift;
376         my $writer=shift;
377         
378         prep_writefile($file, $destdir);
379         
380         my $newfile="$destdir/$file.ikiwiki-new";
381         if (-l $newfile) {
382                 error("cannot write to a symlink ($newfile)");
383         }
384         
385         my $cleanup = sub { unlink($newfile) };
386         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
387         binmode($out) if ($binary);
388         if ($writer) {
389                 $writer->(\*$out, $cleanup);
390         }
391         else {
392                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
393         }
394         close $out || error("failed saving $newfile: $!", $cleanup);
395         rename($newfile, "$destdir/$file") || 
396                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
398         return 1;
399 } #}}}
401 my %cleared;
402 sub will_render ($$;$) { #{{{
403         my $page=shift;
404         my $dest=shift;
405         my $clear=shift;
407         # Important security check.
408         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
409             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
410                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
411         }
413         if (! $clear || $cleared{$page}) {
414                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
415         }
416         else {
417                 foreach my $old (@{$renderedfiles{$page}}) {
418                         delete $destsources{$old};
419                 }
420                 $renderedfiles{$page}=[$dest];
421                 $cleared{$page}=1;
422         }
423         $destsources{$dest}=$page;
425         return 1;
426 } #}}}
428 sub bestlink ($$) { #{{{
429         my $page=shift;
430         my $link=shift;
431         
432         my $cwd=$page;
433         if ($link=~s/^\/+//) {
434                 # absolute links
435                 $cwd="";
436         }
437         $link=~s/\/$//;
439         do {
440                 my $l=$cwd;
441                 $l.="/" if length $l;
442                 $l.=$link;
444                 if (exists $links{$l}) {
445                         return $l;
446                 }
447                 elsif (exists $pagecase{lc $l}) {
448                         return $pagecase{lc $l};
449                 }
450         } while $cwd=~s!/?[^/]+$!!;
452         if (length $config{userdir}) {
453                 my $l = "$config{userdir}/".lc($link);
454                 if (exists $links{$l}) {
455                         return $l;
456                 }
457                 elsif (exists $pagecase{lc $l}) {
458                         return $pagecase{lc $l};
459                 }
460         }
462         #print STDERR "warning: page $page, broken link: $link\n";
463         return "";
464 } #}}}
466 sub isinlinableimage ($) { #{{{
467         my $file=shift;
468         
469         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
470 } #}}}
472 sub pagetitle ($;$) { #{{{
473         my $page=shift;
474         my $unescaped=shift;
476         if ($unescaped) {
477                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
478         }
479         else {
480                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
481         }
483         return $page;
484 } #}}}
486 sub titlepage ($) { #{{{
487         my $title=shift;
488         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
489         return $title;
490 } #}}}
492 sub linkpage ($) { #{{{
493         my $link=shift;
494         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
495         return $link;
496 } #}}}
498 sub cgiurl (@) { #{{{
499         my %params=@_;
501         return $config{cgiurl}."?".
502                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
503 } #}}}
505 sub baseurl (;$) { #{{{
506         my $page=shift;
508         return "$config{url}/" if ! defined $page;
509         
510         $page=htmlpage($page);
511         $page=~s/[^\/]+$//;
512         $page=~s/[^\/]+\//..\//g;
513         return $page;
514 } #}}}
516 sub abs2rel ($$) { #{{{
517         # Work around very innefficient behavior in File::Spec if abs2rel
518         # is passed two relative paths. It's much faster if paths are
519         # absolute! (Debian bug #376658; fixed in debian unstable now)
520         my $path="/".shift;
521         my $base="/".shift;
523         require File::Spec;
524         my $ret=File::Spec->abs2rel($path, $base);
525         $ret=~s/^// if defined $ret;
526         return $ret;
527 } #}}}
529 sub displaytime ($;$) { #{{{
530         my $time=shift;
531         my $format=shift;
532         if (! defined $format) {
533                 $format=$config{timeformat};
534         }
536         # strftime doesn't know about encodings, so make sure
537         # its output is properly treated as utf8
538         return decode_utf8(POSIX::strftime($format, localtime($time)));
539 } #}}}
541 sub beautify_url ($) { #{{{
542         my $url=shift;
544         if ($config{usedirs}) {
545                 $url =~ s!/index.$config{htmlext}$!/!;
546         }
548         # Ensure url is not an empty link, and
549         # if it's relative, make that explicit to avoid colon confusion.
550         if ($url !~ /^\//) {
551                 $url="./$url";
552         }
554         return $url;
555 } #}}}
557 sub urlto ($$;$) { #{{{
558         my $to=shift;
559         my $from=shift;
560         my $absolute=shift;
561         
562         if (! length $to) {
563                 return beautify_url(baseurl($from)."index.$config{htmlext}");
564         }
566         if (! $destsources{$to}) {
567                 $to=htmlpage($to);
568         }
570         if ($absolute) {
571                 return $config{url}.beautify_url("/".$to);
572         }
574         my $link = abs2rel($to, dirname(htmlpage($from)));
576         return beautify_url($link);
577 } #}}}
579 sub htmllink ($$$;@) { #{{{
580         my $lpage=shift; # the page doing the linking
581         my $page=shift; # the page that will contain the link (different for inline)
582         my $link=shift;
583         my %opts=@_;
585         $link=~s/\/$//;
587         my $bestlink;
588         if (! $opts{forcesubpage}) {
589                 $bestlink=bestlink($lpage, $link);
590         }
591         else {
592                 $bestlink="$lpage/".lc($link);
593         }
595         my $linktext;
596         if (defined $opts{linktext}) {
597                 $linktext=$opts{linktext};
598         }
599         else {
600                 $linktext=pagetitle(basename($link));
601         }
602         
603         return "<span class=\"selflink\">$linktext</span>"
604                 if length $bestlink && $page eq $bestlink &&
605                    ! defined $opts{anchor};
606         
607         if (! $destsources{$bestlink}) {
608                 $bestlink=htmlpage($bestlink);
610                 if (! $destsources{$bestlink}) {
611                         return $linktext unless length $config{cgiurl};
612                         return "<span class=\"createlink\"><a href=\"".
613                                 cgiurl(
614                                         do => "create",
615                                         page => lc($link),
616                                         from => $lpage
617                                 ).
618                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
619                 }
620         }
621         
622         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
623         $bestlink=beautify_url($bestlink);
624         
625         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
626                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
627         }
629         if (defined $opts{anchor}) {
630                 $bestlink.="#".$opts{anchor};
631         }
633         my @attrs;
634         if (defined $opts{rel}) {
635                 push @attrs, ' rel="'.$opts{rel}.'"';
636         }
637         if (defined $opts{class}) {
638                 push @attrs, ' class="'.$opts{class}.'"';
639         }
641         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
642 } #}}}
644 sub userlink ($) { #{{{
645         my $user=shift;
647         my $oiduser=eval { openiduser($user) };
648         if (defined $oiduser) {
649                 return "<a href=\"$user\">$oiduser</a>";
650         }
651         else {
652                 eval q{use CGI 'escapeHTML'};
653                 error($@) if $@;
655                 return htmllink("", "", escapeHTML(
656                         length $config{userdir} ? $config{userdir}."/".$user : $user
657                 ), noimageinline => 1);
658         }
659 } #}}}
661 sub htmlize ($$$$) { #{{{
662         my $page=shift;
663         my $destpage=shift;
664         my $type=shift;
665         my $content=shift;
666         
667         my $oneline = $content !~ /\n/;
669         if (exists $hooks{htmlize}{$type}) {
670                 $content=$hooks{htmlize}{$type}{call}->(
671                         page => $page,
672                         content => $content,
673                 );
674         }
675         else {
676                 error("htmlization of $type not supported");
677         }
679         run_hooks(sanitize => sub {
680                 $content=shift->(
681                         page => $page,
682                         destpage => $destpage,
683                         content => $content,
684                 );
685         });
686         
687         if ($oneline) {
688                 # hack to get rid of enclosing junk added by markdown
689                 # and other htmlizers
690                 $content=~s/^<p>//i;
691                 $content=~s/<\/p>$//i;
692                 chomp $content;
693         }
695         return $content;
696 } #}}}
698 sub linkify ($$$) { #{{{
699         my $page=shift;
700         my $destpage=shift;
701         my $content=shift;
703         run_hooks(linkify => sub {
704                 $content=shift->(
705                         page => $page,
706                         destpage => $destpage,
707                         content => $content,
708                 );
709         });
710         
711         return $content;
712 } #}}}
714 our %preprocessing;
715 our $preprocess_preview=0;
716 sub preprocess ($$$;$$) { #{{{
717         my $page=shift; # the page the data comes from
718         my $destpage=shift; # the page the data will appear in (different for inline)
719         my $content=shift;
720         my $scan=shift;
721         my $preview=shift;
723         # Using local because it needs to be set within any nested calls
724         # of this function.
725         local $preprocess_preview=$preview if defined $preview;
727         my $handle=sub {
728                 my $escape=shift;
729                 my $prefix=shift;
730                 my $command=shift;
731                 my $params=shift;
732                 $params="" if ! defined $params;
734                 if (length $escape) {
735                         return "[[$prefix$command $params]]";
736                 }
737                 elsif (exists $hooks{preprocess}{$command}) {
738                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
739                         # Note: preserve order of params, some plugins may
740                         # consider it significant.
741                         my @params;
742                         while ($params =~ m{
743                                 (?:([-\w]+)=)?          # 1: named parameter key?
744                                 (?:
745                                         """(.*?)"""     # 2: triple-quoted value
746                                 |
747                                         "([^"]+)"       # 3: single-quoted value
748                                 |
749                                         (\S+)           # 4: unquoted value
750                                 )
751                                 (?:\s+|$)               # delimiter to next param
752                         }sgx) {
753                                 my $key=$1;
754                                 my $val;
755                                 if (defined $2) {
756                                         $val=$2;
757                                         $val=~s/\r\n/\n/mg;
758                                         $val=~s/^\n+//g;
759                                         $val=~s/\n+$//g;
760                                 }
761                                 elsif (defined $3) {
762                                         $val=$3;
763                                 }
764                                 elsif (defined $4) {
765                                         $val=$4;
766                                 }
768                                 if (defined $key) {
769                                         push @params, $key, $val;
770                                 }
771                                 else {
772                                         push @params, $val, '';
773                                 }
774                         }
775                         if ($preprocessing{$page}++ > 3) {
776                                 # Avoid loops of preprocessed pages preprocessing
777                                 # other pages that preprocess them, etc.
778                                 #translators: The first parameter is a
779                                 #translators: preprocessor directive name,
780                                 #translators: the second a page name, the
781                                 #translators: third a number.
782                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
783                                         $command, $page, $preprocessing{$page}).
784                                 "]]";
785                         }
786                         my $ret;
787                         if (! $scan) {
788                                 $ret=$hooks{preprocess}{$command}{call}->(
789                                         @params,
790                                         page => $page,
791                                         destpage => $destpage,
792                                         preview => $preprocess_preview,
793                                 );
794                         }
795                         else {
796                                 # use void context during scan pass
797                                 $hooks{preprocess}{$command}{call}->(
798                                         @params,
799                                         page => $page,
800                                         destpage => $destpage,
801                                         preview => $preprocess_preview,
802                                 );
803                                 $ret="";
804                         }
805                         $preprocessing{$page}--;
806                         return $ret;
807                 }
808                 else {
809                         return "[[$prefix$command $params]]";
810                 }
811         };
812         
813         my $regex;
814         if ($config{prefix_directives}) {
815                 $regex = qr{
816                         (\\?)           # 1: escape?
817                         \[\[(!)         # directive open; 2: prefix
818                         ([-\w]+)        # 3: command
819                         (               # 4: the parameters..
820                                 \s+     # Must have space if parameters present
821                                 (?:
822                                         (?:[-\w]+=)?            # named parameter key?
823                                         (?:
824                                                 """.*?"""       # triple-quoted value
825                                                 |
826                                                 "[^"]+"         # single-quoted value
827                                                 |
828                                                 [^\s\]]+        # unquoted value
829                                         )
830                                         \s*                     # whitespace or end
831                                                                 # of directive
832                                 )
833                         *)?             # 0 or more parameters
834                         \]\]            # directive closed
835                 }sx;
836         } else {
837                 $regex = qr{
838                         (\\?)           # 1: escape?
839                         \[\[(!?)        # directive open; 2: optional prefix
840                         ([-\w]+)        # 3: command
841                         \s+
842                         (               # 4: the parameters..
843                                 (?:
844                                         (?:[-\w]+=)?            # named parameter key?
845                                         (?:
846                                                 """.*?"""       # triple-quoted value
847                                                 |
848                                                 "[^"]+"         # single-quoted value
849                                                 |
850                                                 [^\s\]]+        # unquoted value
851                                         )
852                                         \s*                     # whitespace or end
853                                                                 # of directive
854                                 )
855                         *)              # 0 or more parameters
856                         \]\]            # directive closed
857                 }sx;
858         }
860         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
861         return $content;
862 } #}}}
864 sub filter ($$$) { #{{{
865         my $page=shift;
866         my $destpage=shift;
867         my $content=shift;
869         run_hooks(filter => sub {
870                 $content=shift->(page => $page, destpage => $destpage, 
871                         content => $content);
872         });
874         return $content;
875 } #}}}
877 sub indexlink () { #{{{
878         return "<a href=\"$config{url}\">$config{wikiname}</a>";
879 } #}}}
881 my $wikilock;
883 sub lockwiki (;$) { #{{{
884         my $wait=@_ ? shift : 1;
885         # Take an exclusive lock on the wiki to prevent multiple concurrent
886         # run issues. The lock will be dropped on program exit.
887         if (! -d $config{wikistatedir}) {
888                 mkdir($config{wikistatedir});
889         }
890         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
891                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
892         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
893                 if ($wait) {
894                         debug("wiki seems to be locked, waiting for lock");
895                         my $wait=600; # arbitrary, but don't hang forever to 
896                                       # prevent process pileup
897                         for (1..$wait) {
898                                 return if flock($wikilock, 2 | 4);
899                                 sleep 1;
900                         }
901                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
902                 }
903                 else {
904                         return 0;
905                 }
906         }
907         return 1;
908 } #}}}
910 sub unlockwiki () { #{{{
911         return close($wikilock) if $wikilock;
912         return;
913 } #}}}
915 my $commitlock;
917 sub commit_hook_enabled () { #{{{
918         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
919                 error("cannot write to $config{wikistatedir}/commitlock: $!");
920         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
921                 close($commitlock) || error("failed closing commitlock: $!");
922                 return 0;
923         }
924         close($commitlock) || error("failed closing commitlock: $!");
925         return 1;
926 } #}}}
928 sub disable_commit_hook () { #{{{
929         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
930                 error("cannot write to $config{wikistatedir}/commitlock: $!");
931         if (! flock($commitlock, 2)) { # LOCK_EX
932                 error("failed to get commit lock");
933         }
934         return 1;
935 } #}}}
937 sub enable_commit_hook () { #{{{
938         return close($commitlock) if $commitlock;
939         return;
940 } #}}}
942 sub loadindex () { #{{{
943         %oldrenderedfiles=%pagectime=();
944         if (! $config{rebuild}) {
945                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
946                 %destsources=%renderedfiles=%pagecase=%pagestate=();
947         }
948         my $in;
949         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
950                 if (-e "$config{wikistatedir}/index") {
951                         system("ikiwiki-transition", "indexdb", $config{srcdir});
952                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
953                 }
954                 else {
955                         return;
956                 }
957         }
958         my $ret=Storable::fd_retrieve($in);
959         if (! defined $ret) {
960                 return 0;
961         }
962         my %index=%$ret;
963         foreach my $src (keys %index) {
964                 my %d=%{$index{$src}};
965                 my $page=pagename($src);
966                 $pagectime{$page}=$d{ctime};
967                 if (! $config{rebuild}) {
968                         $pagesources{$page}=$src;
969                         $pagemtime{$page}=$d{mtime};
970                         $renderedfiles{$page}=$d{dest};
971                         if (exists $d{links} && ref $d{links}) {
972                                 $links{$page}=$d{links};
973                                 $oldlinks{$page}=[@{$d{links}}];
974                         }
975                         if (exists $d{depends}) {
976                                 $depends{$page}=$d{depends};
977                         }
978                         if (exists $d{state}) {
979                                 $pagestate{$page}=$d{state};
980                         }
981                 }
982                 $oldrenderedfiles{$page}=[@{$d{dest}}];
983         }
984         foreach my $page (keys %pagesources) {
985                 $pagecase{lc $page}=$page;
986         }
987         foreach my $page (keys %renderedfiles) {
988                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
989         }
990         return close($in);
991 } #}}}
993 sub saveindex () { #{{{
994         run_hooks(savestate => sub { shift->() });
996         my %hookids;
997         foreach my $type (keys %hooks) {
998                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
999         }
1000         my @hookids=keys %hookids;
1002         if (! -d $config{wikistatedir}) {
1003                 mkdir($config{wikistatedir});
1004         }
1005         my $newfile="$config{wikistatedir}/indexdb.new";
1006         my $cleanup = sub { unlink($newfile) };
1007         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1008         my %index;
1009         foreach my $page (keys %pagemtime) {
1010                 next unless $pagemtime{$page};
1011                 my $src=$pagesources{$page};
1013                 $index{$src}={
1014                         ctime => $pagectime{$page},
1015                         mtime => $pagemtime{$page},
1016                         dest => $renderedfiles{$page},
1017                         links => $links{$page},
1018                 };
1020                 if (exists $depends{$page}) {
1021                         $index{$src}{depends} = $depends{$page};
1022                 }
1024                 if (exists $pagestate{$page}) {
1025                         foreach my $id (@hookids) {
1026                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1027                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1028                                 }
1029                         }
1030                 }
1031         }
1032         my $ret=Storable::nstore_fd(\%index, $out);
1033         return if ! defined $ret || ! $ret;
1034         close $out || error("failed saving to $newfile: $!", $cleanup);
1035         rename($newfile, "$config{wikistatedir}/indexdb") ||
1036                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1037         
1038         return 1;
1039 } #}}}
1041 sub template_file ($) { #{{{
1042         my $template=shift;
1044         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1045                 return "$dir/$template" if -e "$dir/$template";
1046         }
1047         return;
1048 } #}}}
1050 sub template_params (@) { #{{{
1051         my $filename=template_file(shift);
1053         if (! defined $filename) {
1054                 return if wantarray;
1055                 return "";
1056         }
1058         my @ret=(
1059                 filter => sub {
1060                         my $text_ref = shift;
1061                         ${$text_ref} = decode_utf8(${$text_ref});
1062                 },
1063                 filename => $filename,
1064                 loop_context_vars => 1,
1065                 die_on_bad_params => 0,
1066                 @_
1067         );
1068         return wantarray ? @ret : {@ret};
1069 } #}}}
1071 sub template ($;@) { #{{{
1072         require HTML::Template;
1073         return HTML::Template->new(template_params(@_));
1074 } #}}}
1076 sub misctemplate ($$;@) { #{{{
1077         my $title=shift;
1078         my $pagebody=shift;
1079         
1080         my $template=template("misc.tmpl");
1081         $template->param(
1082                 title => $title,
1083                 indexlink => indexlink(),
1084                 wikiname => $config{wikiname},
1085                 pagebody => $pagebody,
1086                 baseurl => baseurl(),
1087                 @_,
1088         );
1089         run_hooks(pagetemplate => sub {
1090                 shift->(page => "", destpage => "", template => $template);
1091         });
1092         return $template->output;
1093 }#}}}
1095 sub hook (@) { # {{{
1096         my %param=@_;
1097         
1098         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1099                 error 'hook requires type, call, and id parameters';
1100         }
1102         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1103         
1104         $hooks{$param{type}}{$param{id}}=\%param;
1105         return 1;
1106 } # }}}
1108 sub run_hooks ($$) { # {{{
1109         # Calls the given sub for each hook of the given type,
1110         # passing it the hook function to call.
1111         my $type=shift;
1112         my $sub=shift;
1114         if (exists $hooks{$type}) {
1115                 my @deferred;
1116                 foreach my $id (keys %{$hooks{$type}}) {
1117                         if ($hooks{$type}{$id}{last}) {
1118                                 push @deferred, $id;
1119                                 next;
1120                         }
1121                         $sub->($hooks{$type}{$id}{call});
1122                 }
1123                 foreach my $id (@deferred) {
1124                         $sub->($hooks{$type}{$id}{call});
1125                 }
1126         }
1128         return 1;
1129 } #}}}
1131 sub globlist_to_pagespec ($) { #{{{
1132         my @globlist=split(' ', shift);
1134         my (@spec, @skip);
1135         foreach my $glob (@globlist) {
1136                 if ($glob=~/^!(.*)/) {
1137                         push @skip, $glob;
1138                 }
1139                 else {
1140                         push @spec, $glob;
1141                 }
1142         }
1144         my $spec=join(' or ', @spec);
1145         if (@skip) {
1146                 my $skip=join(' and ', @skip);
1147                 if (length $spec) {
1148                         $spec="$skip and ($spec)";
1149                 }
1150                 else {
1151                         $spec=$skip;
1152                 }
1153         }
1154         return $spec;
1155 } #}}}
1157 sub is_globlist ($) { #{{{
1158         my $s=shift;
1159         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1160 } #}}}
1162 sub safequote ($) { #{{{
1163         my $s=shift;
1164         $s=~s/[{}]//g;
1165         return "q{$s}";
1166 } #}}}
1168 sub add_depends ($$) { #{{{
1169         my $page=shift;
1170         my $pagespec=shift;
1171         
1172         return unless pagespec_valid($pagespec);
1174         if (! exists $depends{$page}) {
1175                 $depends{$page}=$pagespec;
1176         }
1177         else {
1178                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1179         }
1181         return 1;
1182 } # }}}
1184 sub file_pruned ($$) { #{{{
1185         require File::Spec;
1186         my $file=File::Spec->canonpath(shift);
1187         my $base=File::Spec->canonpath(shift);
1188         $file =~ s#^\Q$base\E/+##;
1190         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1191         return $file =~ m/$regexp/ && $file ne $base;
1192 } #}}}
1194 sub gettext { #{{{
1195         # Only use gettext in the rare cases it's needed.
1196         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1197             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1198             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1199                 if (! $gettext_obj) {
1200                         $gettext_obj=eval q{
1201                                 use Locale::gettext q{textdomain};
1202                                 Locale::gettext->domain('ikiwiki')
1203                         };
1204                         if ($@) {
1205                                 print STDERR "$@";
1206                                 $gettext_obj=undef;
1207                                 return shift;
1208                         }
1209                 }
1210                 return $gettext_obj->get(shift);
1211         }
1212         else {
1213                 return shift;
1214         }
1215 } #}}}
1217 sub pagespec_merge ($$) { #{{{
1218         my $a=shift;
1219         my $b=shift;
1221         return $a if $a eq $b;
1223         # Support for old-style GlobLists.
1224         if (is_globlist($a)) {
1225                 $a=globlist_to_pagespec($a);
1226         }
1227         if (is_globlist($b)) {
1228                 $b=globlist_to_pagespec($b);
1229         }
1231         return "($a) or ($b)";
1232 } #}}}
1234 sub pagespec_translate ($) { #{{{
1235         my $spec=shift;
1237         # Support for old-style GlobLists.
1238         if (is_globlist($spec)) {
1239                 $spec=globlist_to_pagespec($spec);
1240         }
1242         # Convert spec to perl code.
1243         my $code="";
1244         while ($spec=~m{
1245                 \s*             # ignore whitespace
1246                 (               # 1: match a single word
1247                         \!              # !
1248                 |
1249                         \(              # (
1250                 |
1251                         \)              # )
1252                 |
1253                         \w+\([^\)]*\)   # command(params)
1254                 |
1255                         [^\s()]+        # any other text
1256                 )
1257                 \s*             # ignore whitespace
1258         }igx) {
1259                 my $word=$1;
1260                 if (lc $word eq 'and') {
1261                         $code.=' &&';
1262                 }
1263                 elsif (lc $word eq 'or') {
1264                         $code.=' ||';
1265                 }
1266                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1267                         $code.=' '.$word;
1268                 }
1269                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1270                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1271                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1272                         }
1273                         else {
1274                                 $code.=' 0';
1275                         }
1276                 }
1277                 else {
1278                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1279                 }
1280         }
1282         if (! length $code) {
1283                 $code=0;
1284         }
1286         no warnings;
1287         return eval 'sub { my $page=shift; '.$code.' }';
1288 } #}}}
1290 sub pagespec_match ($$;@) { #{{{
1291         my $page=shift;
1292         my $spec=shift;
1293         my @params=@_;
1295         # Backwards compatability with old calling convention.
1296         if (@params == 1) {
1297                 unshift @params, 'location';
1298         }
1300         my $sub=pagespec_translate($spec);
1301         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1302         return $sub->($page, @params);
1303 } #}}}
1305 sub pagespec_valid ($) { #{{{
1306         my $spec=shift;
1308         my $sub=pagespec_translate($spec);
1309         return ! $@;
1310 } #}}}
1311         
1312 sub glob2re ($) { #{{{
1313         my $re=quotemeta(shift);
1314         $re=~s/\\\*/.*/g;
1315         $re=~s/\\\?/./g;
1316         return $re;
1317 } #}}}
1319 package IkiWiki::FailReason;
1321 use overload ( #{{{
1322         '""'    => sub { ${$_[0]} },
1323         '0+'    => sub { 0 },
1324         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1325         fallback => 1,
1326 ); #}}}
1328 sub new { #{{{
1329         my $class = shift;
1330         my $value = shift;
1331         return bless \$value, $class;
1332 } #}}}
1334 package IkiWiki::SuccessReason;
1336 use overload ( #{{{
1337         '""'    => sub { ${$_[0]} },
1338         '0+'    => sub { 1 },
1339         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1340         fallback => 1,
1341 ); #}}}
1343 sub new { #{{{
1344         my $class = shift;
1345         my $value = shift;
1346         return bless \$value, $class;
1347 }; #}}}
1349 package IkiWiki::PageSpec;
1351 sub match_glob ($$;@) { #{{{
1352         my $page=shift;
1353         my $glob=shift;
1354         my %params=@_;
1355         
1356         my $from=exists $params{location} ? $params{location} : '';
1357         
1358         # relative matching
1359         if ($glob =~ m!^\./!) {
1360                 $from=~s#/?[^/]+$##;
1361                 $glob=~s#^\./##;
1362                 $glob="$from/$glob" if length $from;
1363         }
1365         my $regexp=IkiWiki::glob2re($glob);
1366         if ($page=~/^$regexp$/i) {
1367                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1368                         return IkiWiki::SuccessReason->new("$glob matches $page");
1369                 }
1370                 else {
1371                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1372                 }
1373         }
1374         else {
1375                 return IkiWiki::FailReason->new("$glob does not match $page");
1376         }
1377 } #}}}
1379 sub match_internal ($$;@) { #{{{
1380         return match_glob($_[0], $_[1], @_, internal => 1)
1381 } #}}}
1383 sub match_link ($$;@) { #{{{
1384         my $page=shift;
1385         my $link=lc(shift);
1386         my %params=@_;
1388         my $from=exists $params{location} ? $params{location} : '';
1390         # relative matching
1391         if ($link =~ m!^\.! && defined $from) {
1392                 $from=~s#/?[^/]+$##;
1393                 $link=~s#^\./##;
1394                 $link="$from/$link" if length $from;
1395         }
1397         my $links = $IkiWiki::links{$page};
1398         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1399         my $bestlink = IkiWiki::bestlink($from, $link);
1400         foreach my $p (@{$links}) {
1401                 if (length $bestlink) {
1402                         return IkiWiki::SuccessReason->new("$page links to $link")
1403                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1404                 }
1405                 else {
1406                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1407                                 if match_glob($p, $link, %params);
1408                 }
1409         }
1410         return IkiWiki::FailReason->new("$page does not link to $link");
1411 } #}}}
1413 sub match_backlink ($$;@) { #{{{
1414         return match_link($_[1], $_[0], @_);
1415 } #}}}
1417 sub match_created_before ($$;@) { #{{{
1418         my $page=shift;
1419         my $testpage=shift;
1421         if (exists $IkiWiki::pagectime{$testpage}) {
1422                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1423                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1424                 }
1425                 else {
1426                         return IkiWiki::FailReason->new("$page not created before $testpage");
1427                 }
1428         }
1429         else {
1430                 return IkiWiki::FailReason->new("$testpage has no ctime");
1431         }
1432 } #}}}
1434 sub match_created_after ($$;@) { #{{{
1435         my $page=shift;
1436         my $testpage=shift;
1438         if (exists $IkiWiki::pagectime{$testpage}) {
1439                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1440                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1441                 }
1442                 else {
1443                         return IkiWiki::FailReason->new("$page not created after $testpage");
1444                 }
1445         }
1446         else {
1447                 return IkiWiki::FailReason->new("$testpage has no ctime");
1448         }
1449 } #}}}
1451 sub match_creation_day ($$;@) { #{{{
1452         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1453                 return IkiWiki::SuccessReason->new('creation_day matched');
1454         }
1455         else {
1456                 return IkiWiki::FailReason->new('creation_day did not match');
1457         }
1458 } #}}}
1460 sub match_creation_month ($$;@) { #{{{
1461         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1462                 return IkiWiki::SuccessReason->new('creation_month matched');
1463         }
1464         else {
1465                 return IkiWiki::FailReason->new('creation_month did not match');
1466         }
1467 } #}}}
1469 sub match_creation_year ($$;@) { #{{{
1470         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1471                 return IkiWiki::SuccessReason->new('creation_year matched');
1472         }
1473         else {
1474                 return IkiWiki::FailReason->new('creation_year did not match');
1475         }
1476 } #}}}