]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
releasing version 2.53.1
[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         close $in || error("failed to read $file: $!");
338         return $ret;
339 } #}}}
341 sub prep_writefile ($$) {
342         my $file=shift;
343         my $destdir=shift;
344         
345         my $test=$file;
346         while (length $test) {
347                 if (-l "$destdir/$test") {
348                         error("cannot write to a symlink ($test)");
349                 }
350                 $test=dirname($test);
351         }
353         my $dir=dirname("$destdir/$file");
354         if (! -d $dir) {
355                 my $d="";
356                 foreach my $s (split(m!/+!, $dir)) {
357                         $d.="$s/";
358                         if (! -d $d) {
359                                 mkdir($d) || error("failed to create directory $d: $!");
360                         }
361                 }
362         }
364         return 1;
367 sub writefile ($$$;$$) { #{{{
368         my $file=shift; # can include subdirs
369         my $destdir=shift; # directory to put file in
370         my $content=shift;
371         my $binary=shift;
372         my $writer=shift;
373         
374         prep_writefile($file, $destdir);
375         
376         my $newfile="$destdir/$file.ikiwiki-new";
377         if (-l $newfile) {
378                 error("cannot write to a symlink ($newfile)");
379         }
380         
381         my $cleanup = sub { unlink($newfile) };
382         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
383         binmode($out) if ($binary);
384         if ($writer) {
385                 $writer->(\*$out, $cleanup);
386         }
387         else {
388                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
389         }
390         close $out || error("failed saving $newfile: $!", $cleanup);
391         rename($newfile, "$destdir/$file") || 
392                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
394         return 1;
395 } #}}}
397 my %cleared;
398 sub will_render ($$;$) { #{{{
399         my $page=shift;
400         my $dest=shift;
401         my $clear=shift;
403         # Important security check.
404         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
405             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
406                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
407         }
409         if (! $clear || $cleared{$page}) {
410                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
411         }
412         else {
413                 foreach my $old (@{$renderedfiles{$page}}) {
414                         delete $destsources{$old};
415                 }
416                 $renderedfiles{$page}=[$dest];
417                 $cleared{$page}=1;
418         }
419         $destsources{$dest}=$page;
421         return 1;
422 } #}}}
424 sub bestlink ($$) { #{{{
425         my $page=shift;
426         my $link=shift;
427         
428         my $cwd=$page;
429         if ($link=~s/^\/+//) {
430                 # absolute links
431                 $cwd="";
432         }
433         $link=~s/\/$//;
435         do {
436                 my $l=$cwd;
437                 $l.="/" if length $l;
438                 $l.=$link;
440                 if (exists $links{$l}) {
441                         return $l;
442                 }
443                 elsif (exists $pagecase{lc $l}) {
444                         return $pagecase{lc $l};
445                 }
446         } while $cwd=~s!/?[^/]+$!!;
448         if (length $config{userdir}) {
449                 my $l = "$config{userdir}/".lc($link);
450                 if (exists $links{$l}) {
451                         return $l;
452                 }
453                 elsif (exists $pagecase{lc $l}) {
454                         return $pagecase{lc $l};
455                 }
456         }
458         #print STDERR "warning: page $page, broken link: $link\n";
459         return "";
460 } #}}}
462 sub isinlinableimage ($) { #{{{
463         my $file=shift;
464         
465         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
466 } #}}}
468 sub pagetitle ($;$) { #{{{
469         my $page=shift;
470         my $unescaped=shift;
472         if ($unescaped) {
473                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
474         }
475         else {
476                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
477         }
479         return $page;
480 } #}}}
482 sub titlepage ($) { #{{{
483         my $title=shift;
484         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
485         return $title;
486 } #}}}
488 sub linkpage ($) { #{{{
489         my $link=shift;
490         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
491         return $link;
492 } #}}}
494 sub cgiurl (@) { #{{{
495         my %params=@_;
497         return $config{cgiurl}."?".
498                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
499 } #}}}
501 sub baseurl (;$) { #{{{
502         my $page=shift;
504         return "$config{url}/" if ! defined $page;
505         
506         $page=htmlpage($page);
507         $page=~s/[^\/]+$//;
508         $page=~s/[^\/]+\//..\//g;
509         return $page;
510 } #}}}
512 sub abs2rel ($$) { #{{{
513         # Work around very innefficient behavior in File::Spec if abs2rel
514         # is passed two relative paths. It's much faster if paths are
515         # absolute! (Debian bug #376658; fixed in debian unstable now)
516         my $path="/".shift;
517         my $base="/".shift;
519         require File::Spec;
520         my $ret=File::Spec->abs2rel($path, $base);
521         $ret=~s/^// if defined $ret;
522         return $ret;
523 } #}}}
525 sub displaytime ($;$) { #{{{
526         my $time=shift;
527         my $format=shift;
528         if (! defined $format) {
529                 $format=$config{timeformat};
530         }
532         # strftime doesn't know about encodings, so make sure
533         # its output is properly treated as utf8
534         return decode_utf8(POSIX::strftime($format, localtime($time)));
535 } #}}}
537 sub beautify_url ($) { #{{{
538         my $url=shift;
540         if ($config{usedirs}) {
541                 $url =~ s!/index.$config{htmlext}$!/!;
542         }
544         # Ensure url is not an empty link, and
545         # if it's relative, make that explicit to avoid colon confusion.
546         if ($url !~ /^\//) {
547                 $url="./$url";
548         }
550         return $url;
551 } #}}}
553 sub urlto ($$;$) { #{{{
554         my $to=shift;
555         my $from=shift;
556         my $absolute=shift;
557         
558         if (! length $to) {
559                 return beautify_url(baseurl($from)."index.$config{htmlext}");
560         }
562         if (! $destsources{$to}) {
563                 $to=htmlpage($to);
564         }
566         if ($absolute) {
567                 return $config{url}.beautify_urlpath("/".$to);
568         }
570         my $link = abs2rel($to, dirname(htmlpage($from)));
572         return beautify_url($link);
573 } #}}}
575 sub htmllink ($$$;@) { #{{{
576         my $lpage=shift; # the page doing the linking
577         my $page=shift; # the page that will contain the link (different for inline)
578         my $link=shift;
579         my %opts=@_;
581         $link=~s/\/$//;
583         my $bestlink;
584         if (! $opts{forcesubpage}) {
585                 $bestlink=bestlink($lpage, $link);
586         }
587         else {
588                 $bestlink="$lpage/".lc($link);
589         }
591         my $linktext;
592         if (defined $opts{linktext}) {
593                 $linktext=$opts{linktext};
594         }
595         else {
596                 $linktext=pagetitle(basename($link));
597         }
598         
599         return "<span class=\"selflink\">$linktext</span>"
600                 if length $bestlink && $page eq $bestlink &&
601                    ! defined $opts{anchor};
602         
603         if (! $destsources{$bestlink}) {
604                 $bestlink=htmlpage($bestlink);
606                 if (! $destsources{$bestlink}) {
607                         return $linktext unless length $config{cgiurl};
608                         return "<span class=\"createlink\"><a href=\"".
609                                 cgiurl(
610                                         do => "create",
611                                         page => lc($link),
612                                         from => $lpage
613                                 ).
614                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
615                 }
616         }
617         
618         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
619         $bestlink=beautify_url($bestlink);
620         
621         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
622                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
623         }
625         if (defined $opts{anchor}) {
626                 $bestlink.="#".$opts{anchor};
627         }
629         my @attrs;
630         if (defined $opts{rel}) {
631                 push @attrs, ' rel="'.$opts{rel}.'"';
632         }
633         if (defined $opts{class}) {
634                 push @attrs, ' class="'.$opts{class}.'"';
635         }
637         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
638 } #}}}
640 sub userlink ($) { #{{{
641         my $user=shift;
643         my $oiduser=eval { openiduser($user) };
644         if (defined $oiduser) {
645                 return "<a href=\"$user\">$oiduser</a>";
646         }
647         else {
648                 eval q{use CGI 'escapeHTML'};
649                 error($@) if $@;
651                 return htmllink("", "", escapeHTML(
652                         length $config{userdir} ? $config{userdir}."/".$user : $user
653                 ), noimageinline => 1);
654         }
655 } #}}}
657 sub htmlize ($$$$) { #{{{
658         my $page=shift;
659         my $destpage=shift;
660         my $type=shift;
661         my $content=shift;
662         
663         my $oneline = $content !~ /\n/;
665         if (exists $hooks{htmlize}{$type}) {
666                 $content=$hooks{htmlize}{$type}{call}->(
667                         page => $page,
668                         content => $content,
669                 );
670         }
671         else {
672                 error("htmlization of $type not supported");
673         }
675         run_hooks(sanitize => sub {
676                 $content=shift->(
677                         page => $page,
678                         destpage => $destpage,
679                         content => $content,
680                 );
681         });
682         
683         if ($oneline) {
684                 # hack to get rid of enclosing junk added by markdown
685                 # and other htmlizers
686                 $content=~s/^<p>//i;
687                 $content=~s/<\/p>$//i;
688                 chomp $content;
689         }
691         return $content;
692 } #}}}
694 sub linkify ($$$) { #{{{
695         my $page=shift;
696         my $destpage=shift;
697         my $content=shift;
699         run_hooks(linkify => sub {
700                 $content=shift->(
701                         page => $page,
702                         destpage => $destpage,
703                         content => $content,
704                 );
705         });
706         
707         return $content;
708 } #}}}
710 our %preprocessing;
711 our $preprocess_preview=0;
712 sub preprocess ($$$;$$) { #{{{
713         my $page=shift; # the page the data comes from
714         my $destpage=shift; # the page the data will appear in (different for inline)
715         my $content=shift;
716         my $scan=shift;
717         my $preview=shift;
719         # Using local because it needs to be set within any nested calls
720         # of this function.
721         local $preprocess_preview=$preview if defined $preview;
723         my $handle=sub {
724                 my $escape=shift;
725                 my $prefix=shift;
726                 my $command=shift;
727                 my $params=shift;
728                 $params="" if ! defined $params;
730                 if (length $escape) {
731                         return "[[$prefix$command $params]]";
732                 }
733                 elsif (exists $hooks{preprocess}{$command}) {
734                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
735                         # Note: preserve order of params, some plugins may
736                         # consider it significant.
737                         my @params;
738                         while ($params =~ m{
739                                 (?:([-\w]+)=)?          # 1: named parameter key?
740                                 (?:
741                                         """(.*?)"""     # 2: triple-quoted value
742                                 |
743                                         "([^"]+)"       # 3: single-quoted value
744                                 |
745                                         (\S+)           # 4: unquoted value
746                                 )
747                                 (?:\s+|$)               # delimiter to next param
748                         }sgx) {
749                                 my $key=$1;
750                                 my $val;
751                                 if (defined $2) {
752                                         $val=$2;
753                                         $val=~s/\r\n/\n/mg;
754                                         $val=~s/^\n+//g;
755                                         $val=~s/\n+$//g;
756                                 }
757                                 elsif (defined $3) {
758                                         $val=$3;
759                                 }
760                                 elsif (defined $4) {
761                                         $val=$4;
762                                 }
764                                 if (defined $key) {
765                                         push @params, $key, $val;
766                                 }
767                                 else {
768                                         push @params, $val, '';
769                                 }
770                         }
771                         if ($preprocessing{$page}++ > 3) {
772                                 # Avoid loops of preprocessed pages preprocessing
773                                 # other pages that preprocess them, etc.
774                                 #translators: The first parameter is a
775                                 #translators: preprocessor directive name,
776                                 #translators: the second a page name, the
777                                 #translators: third a number.
778                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
779                                         $command, $page, $preprocessing{$page}).
780                                 "]]";
781                         }
782                         my $ret;
783                         if (! $scan) {
784                                 $ret=$hooks{preprocess}{$command}{call}->(
785                                         @params,
786                                         page => $page,
787                                         destpage => $destpage,
788                                         preview => $preprocess_preview,
789                                 );
790                         }
791                         else {
792                                 # use void context during scan pass
793                                 $hooks{preprocess}{$command}{call}->(
794                                         @params,
795                                         page => $page,
796                                         destpage => $destpage,
797                                         preview => $preprocess_preview,
798                                 );
799                                 $ret="";
800                         }
801                         $preprocessing{$page}--;
802                         return $ret;
803                 }
804                 else {
805                         return "[[$prefix$command $params]]";
806                 }
807         };
808         
809         my $regex;
810         if ($config{prefix_directives}) {
811                 $regex = qr{
812                         (\\?)           # 1: escape?
813                         \[\[(!)         # directive open; 2: prefix
814                         ([-\w]+)        # 3: command
815                         (               # 4: the parameters..
816                                 \s+     # Must have space if parameters present
817                                 (?:
818                                         (?:[-\w]+=)?            # named parameter key?
819                                         (?:
820                                                 """.*?"""       # triple-quoted value
821                                                 |
822                                                 "[^"]+"         # single-quoted value
823                                                 |
824                                                 [^\s\]]+        # unquoted value
825                                         )
826                                         \s*                     # whitespace or end
827                                                                 # of directive
828                                 )
829                         *)?             # 0 or more parameters
830                         \]\]            # directive closed
831                 }sx;
832         } else {
833                 $regex = qr{
834                         (\\?)           # 1: escape?
835                         \[\[(!?)        # directive open; 2: optional prefix
836                         ([-\w]+)        # 3: command
837                         \s+
838                         (               # 4: the parameters..
839                                 (?:
840                                         (?:[-\w]+=)?            # named parameter key?
841                                         (?:
842                                                 """.*?"""       # triple-quoted value
843                                                 |
844                                                 "[^"]+"         # single-quoted value
845                                                 |
846                                                 [^\s\]]+        # unquoted value
847                                         )
848                                         \s*                     # whitespace or end
849                                                                 # of directive
850                                 )
851                         *)              # 0 or more parameters
852                         \]\]            # directive closed
853                 }sx;
854         }
856         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
857         return $content;
858 } #}}}
860 sub filter ($$$) { #{{{
861         my $page=shift;
862         my $destpage=shift;
863         my $content=shift;
865         run_hooks(filter => sub {
866                 $content=shift->(page => $page, destpage => $destpage, 
867                         content => $content);
868         });
870         return $content;
871 } #}}}
873 sub indexlink () { #{{{
874         return "<a href=\"$config{url}\">$config{wikiname}</a>";
875 } #}}}
877 my $wikilock;
879 sub lockwiki (;$) { #{{{
880         my $wait=@_ ? shift : 1;
881         # Take an exclusive lock on the wiki to prevent multiple concurrent
882         # run issues. The lock will be dropped on program exit.
883         if (! -d $config{wikistatedir}) {
884                 mkdir($config{wikistatedir});
885         }
886         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
887                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
888         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
889                 if ($wait) {
890                         debug("wiki seems to be locked, waiting for lock");
891                         my $wait=600; # arbitrary, but don't hang forever to 
892                                       # prevent process pileup
893                         for (1..$wait) {
894                                 return if flock($wikilock, 2 | 4);
895                                 sleep 1;
896                         }
897                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
898                 }
899                 else {
900                         return 0;
901                 }
902         }
903         return 1;
904 } #}}}
906 sub unlockwiki () { #{{{
907         return close($wikilock) if $wikilock;
908         return;
909 } #}}}
911 my $commitlock;
913 sub commit_hook_enabled () { #{{{
914         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
915                 error("cannot write to $config{wikistatedir}/commitlock: $!");
916         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
917                 close($commitlock) || error("failed closing commitlock: $!");
918                 return 0;
919         }
920         close($commitlock) || error("failed closing commitlock: $!");
921         return 1;
922 } #}}}
924 sub disable_commit_hook () { #{{{
925         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
926                 error("cannot write to $config{wikistatedir}/commitlock: $!");
927         if (! flock($commitlock, 2)) { # LOCK_EX
928                 error("failed to get commit lock");
929         }
930         return 1;
931 } #}}}
933 sub enable_commit_hook () { #{{{
934         return close($commitlock) if $commitlock;
935         return;
936 } #}}}
938 sub loadindex () { #{{{
939         %oldrenderedfiles=%pagectime=();
940         if (! $config{rebuild}) {
941                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
942                 %destsources=%renderedfiles=%pagecase=%pagestate=();
943         }
944         my $in;
945         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
946                 if (-e "$config{wikistatedir}/index") {
947                         system("ikiwiki-transition", "indexdb", $config{srcdir});
948                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
949                 }
950                 else {
951                         return;
952                 }
953         }
954         my $ret=Storable::fd_retrieve($in);
955         if (! defined $ret) {
956                 return 0;
957         }
958         my %index=%$ret;
959         foreach my $src (keys %index) {
960                 my %d=%{$index{$src}};
961                 my $page=pagename($src);
962                 $pagectime{$page}=$d{ctime};
963                 if (! $config{rebuild}) {
964                         $pagesources{$page}=$src;
965                         $pagemtime{$page}=$d{mtime};
966                         $renderedfiles{$page}=$d{dest};
967                         if (exists $d{links} && ref $d{links}) {
968                                 $links{$page}=$d{links};
969                                 $oldlinks{$page}=[@{$d{links}}];
970                         }
971                         if (exists $d{depends}) {
972                                 $depends{$page}=$d{depends};
973                         }
974                         if (exists $d{state}) {
975                                 $pagestate{$page}=$d{state};
976                         }
977                 }
978                 $oldrenderedfiles{$page}=[@{$d{dest}}];
979         }
980         foreach my $page (keys %pagesources) {
981                 $pagecase{lc $page}=$page;
982         }
983         foreach my $page (keys %renderedfiles) {
984                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
985         }
986         return close($in);
987 } #}}}
989 sub saveindex () { #{{{
990         run_hooks(savestate => sub { shift->() });
992         my %hookids;
993         foreach my $type (keys %hooks) {
994                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
995         }
996         my @hookids=keys %hookids;
998         if (! -d $config{wikistatedir}) {
999                 mkdir($config{wikistatedir});
1000         }
1001         my $newfile="$config{wikistatedir}/indexdb.new";
1002         my $cleanup = sub { unlink($newfile) };
1003         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1004         my %index;
1005         foreach my $page (keys %pagemtime) {
1006                 next unless $pagemtime{$page};
1007                 my $src=$pagesources{$page};
1009                 $index{$src}={
1010                         ctime => $pagectime{$page},
1011                         mtime => $pagemtime{$page},
1012                         dest => $renderedfiles{$page},
1013                         links => $links{$page},
1014                 };
1016                 if (exists $depends{$page}) {
1017                         $index{$src}{depends} = $depends{$page};
1018                 }
1020                 if (exists $pagestate{$page}) {
1021                         foreach my $id (@hookids) {
1022                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1023                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1024                                 }
1025                         }
1026                 }
1027         }
1028         my $ret=Storable::nstore_fd(\%index, $out);
1029         return if ! defined $ret || ! $ret;
1030         close $out || error("failed saving to $newfile: $!", $cleanup);
1031         rename($newfile, "$config{wikistatedir}/indexdb") ||
1032                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1033         
1034         return 1;
1035 } #}}}
1037 sub template_file ($) { #{{{
1038         my $template=shift;
1040         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1041                 return "$dir/$template" if -e "$dir/$template";
1042         }
1043         return;
1044 } #}}}
1046 sub template_params (@) { #{{{
1047         my $filename=template_file(shift);
1049         if (! defined $filename) {
1050                 return if wantarray;
1051                 return "";
1052         }
1054         my @ret=(
1055                 filter => sub {
1056                         my $text_ref = shift;
1057                         ${$text_ref} = decode_utf8(${$text_ref});
1058                 },
1059                 filename => $filename,
1060                 loop_context_vars => 1,
1061                 die_on_bad_params => 0,
1062                 @_
1063         );
1064         return wantarray ? @ret : {@ret};
1065 } #}}}
1067 sub template ($;@) { #{{{
1068         require HTML::Template;
1069         return HTML::Template->new(template_params(@_));
1070 } #}}}
1072 sub misctemplate ($$;@) { #{{{
1073         my $title=shift;
1074         my $pagebody=shift;
1075         
1076         my $template=template("misc.tmpl");
1077         $template->param(
1078                 title => $title,
1079                 indexlink => indexlink(),
1080                 wikiname => $config{wikiname},
1081                 pagebody => $pagebody,
1082                 baseurl => baseurl(),
1083                 @_,
1084         );
1085         run_hooks(pagetemplate => sub {
1086                 shift->(page => "", destpage => "", template => $template);
1087         });
1088         return $template->output;
1089 }#}}}
1091 sub hook (@) { # {{{
1092         my %param=@_;
1093         
1094         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1095                 error 'hook requires type, call, and id parameters';
1096         }
1098         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1099         
1100         $hooks{$param{type}}{$param{id}}=\%param;
1101         return 1;
1102 } # }}}
1104 sub run_hooks ($$) { # {{{
1105         # Calls the given sub for each hook of the given type,
1106         # passing it the hook function to call.
1107         my $type=shift;
1108         my $sub=shift;
1110         if (exists $hooks{$type}) {
1111                 my @deferred;
1112                 foreach my $id (keys %{$hooks{$type}}) {
1113                         if ($hooks{$type}{$id}{last}) {
1114                                 push @deferred, $id;
1115                                 next;
1116                         }
1117                         $sub->($hooks{$type}{$id}{call});
1118                 }
1119                 foreach my $id (@deferred) {
1120                         $sub->($hooks{$type}{$id}{call});
1121                 }
1122         }
1124         return 1;
1125 } #}}}
1127 sub globlist_to_pagespec ($) { #{{{
1128         my @globlist=split(' ', shift);
1130         my (@spec, @skip);
1131         foreach my $glob (@globlist) {
1132                 if ($glob=~/^!(.*)/) {
1133                         push @skip, $glob;
1134                 }
1135                 else {
1136                         push @spec, $glob;
1137                 }
1138         }
1140         my $spec=join(' or ', @spec);
1141         if (@skip) {
1142                 my $skip=join(' and ', @skip);
1143                 if (length $spec) {
1144                         $spec="$skip and ($spec)";
1145                 }
1146                 else {
1147                         $spec=$skip;
1148                 }
1149         }
1150         return $spec;
1151 } #}}}
1153 sub is_globlist ($) { #{{{
1154         my $s=shift;
1155         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1156 } #}}}
1158 sub safequote ($) { #{{{
1159         my $s=shift;
1160         $s=~s/[{}]//g;
1161         return "q{$s}";
1162 } #}}}
1164 sub add_depends ($$) { #{{{
1165         my $page=shift;
1166         my $pagespec=shift;
1167         
1168         return unless pagespec_valid($pagespec);
1170         if (! exists $depends{$page}) {
1171                 $depends{$page}=$pagespec;
1172         }
1173         else {
1174                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1175         }
1177         return 1;
1178 } # }}}
1180 sub file_pruned ($$) { #{{{
1181         require File::Spec;
1182         my $file=File::Spec->canonpath(shift);
1183         my $base=File::Spec->canonpath(shift);
1184         $file =~ s#^\Q$base\E/+##;
1186         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1187         return $file =~ m/$regexp/ && $file ne $base;
1188 } #}}}
1190 sub gettext { #{{{
1191         # Only use gettext in the rare cases it's needed.
1192         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1193             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1194             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1195                 if (! $gettext_obj) {
1196                         $gettext_obj=eval q{
1197                                 use Locale::gettext q{textdomain};
1198                                 Locale::gettext->domain('ikiwiki')
1199                         };
1200                         if ($@) {
1201                                 print STDERR "$@";
1202                                 $gettext_obj=undef;
1203                                 return shift;
1204                         }
1205                 }
1206                 return $gettext_obj->get(shift);
1207         }
1208         else {
1209                 return shift;
1210         }
1211 } #}}}
1213 sub pagespec_merge ($$) { #{{{
1214         my $a=shift;
1215         my $b=shift;
1217         return $a if $a eq $b;
1219         # Support for old-style GlobLists.
1220         if (is_globlist($a)) {
1221                 $a=globlist_to_pagespec($a);
1222         }
1223         if (is_globlist($b)) {
1224                 $b=globlist_to_pagespec($b);
1225         }
1227         return "($a) or ($b)";
1228 } #}}}
1230 sub pagespec_translate ($) { #{{{
1231         my $spec=shift;
1233         # Support for old-style GlobLists.
1234         if (is_globlist($spec)) {
1235                 $spec=globlist_to_pagespec($spec);
1236         }
1238         # Convert spec to perl code.
1239         my $code="";
1240         while ($spec=~m{
1241                 \s*             # ignore whitespace
1242                 (               # 1: match a single word
1243                         \!              # !
1244                 |
1245                         \(              # (
1246                 |
1247                         \)              # )
1248                 |
1249                         \w+\([^\)]*\)   # command(params)
1250                 |
1251                         [^\s()]+        # any other text
1252                 )
1253                 \s*             # ignore whitespace
1254         }igx) {
1255                 my $word=$1;
1256                 if (lc $word eq 'and') {
1257                         $code.=' &&';
1258                 }
1259                 elsif (lc $word eq 'or') {
1260                         $code.=' ||';
1261                 }
1262                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1263                         $code.=' '.$word;
1264                 }
1265                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1266                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1267                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1268                         }
1269                         else {
1270                                 $code.=' 0';
1271                         }
1272                 }
1273                 else {
1274                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1275                 }
1276         }
1278         if (! length $code) {
1279                 $code=0;
1280         }
1282         no warnings;
1283         return eval 'sub { my $page=shift; '.$code.' }';
1284 } #}}}
1286 sub pagespec_match ($$;@) { #{{{
1287         my $page=shift;
1288         my $spec=shift;
1289         my @params=@_;
1291         # Backwards compatability with old calling convention.
1292         if (@params == 1) {
1293                 unshift @params, 'location';
1294         }
1296         my $sub=pagespec_translate($spec);
1297         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1298         return $sub->($page, @params);
1299 } #}}}
1301 sub pagespec_valid ($) { #{{{
1302         my $spec=shift;
1304         my $sub=pagespec_translate($spec);
1305         return ! $@;
1306 } #}}}
1307         
1308 sub glob2re ($) { #{{{
1309         my $re=quotemeta(shift);
1310         $re=~s/\\\*/.*/g;
1311         $re=~s/\\\?/./g;
1312         return $re;
1313 } #}}}
1315 package IkiWiki::FailReason;
1317 use overload ( #{{{
1318         '""'    => sub { ${$_[0]} },
1319         '0+'    => sub { 0 },
1320         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1321         fallback => 1,
1322 ); #}}}
1324 sub new { #{{{
1325         my $class = shift;
1326         my $value = shift;
1327         return bless \$value, $class;
1328 } #}}}
1330 package IkiWiki::SuccessReason;
1332 use overload ( #{{{
1333         '""'    => sub { ${$_[0]} },
1334         '0+'    => sub { 1 },
1335         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1336         fallback => 1,
1337 ); #}}}
1339 sub new { #{{{
1340         my $class = shift;
1341         my $value = shift;
1342         return bless \$value, $class;
1343 }; #}}}
1345 package IkiWiki::PageSpec;
1347 sub match_glob ($$;@) { #{{{
1348         my $page=shift;
1349         my $glob=shift;
1350         my %params=@_;
1351         
1352         my $from=exists $params{location} ? $params{location} : '';
1353         
1354         # relative matching
1355         if ($glob =~ m!^\./!) {
1356                 $from=~s#/?[^/]+$##;
1357                 $glob=~s#^\./##;
1358                 $glob="$from/$glob" if length $from;
1359         }
1361         my $regexp=IkiWiki::glob2re($glob);
1362         if ($page=~/^$regexp$/i) {
1363                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1364                         return IkiWiki::SuccessReason->new("$glob matches $page");
1365                 }
1366                 else {
1367                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1368                 }
1369         }
1370         else {
1371                 return IkiWiki::FailReason->new("$glob does not match $page");
1372         }
1373 } #}}}
1375 sub match_internal ($$;@) { #{{{
1376         return match_glob($_[0], $_[1], @_, internal => 1)
1377 } #}}}
1379 sub match_link ($$;@) { #{{{
1380         my $page=shift;
1381         my $link=lc(shift);
1382         my %params=@_;
1384         my $from=exists $params{location} ? $params{location} : '';
1386         # relative matching
1387         if ($link =~ m!^\.! && defined $from) {
1388                 $from=~s#/?[^/]+$##;
1389                 $link=~s#^\./##;
1390                 $link="$from/$link" if length $from;
1391         }
1393         my $links = $IkiWiki::links{$page};
1394         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1395         my $bestlink = IkiWiki::bestlink($from, $link);
1396         foreach my $p (@{$links}) {
1397                 if (length $bestlink) {
1398                         return IkiWiki::SuccessReason->new("$page links to $link")
1399                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1400                 }
1401                 else {
1402                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1403                                 if match_glob($p, $link, %params);
1404                 }
1405         }
1406         return IkiWiki::FailReason->new("$page does not link to $link");
1407 } #}}}
1409 sub match_backlink ($$;@) { #{{{
1410         return match_link($_[1], $_[0], @_);
1411 } #}}}
1413 sub match_created_before ($$;@) { #{{{
1414         my $page=shift;
1415         my $testpage=shift;
1417         if (exists $IkiWiki::pagectime{$testpage}) {
1418                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1419                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1420                 }
1421                 else {
1422                         return IkiWiki::FailReason->new("$page not created before $testpage");
1423                 }
1424         }
1425         else {
1426                 return IkiWiki::FailReason->new("$testpage has no ctime");
1427         }
1428 } #}}}
1430 sub match_created_after ($$;@) { #{{{
1431         my $page=shift;
1432         my $testpage=shift;
1434         if (exists $IkiWiki::pagectime{$testpage}) {
1435                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1436                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1437                 }
1438                 else {
1439                         return IkiWiki::FailReason->new("$page not created after $testpage");
1440                 }
1441         }
1442         else {
1443                 return IkiWiki::FailReason->new("$testpage has no ctime");
1444         }
1445 } #}}}
1447 sub match_creation_day ($$;@) { #{{{
1448         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1449                 return IkiWiki::SuccessReason->new('creation_day matched');
1450         }
1451         else {
1452                 return IkiWiki::FailReason->new('creation_day did not match');
1453         }
1454 } #}}}
1456 sub match_creation_month ($$;@) { #{{{
1457         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1458                 return IkiWiki::SuccessReason->new('creation_month matched');
1459         }
1460         else {
1461                 return IkiWiki::FailReason->new('creation_month did not match');
1462         }
1463 } #}}}
1465 sub match_creation_year ($$;@) { #{{{
1466         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1467                 return IkiWiki::SuccessReason->new('creation_year matched');
1468         }
1469         else {
1470                 return IkiWiki::FailReason->new('creation_year did not match');
1471         }
1472 } #}}}