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