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