]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
move question to discussion page, where it belongs
[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 } #}}}
93 sub checkconfig () { #{{{
94         # locale stuff; avoid LC_ALL since it overrides everything
95         if (defined $ENV{LC_ALL}) {
96                 $ENV{LANG} = $ENV{LC_ALL};
97                 delete $ENV{LC_ALL};
98         }
99         if (defined $config{locale}) {
100                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
101                         $ENV{LANG}=$config{locale};
102                         $gettext_obj=undef;
103                 }
104         }
106         if ($config{w3mmode}) {
107                 eval q{use Cwd q{abs_path}};
108                 error($@) if $@;
109                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
110                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
111                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
112                         unless $config{cgiurl} =~ m!file:///!;
113                 $config{url}="file://".$config{destdir};
114         }
116         if ($config{cgi} && ! length $config{url}) {
117                 error(gettext("Must specify url to wiki with --url when using --cgi"));
118         }
119         
120         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
121                 unless exists $config{wikistatedir};
122         
123         if ($config{rcs}) {
124                 eval qq{use IkiWiki::Rcs::$config{rcs}};
125                 if ($@) {
126                         error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
127                 }
128         }
129         else {
130                 require IkiWiki::Rcs::Stub;
131         }
133         if (exists $config{umask}) {
134                 umask(possibly_foolish_untaint($config{umask}));
135         }
137         run_hooks(checkconfig => sub { shift->() });
139         return 1;
140 } #}}}
142 sub loadplugins () { #{{{
143         if (defined $config{libdir}) {
144                 unshift @INC, possibly_foolish_untaint($config{libdir});
145         }
147         loadplugin($_) foreach @{$config{plugin}};
149         run_hooks(getopt => sub { shift->() });
150         if (grep /^-/, @ARGV) {
151                 print STDERR "Unknown option: $_\n"
152                         foreach grep /^-/, @ARGV;
153                 usage();
154         }
156         return 1;
157 } #}}}
159 sub loadplugin ($) { #{{{
160         my $plugin=shift;
162         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
164         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
165                          "$installdir/lib/ikiwiki") {
166                 if (defined $dir && -x "$dir/plugins/$plugin") {
167                         require IkiWiki::Plugin::external;
168                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
169                         return 1;
170                 }
171         }
173         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
174         eval qq{use $mod};
175         if ($@) {
176                 error("Failed to load plugin $mod: $@");
177         }
178         return 1;
179 } #}}}
181 sub error ($;$) { #{{{
182         my $message=shift;
183         my $cleaner=shift;
184         if ($config{cgi}) {
185                 print "Content-type: text/html\n\n";
186                 print misctemplate(gettext("Error"),
187                         "<p>".gettext("Error").": $message</p>");
188         }
189         log_message('err' => $message) if $config{syslog};
190         if (defined $cleaner) {
191                 $cleaner->();
192         }
193         die $message."\n";
194 } #}}}
196 sub debug ($) { #{{{
197         return unless $config{verbose};
198         return log_message(debug => @_);
199 } #}}}
201 my $log_open=0;
202 sub log_message ($$) { #{{{
203         my $type=shift;
205         if ($config{syslog}) {
206                 require Sys::Syslog;
207                 if (! $log_open) {
208                         Sys::Syslog::setlogsock('unix');
209                         Sys::Syslog::openlog('ikiwiki', '', 'user');
210                         $log_open=1;
211                 }
212                 return eval {
213                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
214                 };
215         }
216         elsif (! $config{cgi}) {
217                 return print "@_\n";
218         }
219         else {
220                 return print STDERR "@_\n";
221         }
222 } #}}}
224 sub possibly_foolish_untaint ($) { #{{{
225         my $tainted=shift;
226         my ($untainted)=$tainted=~/(.*)/s;
227         return $untainted;
228 } #}}}
230 sub basename ($) { #{{{
231         my $file=shift;
233         $file=~s!.*/+!!;
234         return $file;
235 } #}}}
237 sub dirname ($) { #{{{
238         my $file=shift;
240         $file=~s!/*[^/]+$!!;
241         return $file;
242 } #}}}
244 sub pagetype ($) { #{{{
245         my $page=shift;
246         
247         if ($page =~ /\.([^.]+)$/) {
248                 return $1 if exists $hooks{htmlize}{$1};
249         }
250         return;
251 } #}}}
253 sub isinternal ($) { #{{{
254         my $page=shift;
255         return exists $pagesources{$page} &&
256                 $pagesources{$page} =~ /\._([^.]+)$/;
257 } #}}}
259 sub pagename ($) { #{{{
260         my $file=shift;
262         my $type=pagetype($file);
263         my $page=$file;
264         $page=~s/\Q.$type\E*$// if defined $type;
265         return $page;
266 } #}}}
268 sub targetpage ($$) { #{{{
269         my $page=shift;
270         my $ext=shift;
271         
272         if (! $config{usedirs} || $page =~ /^index$/ ) {
273                 return $page.".".$ext;
274         } else {
275                 return $page."/index.".$ext;
276         }
277 } #}}}
279 sub htmlpage ($) { #{{{
280         my $page=shift;
281         
282         return targetpage($page, $config{htmlext});
283 } #}}}
285 sub srcfile ($) { #{{{
286         my $file=shift;
288         return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
289         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
290                 return "$dir/$file" if -e "$dir/$file";
291         }
292         error("internal error: $file cannot be found in $config{srcdir} or underlay");
293         return;
294 } #}}}
296 sub add_underlay ($) { #{{{
297         my $dir=shift;
299         if ($dir=~/^\//) {
300                 unshift @{$config{underlaydirs}}, $dir;
301         }
302         else {
303                 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
304         }
306         return 1;
307 } #}}}
309 sub readfile ($;$$) { #{{{
310         my $file=shift;
311         my $binary=shift;
312         my $wantfd=shift;
314         if (-l $file) {
315                 error("cannot read a symlink ($file)");
316         }
317         
318         local $/=undef;
319         open (my $in, "<", $file) || error("failed to read $file: $!");
320         binmode($in) if ($binary);
321         return \*$in if $wantfd;
322         my $ret=<$in>;
323         close $in || error("failed to read $file: $!");
324         return $ret;
325 } #}}}
327 sub prep_writefile ($$) {
328         my $file=shift;
329         my $destdir=shift;
330         
331         my $test=$file;
332         while (length $test) {
333                 if (-l "$destdir/$test") {
334                         error("cannot write to a symlink ($test)");
335                 }
336                 $test=dirname($test);
337         }
339         my $dir=dirname("$destdir/$file");
340         if (! -d $dir) {
341                 my $d="";
342                 foreach my $s (split(m!/+!, $dir)) {
343                         $d.="$s/";
344                         if (! -d $d) {
345                                 mkdir($d) || error("failed to create directory $d: $!");
346                         }
347                 }
348         }
350         return 1;
353 sub writefile ($$$;$$) { #{{{
354         my $file=shift; # can include subdirs
355         my $destdir=shift; # directory to put file in
356         my $content=shift;
357         my $binary=shift;
358         my $writer=shift;
359         
360         prep_writefile($file, $destdir);
361         
362         my $newfile="$destdir/$file.ikiwiki-new";
363         if (-l $newfile) {
364                 error("cannot write to a symlink ($newfile)");
365         }
366         
367         my $cleanup = sub { unlink($newfile) };
368         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
369         binmode($out) if ($binary);
370         if ($writer) {
371                 $writer->(\*$out, $cleanup);
372         }
373         else {
374                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
375         }
376         close $out || error("failed saving $newfile: $!", $cleanup);
377         rename($newfile, "$destdir/$file") || 
378                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
380         return 1;
381 } #}}}
383 my %cleared;
384 sub will_render ($$;$) { #{{{
385         my $page=shift;
386         my $dest=shift;
387         my $clear=shift;
389         # Important security check.
390         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
391             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
392                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
393         }
395         if (! $clear || $cleared{$page}) {
396                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
397         }
398         else {
399                 foreach my $old (@{$renderedfiles{$page}}) {
400                         delete $destsources{$old};
401                 }
402                 $renderedfiles{$page}=[$dest];
403                 $cleared{$page}=1;
404         }
405         $destsources{$dest}=$page;
407         return 1;
408 } #}}}
410 sub bestlink ($$) { #{{{
411         my $page=shift;
412         my $link=shift;
413         
414         my $cwd=$page;
415         if ($link=~s/^\/+//) {
416                 # absolute links
417                 $cwd="";
418         }
419         $link=~s/\/$//;
421         do {
422                 my $l=$cwd;
423                 $l.="/" if length $l;
424                 $l.=$link;
426                 if (exists $links{$l}) {
427                         return $l;
428                 }
429                 elsif (exists $pagecase{lc $l}) {
430                         return $pagecase{lc $l};
431                 }
432         } while $cwd=~s!/?[^/]+$!!;
434         if (length $config{userdir}) {
435                 my $l = "$config{userdir}/".lc($link);
436                 if (exists $links{$l}) {
437                         return $l;
438                 }
439                 elsif (exists $pagecase{lc $l}) {
440                         return $pagecase{lc $l};
441                 }
442         }
444         #print STDERR "warning: page $page, broken link: $link\n";
445         return "";
446 } #}}}
448 sub isinlinableimage ($) { #{{{
449         my $file=shift;
450         
451         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
452 } #}}}
454 sub pagetitle ($;$) { #{{{
455         my $page=shift;
456         my $unescaped=shift;
458         if ($unescaped) {
459                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
460         }
461         else {
462                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
463         }
465         return $page;
466 } #}}}
468 sub titlepage ($) { #{{{
469         my $title=shift;
470         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
471         return $title;
472 } #}}}
474 sub linkpage ($) { #{{{
475         my $link=shift;
476         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
477         return $link;
478 } #}}}
480 sub cgiurl (@) { #{{{
481         my %params=@_;
483         return $config{cgiurl}."?".
484                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
485 } #}}}
487 sub baseurl (;$) { #{{{
488         my $page=shift;
490         return "$config{url}/" if ! defined $page;
491         
492         $page=htmlpage($page);
493         $page=~s/[^\/]+$//;
494         $page=~s/[^\/]+\//..\//g;
495         return $page;
496 } #}}}
498 sub abs2rel ($$) { #{{{
499         # Work around very innefficient behavior in File::Spec if abs2rel
500         # is passed two relative paths. It's much faster if paths are
501         # absolute! (Debian bug #376658; fixed in debian unstable now)
502         my $path="/".shift;
503         my $base="/".shift;
505         require File::Spec;
506         my $ret=File::Spec->abs2rel($path, $base);
507         $ret=~s/^// if defined $ret;
508         return $ret;
509 } #}}}
511 sub displaytime ($;$) { #{{{
512         my $time=shift;
513         my $format=shift;
514         if (! defined $format) {
515                 $format=$config{timeformat};
516         }
518         # strftime doesn't know about encodings, so make sure
519         # its output is properly treated as utf8
520         return decode_utf8(POSIX::strftime($format, localtime($time)));
521 } #}}}
523 sub beautify_url ($) { #{{{
524         my $url=shift;
526         if ($config{usedirs}) {
527                 $url =~ s!/index.$config{htmlext}$!/!;
528         }
529         $url =~ s!^$!./!; # Browsers don't like empty links...
531         return $url;
532 } #}}}
534 sub urlto ($$) { #{{{
535         my $to=shift;
536         my $from=shift;
538         if (! length $to) {
539                 return beautify_url(baseurl($from));
540         }
542         if (! $destsources{$to}) {
543                 $to=htmlpage($to);
544         }
546         my $link = abs2rel($to, dirname(htmlpage($from)));
548         return beautify_url($link);
549 } #}}}
551 sub htmllink ($$$;@) { #{{{
552         my $lpage=shift; # the page doing the linking
553         my $page=shift; # the page that will contain the link (different for inline)
554         my $link=shift;
555         my %opts=@_;
557         $link=~s/\/$//;
559         my $bestlink;
560         if (! $opts{forcesubpage}) {
561                 $bestlink=bestlink($lpage, $link);
562         }
563         else {
564                 $bestlink="$lpage/".lc($link);
565         }
567         my $linktext;
568         if (defined $opts{linktext}) {
569                 $linktext=$opts{linktext};
570         }
571         else {
572                 $linktext=pagetitle(basename($link));
573         }
574         
575         return "<span class=\"selflink\">$linktext</span>"
576                 if length $bestlink && $page eq $bestlink &&
577                    ! defined $opts{anchor};
578         
579         if (! $destsources{$bestlink}) {
580                 $bestlink=htmlpage($bestlink);
582                 if (! $destsources{$bestlink}) {
583                         return $linktext unless length $config{cgiurl};
584                         return "<span class=\"createlink\"><a href=\"".
585                                 cgiurl(
586                                         do => "create",
587                                         page => pagetitle(lc($link), 1),
588                                         from => $lpage
589                                 ).
590                                 "\">?</a>$linktext</span>"
591                 }
592         }
593         
594         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
595         $bestlink=beautify_url($bestlink);
596         
597         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
598                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
599         }
601         if (defined $opts{anchor}) {
602                 $bestlink.="#".$opts{anchor};
603         }
605         my @attrs;
606         if (defined $opts{rel}) {
607                 push @attrs, ' rel="'.$opts{rel}.'"';
608         }
609         if (defined $opts{class}) {
610                 push @attrs, ' class="'.$opts{class}.'"';
611         }
613         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
614 } #}}}
616 sub userlink ($) { #{{{
617         my $user=shift;
619         my $oiduser=eval { openiduser($user) };
620         if (defined $oiduser) {
621                 return "<a href=\"$user\">$oiduser</a>";
622         }
623         else {
624                 eval q{use CGI 'escapeHTML'};
625                 error($@) if $@;
627                 return htmllink("", "", escapeHTML(
628                         length $config{userdir} ? $config{userdir}."/".$user : $user
629                 ), noimageinline => 1);
630         }
631 } #}}}
633 sub htmlize ($$$) { #{{{
634         my $page=shift;
635         my $type=shift;
636         my $content=shift;
637         
638         my $oneline = $content !~ /\n/;
640         if (exists $hooks{htmlize}{$type}) {
641                 $content=$hooks{htmlize}{$type}{call}->(
642                         page => $page,
643                         content => $content,
644                 );
645         }
646         else {
647                 error("htmlization of $type not supported");
648         }
650         run_hooks(sanitize => sub {
651                 $content=shift->(
652                         page => $page,
653                         content => $content,
654                 );
655         });
656         
657         if ($oneline) {
658                 # hack to get rid of enclosing junk added by markdown
659                 # and other htmlizers
660                 $content=~s/^<p>//i;
661                 $content=~s/<\/p>$//i;
662                 chomp $content;
663         }
665         return $content;
666 } #}}}
668 sub linkify ($$$) { #{{{
669         my $page=shift;
670         my $destpage=shift;
671         my $content=shift;
673         run_hooks(linkify => sub {
674                 $content=shift->(
675                         page => $page,
676                         destpage => $destpage,
677                         content => $content,
678                 );
679         });
680         
681         return $content;
682 } #}}}
684 my %preprocessing;
685 our $preprocess_preview=0;
686 sub preprocess ($$$;$$) { #{{{
687         my $page=shift; # the page the data comes from
688         my $destpage=shift; # the page the data will appear in (different for inline)
689         my $content=shift;
690         my $scan=shift;
691         my $preview=shift;
693         # Using local because it needs to be set within any nested calls
694         # of this function.
695         local $preprocess_preview=$preview if defined $preview;
697         my $handle=sub {
698                 my $escape=shift;
699                 my $prefix=shift;
700                 my $command=shift;
701                 my $params=shift;
702                 if (length $escape) {
703                         return "[[$prefix$command $params]]";
704                 }
705                 elsif (exists $hooks{preprocess}{$command}) {
706                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
707                         # Note: preserve order of params, some plugins may
708                         # consider it significant.
709                         my @params;
710                         while ($params =~ m{
711                                 (?:([-\w]+)=)?          # 1: named parameter key?
712                                 (?:
713                                         """(.*?)"""     # 2: triple-quoted value
714                                 |
715                                         "([^"]+)"       # 3: single-quoted value
716                                 |
717                                         (\S+)           # 4: unquoted value
718                                 )
719                                 (?:\s+|$)               # delimiter to next param
720                         }sgx) {
721                                 my $key=$1;
722                                 my $val;
723                                 if (defined $2) {
724                                         $val=$2;
725                                         $val=~s/\r\n/\n/mg;
726                                         $val=~s/^\n+//g;
727                                         $val=~s/\n+$//g;
728                                 }
729                                 elsif (defined $3) {
730                                         $val=$3;
731                                 }
732                                 elsif (defined $4) {
733                                         $val=$4;
734                                 }
736                                 if (defined $key) {
737                                         push @params, $key, $val;
738                                 }
739                                 else {
740                                         push @params, $val, '';
741                                 }
742                         }
743                         if ($preprocessing{$page}++ > 3) {
744                                 # Avoid loops of preprocessed pages preprocessing
745                                 # other pages that preprocess them, etc.
746                                 #translators: The first parameter is a
747                                 #translators: preprocessor directive name,
748                                 #translators: the second a page name, the
749                                 #translators: third a number.
750                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
751                                         $command, $page, $preprocessing{$page}).
752                                 "]]";
753                         }
754                         my $ret;
755                         if (! $scan) {
756                                 $ret=$hooks{preprocess}{$command}{call}->(
757                                         @params,
758                                         page => $page,
759                                         destpage => $destpage,
760                                         preview => $preprocess_preview,
761                                 );
762                         }
763                         else {
764                                 # use void context during scan pass
765                                 $hooks{preprocess}{$command}{call}->(
766                                         @params,
767                                         page => $page,
768                                         destpage => $destpage,
769                                         preview => $preprocess_preview,
770                                 );
771                                 $ret="";
772                         }
773                         $preprocessing{$page}--;
774                         return $ret;
775                 }
776                 else {
777                         return "[[$prefix$command $params]]";
778                 }
779         };
780         
781         my $regex;
782         if ($config{prefix_directives}) {
783                 $regex = qr{
784                         (\\?)           # 1: escape?
785                         \[\[(!)         # directive open; 2: prefix
786                         ([-\w]+)        # 3: command
787                         (               # 4: the parameters..
788                                 \s+     # Must have space if parameters present
789                                 (?:
790                                         (?:[-\w]+=)?            # named parameter key?
791                                         (?:
792                                                 """.*?"""       # triple-quoted value
793                                                 |
794                                                 "[^"]+"         # single-quoted value
795                                                 |
796                                                 [^\s\]]+        # unquoted value
797                                         )
798                                         \s*                     # whitespace or end
799                                                                 # of directive
800                                 )
801                         *)?             # 0 or more parameters
802                         \]\]            # directive closed
803                 }sx;
804         } else {
805                 $regex = qr{
806                         (\\?)           # 1: escape?
807                         \[\[(!?)        # directive open; 2: optional prefix
808                         ([-\w]+)        # 3: command
809                         \s+
810                         (               # 4: the parameters..
811                                 (?:
812                                         (?:[-\w]+=)?            # named parameter key?
813                                         (?:
814                                                 """.*?"""       # triple-quoted value
815                                                 |
816                                                 "[^"]+"         # single-quoted value
817                                                 |
818                                                 [^\s\]]+        # unquoted value
819                                         )
820                                         \s*                     # whitespace or end
821                                                                 # of directive
822                                 )
823                         *)              # 0 or more parameters
824                         \]\]            # directive closed
825                 }sx;
826         }
828         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
829         return $content;
830 } #}}}
832 sub filter ($$$) { #{{{
833         my $page=shift;
834         my $destpage=shift;
835         my $content=shift;
837         run_hooks(filter => sub {
838                 $content=shift->(page => $page, destpage => $destpage, 
839                         content => $content);
840         });
842         return $content;
843 } #}}}
845 sub indexlink () { #{{{
846         return "<a href=\"$config{url}\">$config{wikiname}</a>";
847 } #}}}
849 my $wikilock;
851 sub lockwiki (;$) { #{{{
852         my $wait=@_ ? shift : 1;
853         # Take an exclusive lock on the wiki to prevent multiple concurrent
854         # run issues. The lock will be dropped on program exit.
855         if (! -d $config{wikistatedir}) {
856                 mkdir($config{wikistatedir});
857         }
858         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
859                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
860         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
861                 if ($wait) {
862                         debug("wiki seems to be locked, waiting for lock");
863                         my $wait=600; # arbitrary, but don't hang forever to 
864                                       # prevent process pileup
865                         for (1..$wait) {
866                                 return if flock($wikilock, 2 | 4);
867                                 sleep 1;
868                         }
869                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
870                 }
871                 else {
872                         return 0;
873                 }
874         }
875         return 1;
876 } #}}}
878 sub unlockwiki () { #{{{
879         return close($wikilock) if $wikilock;
880         return;
881 } #}}}
883 my $commitlock;
885 sub commit_hook_enabled () { #{{{
886         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
887                 error("cannot write to $config{wikistatedir}/commitlock: $!");
888         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
889                 close($commitlock) || error("failed closing commitlock: $!");
890                 return 0;
891         }
892         close($commitlock) || error("failed closing commitlock: $!");
893         return 1;
894 } #}}}
896 sub disable_commit_hook () { #{{{
897         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
898                 error("cannot write to $config{wikistatedir}/commitlock: $!");
899         if (! flock($commitlock, 2)) { # LOCK_EX
900                 error("failed to get commit lock");
901         }
902         return 1;
903 } #}}}
905 sub enable_commit_hook () { #{{{
906         return close($commitlock) if $commitlock;
907         return;
908 } #}}}
910 sub loadindex () { #{{{
911         %oldrenderedfiles=%pagectime=();
912         if (! $config{rebuild}) {
913                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
914                 %destsources=%renderedfiles=%pagecase=%pagestate=();
915         }
916         my $in;
917         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
918                 if (-e "$config{wikistatedir}/index") {
919                         system("ikiwiki-transition", "indexdb", $config{srcdir});
920                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
921                 }
922                 else {
923                         return;
924                 }
925         }
926         my $ret=Storable::fd_retrieve($in);
927         if (! defined $ret) {
928                 return 0;
929         }
930         my %index=%$ret;
931         foreach my $src (keys %index) {
932                 my %d=%{$index{$src}};
933                 my $page=pagename($src);
934                 $pagectime{$page}=$d{ctime};
935                 if (! $config{rebuild}) {
936                         $pagesources{$page}=$src;
937                         $pagemtime{$page}=$d{mtime};
938                         $renderedfiles{$page}=$d{dest};
939                         if (exists $d{links} && ref $d{links}) {
940                                 $links{$page}=$d{links};
941                                 $oldlinks{$page}=[@{$d{links}}];
942                         }
943                         if (exists $d{depends}) {
944                                 $depends{$page}=$d{depends};
945                         }
946                         if (exists $d{state}) {
947                                 $pagestate{$page}=$d{state};
948                         }
949                 }
950                 $oldrenderedfiles{$page}=[@{$d{dest}}];
951         }
952         foreach my $page (keys %pagesources) {
953                 $pagecase{lc $page}=$page;
954         }
955         foreach my $page (keys %renderedfiles) {
956                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
957         }
958         return close($in);
959 } #}}}
961 sub saveindex () { #{{{
962         run_hooks(savestate => sub { shift->() });
964         my %hookids;
965         foreach my $type (keys %hooks) {
966                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
967         }
968         my @hookids=keys %hookids;
970         if (! -d $config{wikistatedir}) {
971                 mkdir($config{wikistatedir});
972         }
973         my $newfile="$config{wikistatedir}/indexdb.new";
974         my $cleanup = sub { unlink($newfile) };
975         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
976         my %index;
977         foreach my $page (keys %pagemtime) {
978                 next unless $pagemtime{$page};
979                 my $src=$pagesources{$page};
981                 $index{$src}={
982                         ctime => $pagectime{$page},
983                         mtime => $pagemtime{$page},
984                         dest => $renderedfiles{$page},
985                         links => $links{$page},
986                 };
988                 if (exists $depends{$page}) {
989                         $index{$src}{depends} = $depends{$page};
990                 }
992                 if (exists $pagestate{$page}) {
993                         foreach my $id (@hookids) {
994                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
995                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
996                                 }
997                         }
998                 }
999         }
1000         my $ret=Storable::nstore_fd(\%index, $out);
1001         return if ! defined $ret || ! $ret;
1002         close $out || error("failed saving to $newfile: $!", $cleanup);
1003         rename($newfile, "$config{wikistatedir}/indexdb") ||
1004                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1005         
1006         return 1;
1007 } #}}}
1009 sub template_file ($) { #{{{
1010         my $template=shift;
1012         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1013                 return "$dir/$template" if -e "$dir/$template";
1014         }
1015         return;
1016 } #}}}
1018 sub template_params (@) { #{{{
1019         my $filename=template_file(shift);
1021         if (! defined $filename) {
1022                 return if wantarray;
1023                 return "";
1024         }
1026         my @ret=(
1027                 filter => sub {
1028                         my $text_ref = shift;
1029                         ${$text_ref} = decode_utf8(${$text_ref});
1030                 },
1031                 filename => $filename,
1032                 loop_context_vars => 1,
1033                 die_on_bad_params => 0,
1034                 @_
1035         );
1036         return wantarray ? @ret : {@ret};
1037 } #}}}
1039 sub template ($;@) { #{{{
1040         require HTML::Template;
1041         return HTML::Template->new(template_params(@_));
1042 } #}}}
1044 sub misctemplate ($$;@) { #{{{
1045         my $title=shift;
1046         my $pagebody=shift;
1047         
1048         my $template=template("misc.tmpl");
1049         $template->param(
1050                 title => $title,
1051                 indexlink => indexlink(),
1052                 wikiname => $config{wikiname},
1053                 pagebody => $pagebody,
1054                 baseurl => baseurl(),
1055                 @_,
1056         );
1057         run_hooks(pagetemplate => sub {
1058                 shift->(page => "", destpage => "", template => $template);
1059         });
1060         return $template->output;
1061 }#}}}
1063 sub hook (@) { # {{{
1064         my %param=@_;
1065         
1066         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1067                 error 'hook requires type, call, and id parameters';
1068         }
1070         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1071         
1072         $hooks{$param{type}}{$param{id}}=\%param;
1073         return 1;
1074 } # }}}
1076 sub run_hooks ($$) { # {{{
1077         # Calls the given sub for each hook of the given type,
1078         # passing it the hook function to call.
1079         my $type=shift;
1080         my $sub=shift;
1082         if (exists $hooks{$type}) {
1083                 my @deferred;
1084                 foreach my $id (keys %{$hooks{$type}}) {
1085                         if ($hooks{$type}{$id}{last}) {
1086                                 push @deferred, $id;
1087                                 next;
1088                         }
1089                         $sub->($hooks{$type}{$id}{call});
1090                 }
1091                 foreach my $id (@deferred) {
1092                         $sub->($hooks{$type}{$id}{call});
1093                 }
1094         }
1096         return 1;
1097 } #}}}
1099 sub globlist_to_pagespec ($) { #{{{
1100         my @globlist=split(' ', shift);
1102         my (@spec, @skip);
1103         foreach my $glob (@globlist) {
1104                 if ($glob=~/^!(.*)/) {
1105                         push @skip, $glob;
1106                 }
1107                 else {
1108                         push @spec, $glob;
1109                 }
1110         }
1112         my $spec=join(' or ', @spec);
1113         if (@skip) {
1114                 my $skip=join(' and ', @skip);
1115                 if (length $spec) {
1116                         $spec="$skip and ($spec)";
1117                 }
1118                 else {
1119                         $spec=$skip;
1120                 }
1121         }
1122         return $spec;
1123 } #}}}
1125 sub is_globlist ($) { #{{{
1126         my $s=shift;
1127         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1128 } #}}}
1130 sub safequote ($) { #{{{
1131         my $s=shift;
1132         $s=~s/[{}]//g;
1133         return "q{$s}";
1134 } #}}}
1136 sub add_depends ($$) { #{{{
1137         my $page=shift;
1138         my $pagespec=shift;
1139         
1140         return unless pagespec_valid($pagespec);
1142         if (! exists $depends{$page}) {
1143                 $depends{$page}=$pagespec;
1144         }
1145         else {
1146                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1147         }
1149         return 1;
1150 } # }}}
1152 sub file_pruned ($$) { #{{{
1153         require File::Spec;
1154         my $file=File::Spec->canonpath(shift);
1155         my $base=File::Spec->canonpath(shift);
1156         $file =~ s#^\Q$base\E/+##;
1158         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1159         return $file =~ m/$regexp/ && $file ne $base;
1160 } #}}}
1162 sub gettext { #{{{
1163         # Only use gettext in the rare cases it's needed.
1164         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1165             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1166             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1167                 if (! $gettext_obj) {
1168                         $gettext_obj=eval q{
1169                                 use Locale::gettext q{textdomain};
1170                                 Locale::gettext->domain('ikiwiki')
1171                         };
1172                         if ($@) {
1173                                 print STDERR "$@";
1174                                 $gettext_obj=undef;
1175                                 return shift;
1176                         }
1177                 }
1178                 return $gettext_obj->get(shift);
1179         }
1180         else {
1181                 return shift;
1182         }
1183 } #}}}
1185 sub pagespec_merge ($$) { #{{{
1186         my $a=shift;
1187         my $b=shift;
1189         return $a if $a eq $b;
1191         # Support for old-style GlobLists.
1192         if (is_globlist($a)) {
1193                 $a=globlist_to_pagespec($a);
1194         }
1195         if (is_globlist($b)) {
1196                 $b=globlist_to_pagespec($b);
1197         }
1199         return "($a) or ($b)";
1200 } #}}}
1202 sub pagespec_translate ($) { #{{{
1203         my $spec=shift;
1205         # Support for old-style GlobLists.
1206         if (is_globlist($spec)) {
1207                 $spec=globlist_to_pagespec($spec);
1208         }
1210         # Convert spec to perl code.
1211         my $code="";
1212         while ($spec=~m{
1213                 \s*             # ignore whitespace
1214                 (               # 1: match a single word
1215                         \!              # !
1216                 |
1217                         \(              # (
1218                 |
1219                         \)              # )
1220                 |
1221                         \w+\([^\)]*\)   # command(params)
1222                 |
1223                         [^\s()]+        # any other text
1224                 )
1225                 \s*             # ignore whitespace
1226         }igx) {
1227                 my $word=$1;
1228                 if (lc $word eq 'and') {
1229                         $code.=' &&';
1230                 }
1231                 elsif (lc $word eq 'or') {
1232                         $code.=' ||';
1233                 }
1234                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1235                         $code.=' '.$word;
1236                 }
1237                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1238                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1239                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1240                         }
1241                         else {
1242                                 $code.=' 0';
1243                         }
1244                 }
1245                 else {
1246                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1247                 }
1248         }
1250         if (! length $code) {
1251                 $code=0;
1252         }
1254         return eval 'sub { my $page=shift; '.$code.' }';
1255 } #}}}
1257 sub pagespec_match ($$;@) { #{{{
1258         my $page=shift;
1259         my $spec=shift;
1260         my @params=@_;
1262         # Backwards compatability with old calling convention.
1263         if (@params == 1) {
1264                 unshift @params, 'location';
1265         }
1267         my $sub=pagespec_translate($spec);
1268         return IkiWiki::FailReason->new('syntax error') if $@;
1269         return $sub->($page, @params);
1270 } #}}}
1272 sub pagespec_valid ($) { #{{{
1273         my $spec=shift;
1275         my $sub=pagespec_translate($spec);
1276         return ! $@;
1277 } #}}}
1279 package IkiWiki::FailReason;
1281 use overload ( #{{{
1282         '""'    => sub { ${$_[0]} },
1283         '0+'    => sub { 0 },
1284         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1285         fallback => 1,
1286 ); #}}}
1288 sub new { #{{{
1289         return bless \$_[1], $_[0];
1290 } #}}}
1292 package IkiWiki::SuccessReason;
1294 use overload ( #{{{
1295         '""'    => sub { ${$_[0]} },
1296         '0+'    => sub { 1 },
1297         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1298         fallback => 1,
1299 ); #}}}
1301 sub new { #{{{
1302         return bless \$_[1], $_[0];
1303 }; #}}}
1305 package IkiWiki::PageSpec;
1307 sub match_glob ($$;@) { #{{{
1308         my $page=shift;
1309         my $glob=shift;
1310         my %params=@_;
1311         
1312         my $from=exists $params{location} ? $params{location} : '';
1313         
1314         # relative matching
1315         if ($glob =~ m!^\./!) {
1316                 $from=~s#/?[^/]+$##;
1317                 $glob=~s#^\./##;
1318                 $glob="$from/$glob" if length $from;
1319         }
1321         # turn glob into safe regexp
1322         $glob=quotemeta($glob);
1323         $glob=~s/\\\*/.*/g;
1324         $glob=~s/\\\?/./g;
1326         if ($page=~/^$glob$/i) {
1327                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1328                         return IkiWiki::SuccessReason->new("$glob matches $page");
1329                 }
1330                 else {
1331                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1332                 }
1333         }
1334         else {
1335                 return IkiWiki::FailReason->new("$glob does not match $page");
1336         }
1337 } #}}}
1339 sub match_internal ($$;@) { #{{{
1340         return match_glob($_[0], $_[1], @_, internal => 1)
1341 } #}}}
1343 sub match_link ($$;@) { #{{{
1344         my $page=shift;
1345         my $link=lc(shift);
1346         my %params=@_;
1348         my $from=exists $params{location} ? $params{location} : '';
1350         # relative matching
1351         if ($link =~ m!^\.! && defined $from) {
1352                 $from=~s#/?[^/]+$##;
1353                 $link=~s#^\./##;
1354                 $link="$from/$link" if length $from;
1355         }
1357         my $links = $IkiWiki::links{$page};
1358         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1359         my $bestlink = IkiWiki::bestlink($from, $link);
1360         foreach my $p (@{$links}) {
1361                 if (length $bestlink) {
1362                         return IkiWiki::SuccessReason->new("$page links to $link")
1363                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1364                 }
1365                 else {
1366                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1367                                 if match_glob($p, $link, %params);
1368                 }
1369         }
1370         return IkiWiki::FailReason->new("$page does not link to $link");
1371 } #}}}
1373 sub match_backlink ($$;@) { #{{{
1374         return match_link($_[1], $_[0], @_);
1375 } #}}}
1377 sub match_created_before ($$;@) { #{{{
1378         my $page=shift;
1379         my $testpage=shift;
1381         if (exists $IkiWiki::pagectime{$testpage}) {
1382                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1383                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1384                 }
1385                 else {
1386                         return IkiWiki::FailReason->new("$page not created before $testpage");
1387                 }
1388         }
1389         else {
1390                 return IkiWiki::FailReason->new("$testpage has no ctime");
1391         }
1392 } #}}}
1394 sub match_created_after ($$;@) { #{{{
1395         my $page=shift;
1396         my $testpage=shift;
1398         if (exists $IkiWiki::pagectime{$testpage}) {
1399                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1400                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1401                 }
1402                 else {
1403                         return IkiWiki::FailReason->new("$page not created after $testpage");
1404                 }
1405         }
1406         else {
1407                 return IkiWiki::FailReason->new("$testpage has no ctime");
1408         }
1409 } #}}}
1411 sub match_creation_day ($$;@) { #{{{
1412         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1413                 return IkiWiki::SuccessReason->new('creation_day matched');
1414         }
1415         else {
1416                 return IkiWiki::FailReason->new('creation_day did not match');
1417         }
1418 } #}}}
1420 sub match_creation_month ($$;@) { #{{{
1421         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1422                 return IkiWiki::SuccessReason->new('creation_month matched');
1423         }
1424         else {
1425                 return IkiWiki::FailReason->new('creation_month did not match');
1426         }
1427 } #}}}
1429 sub match_creation_year ($$;@) { #{{{
1430         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1431                 return IkiWiki::SuccessReason->new('creation_year matched');
1432         }
1433         else {
1434                 return IkiWiki::FailReason->new('creation_year did not match');
1435         }
1436 } #}}}