enhancesments for shared hosting
[ikiwiki.git] / IkiWiki.pm
1 #!/usr/bin/perl
2
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};
12
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14             %pagestate %renderedfiles %oldrenderedfiles %pagesources
15             %destsources %depends %hooks %forcerebuild $gettext_obj};
16
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
27
28 # Optimisation.
29 use Memoize;
30 memoize("abs2rel");
31 memoize("pagespec_translate");
32 memoize("file_pruned");
33
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 } #}}}
92
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         }
105
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         }
115
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         }
132
133         if (exists $config{umask}) {
134                 umask(possibly_foolish_untaint($config{umask}));
135         }
136
137         run_hooks(checkconfig => sub { shift->() });
138
139         return 1;
140 } #}}}
141
142 sub loadplugins () { #{{{
143         if (defined $config{libdir}) {
144                 unshift @INC, possibly_foolish_untaint($config{libdir});
145         }
146
147         loadplugin($_) foreach @{$config{plugin}};
148
149         run_hooks(getopt => sub { shift->() });
150         if (grep /^-/, @ARGV) {
151                 print STDERR "Unknown option: $_\n"
152                         foreach grep /^-/, @ARGV;
153                 usage();
154         }
155
156         return 1;
157 } #}}}
158
159 sub loadplugin ($) { #{{{
160         my $plugin=shift;
161
162         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
163
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         }
172
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 } #}}}
180
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 } #}}}
195
196 sub debug ($) { #{{{
197         return unless $config{verbose};
198         return log_message(debug => @_);
199 } #}}}
200
201 my $log_open=0;
202 sub log_message ($$) { #{{{
203         my $type=shift;
204
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 } #}}}
223
224 sub possibly_foolish_untaint ($) { #{{{
225         my $tainted=shift;
226         my ($untainted)=$tainted=~/(.*)/s;
227         return $untainted;
228 } #}}}
229
230 sub basename ($) { #{{{
231         my $file=shift;
232
233         $file=~s!.*/+!!;
234         return $file;
235 } #}}}
236
237 sub dirname ($) { #{{{
238         my $file=shift;
239
240         $file=~s!/*[^/]+$!!;
241         return $file;
242 } #}}}
243
244 sub pagetype ($) { #{{{
245         my $page=shift;
246         
247         if ($page =~ /\.([^.]+)$/) {
248                 return $1 if exists $hooks{htmlize}{$1};
249         }
250         return;
251 } #}}}
252
253 sub isinternal ($) { #{{{
254         my $page=shift;
255         return exists $pagesources{$page} &&
256                 $pagesources{$page} =~ /\._([^.]+)$/;
257 } #}}}
258
259 sub pagename ($) { #{{{
260         my $file=shift;
261
262         my $type=pagetype($file);
263         my $page=$file;
264         $page=~s/\Q.$type\E*$// if defined $type;
265         return $page;
266 } #}}}
267
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 } #}}}
278
279 sub htmlpage ($) { #{{{
280         my $page=shift;
281         
282         return targetpage($page, $config{htmlext});
283 } #}}}
284
285 sub srcfile ($;$) { #{{{
286         my $file=shift;
287         my $nothrow=shift;
288
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 } #}}}
296
297 sub add_underlay ($) { #{{{
298         my $dir=shift;
299
300         if ($dir=~/^\//) {
301                 unshift @{$config{underlaydirs}}, $dir;
302         }
303         else {
304                 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
305         }
306
307         return 1;
308 } #}}}
309
310 sub readfile ($;$$) { #{{{
311         my $file=shift;
312         my $binary=shift;
313         my $wantfd=shift;
314
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 } #}}}
327
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         }
339
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         }
350
351         return 1;
352 }
353
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);
380
381         return 1;
382 } #}}}
383
384 my %cleared;
385 sub will_render ($$;$) { #{{{
386         my $page=shift;
387         my $dest=shift;
388         my $clear=shift;
389
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         }
395
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;
407
408         return 1;
409 } #}}}
410
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/\/$//;
421
422         do {
423                 my $l=$cwd;
424                 $l.="/" if length $l;
425                 $l.=$link;
426
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!/?[^/]+$!!;
434
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         }
444
445         #print STDERR "warning: page $page, broken link: $link\n";
446         return "";
447 } #}}}
448
449 sub isinlinableimage ($) { #{{{
450         my $file=shift;
451         
452         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
453 } #}}}
454
455 sub pagetitle ($;$) { #{{{
456         my $page=shift;
457         my $unescaped=shift;
458
459         if ($unescaped) {
460                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
461         }
462         else {
463                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
464         }
465
466         return $page;
467 } #}}}
468
469 sub titlepage ($) { #{{{
470         my $title=shift;
471         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
472         return $title;
473 } #}}}
474
475 sub linkpage ($) { #{{{
476         my $link=shift;
477         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
478         return $link;
479 } #}}}
480
481 sub cgiurl (@) { #{{{
482         my %params=@_;
483
484         return $config{cgiurl}."?".
485                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
486 } #}}}
487
488 sub baseurl (;$) { #{{{
489         my $page=shift;
490
491         return "$config{url}/" if ! defined $page;
492         
493         $page=htmlpage($page);
494         $page=~s/[^\/]+$//;
495         $page=~s/[^\/]+\//..\//g;
496         return $page;
497 } #}}}
498
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;
505
506         require File::Spec;
507         my $ret=File::Spec->abs2rel($path, $base);
508         $ret=~s/^// if defined $ret;
509         return $ret;
510 } #}}}
511
512 sub displaytime ($;$) { #{{{
513         my $time=shift;
514         my $format=shift;
515         if (! defined $format) {
516                 $format=$config{timeformat};
517         }
518
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 } #}}}
523
524 sub beautify_url ($) { #{{{
525         my $url=shift;
526
527         if ($config{usedirs}) {
528                 $url =~ s!/index.$config{htmlext}$!/!;
529         }
530         $url =~ s!^$!./!; # Browsers don't like empty links...
531
532         return $url;
533 } #}}}
534
535 sub urlto ($$) { #{{{
536         my $to=shift;
537         my $from=shift;
538
539         if (! length $to) {
540                 return beautify_url(baseurl($from));
541         }
542
543         if (! $destsources{$to}) {
544                 $to=htmlpage($to);
545         }
546
547         my $link = abs2rel($to, dirname(htmlpage($from)));
548
549         return beautify_url($link);
550 } #}}}
551
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=@_;
557
558         $link=~s/\/$//;
559
560         my $bestlink;
561         if (! $opts{forcesubpage}) {
562                 $bestlink=bestlink($lpage, $link);
563         }
564         else {
565                 $bestlink="$lpage/".lc($link);
566         }
567
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);
582
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         }
601
602         if (defined $opts{anchor}) {
603                 $bestlink.="#".$opts{anchor};
604         }
605
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         }
613
614         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
615 } #}}}
616
617 sub userlink ($) { #{{{
618         my $user=shift;
619
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 $@;
627
628                 return htmllink("", "", escapeHTML(
629                         length $config{userdir} ? $config{userdir}."/".$user : $user
630                 ), noimageinline => 1);
631         }
632 } #}}}
633
634 sub htmlize ($$$) { #{{{
635         my $page=shift;
636         my $type=shift;
637         my $content=shift;
638         
639         my $oneline = $content !~ /\n/;
640
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         }
650
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         }
665
666         return $content;
667 } #}}}
668
669 sub linkify ($$$) { #{{{
670         my $page=shift;
671         my $destpage=shift;
672         my $content=shift;
673
674         run_hooks(linkify => sub {
675                 $content=shift->(
676                         page => $page,
677                         destpage => $destpage,
678                         content => $content,
679                 );
680         });
681         
682         return $content;
683 } #}}}
684
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;
693
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;
697
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                                 }
736
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         }
828
829         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
830         return $content;
831 } #}}}
832
833 sub filter ($$$) { #{{{
834         my $page=shift;
835         my $destpage=shift;
836         my $content=shift;
837
838         run_hooks(filter => sub {
839                 $content=shift->(page => $page, destpage => $destpage, 
840                         content => $content);
841         });
842
843         return $content;
844 } #}}}
845
846 sub indexlink () { #{{{
847         return "<a href=\"$config{url}\">$config{wikiname}</a>";
848 } #}}}
849
850 my $wikilock;
851
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 } #}}}
878
879 sub unlockwiki () { #{{{
880         return close($wikilock) if $wikilock;
881         return;
882 } #}}}
883
884 my $commitlock;
885
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 } #}}}
896
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 } #}}}
905
906 sub enable_commit_hook () { #{{{
907         return close($commitlock) if $commitlock;
908         return;
909 } #}}}
910
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 } #}}}
961
962 sub saveindex () { #{{{
963         run_hooks(savestate => sub { shift->() });
964
965         my %hookids;
966         foreach my $type (keys %hooks) {
967                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
968         }
969         my @hookids=keys %hookids;
970
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};
981
982                 $index{$src}={
983                         ctime => $pagectime{$page},
984                         mtime => $pagemtime{$page},
985                         dest => $renderedfiles{$page},
986                         links => $links{$page},
987                 };
988
989                 if (exists $depends{$page}) {
990                         $index{$src}{depends} = $depends{$page};
991                 }
992
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 } #}}}
1009
1010 sub template_file ($) { #{{{
1011         my $template=shift;
1012
1013         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1014                 return "$dir/$template" if -e "$dir/$template";
1015         }
1016         return;
1017 } #}}}
1018
1019 sub template_params (@) { #{{{
1020         my $filename=template_file(shift);
1021
1022         if (! defined $filename) {
1023                 return if wantarray;
1024                 return "";
1025         }
1026
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 } #}}}
1039
1040 sub template ($;@) { #{{{
1041         require HTML::Template;
1042         return HTML::Template->new(template_params(@_));
1043 } #}}}
1044
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 }#}}}
1063
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         }
1070
1071         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1072         
1073         $hooks{$param{type}}{$param{id}}=\%param;
1074         return 1;
1075 } # }}}
1076
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;
1082
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         }
1096
1097         return 1;
1098 } #}}}
1099
1100 sub globlist_to_pagespec ($) { #{{{
1101         my @globlist=split(' ', shift);
1102
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         }
1112
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 } #}}}
1125
1126 sub is_globlist ($) { #{{{
1127         my $s=shift;
1128         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1129 } #}}}
1130
1131 sub safequote ($) { #{{{
1132         my $s=shift;
1133         $s=~s/[{}]//g;
1134         return "q{$s}";
1135 } #}}}
1136
1137 sub add_depends ($$) { #{{{
1138         my $page=shift;
1139         my $pagespec=shift;
1140         
1141         return unless pagespec_valid($pagespec);
1142
1143         if (! exists $depends{$page}) {
1144                 $depends{$page}=$pagespec;
1145         }
1146         else {
1147                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1148         }
1149
1150         return 1;
1151 } # }}}
1152
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/+##;
1158
1159         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1160         return $file =~ m/$regexp/ && $file ne $base;
1161 } #}}}
1162
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 } #}}}
1185
1186 sub pagespec_merge ($$) { #{{{
1187         my $a=shift;
1188         my $b=shift;
1189
1190         return $a if $a eq $b;
1191
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         }
1199
1200         return "($a) or ($b)";
1201 } #}}}
1202
1203 sub pagespec_translate ($) { #{{{
1204         my $spec=shift;
1205
1206         # Support for old-style GlobLists.
1207         if (is_globlist($spec)) {
1208                 $spec=globlist_to_pagespec($spec);
1209         }
1210
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         }
1250
1251         if (! length $code) {
1252                 $code=0;
1253         }
1254
1255         return eval 'sub { my $page=shift; '.$code.' }';
1256 } #}}}
1257
1258 sub pagespec_match ($$;@) { #{{{
1259         my $page=shift;
1260         my $spec=shift;
1261         my @params=@_;
1262
1263         # Backwards compatability with old calling convention.
1264         if (@params == 1) {
1265                 unshift @params, 'location';
1266         }
1267
1268         my $sub=pagespec_translate($spec);
1269         return IkiWiki::FailReason->new('syntax error') if $@;
1270         return $sub->($page, @params);
1271 } #}}}
1272
1273 sub pagespec_valid ($) { #{{{
1274         my $spec=shift;
1275
1276         my $sub=pagespec_translate($spec);
1277         return ! $@;
1278 } #}}}
1279
1280 package IkiWiki::FailReason;
1281
1282 use overload ( #{{{
1283         '""'    => sub { ${$_[0]} },
1284         '0+'    => sub { 0 },
1285         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1286         fallback => 1,
1287 ); #}}}
1288
1289 sub new { #{{{
1290         my $class = shift;
1291         my $value = shift;
1292         return bless \$value, $class;
1293 } #}}}
1294
1295 package IkiWiki::SuccessReason;
1296
1297 use overload ( #{{{
1298         '""'    => sub { ${$_[0]} },
1299         '0+'    => sub { 1 },
1300         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1301         fallback => 1,
1302 ); #}}}
1303
1304 sub new { #{{{
1305         my $class = shift;
1306         my $value = shift;
1307         return bless \$value, $class;
1308 }; #}}}
1309
1310 package IkiWiki::PageSpec;
1311
1312 sub match_glob ($$;@) { #{{{
1313         my $page=shift;
1314         my $glob=shift;
1315         my %params=@_;
1316         
1317         my $from=exists $params{location} ? $params{location} : '';
1318         
1319         # relative matching
1320         if ($glob =~ m!^\./!) {
1321                 $from=~s#/?[^/]+$##;
1322                 $glob=~s#^\./##;
1323                 $glob="$from/$glob" if length $from;
1324         }
1325
1326         # turn glob into safe regexp
1327         $glob=quotemeta($glob);
1328         $glob=~s/\\\*/.*/g;
1329         $glob=~s/\\\?/./g;
1330
1331         if ($page=~/^$glob$/i) {
1332                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1333                         return IkiWiki::SuccessReason->new("$glob matches $page");
1334                 }
1335                 else {
1336                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1337                 }
1338         }
1339         else {
1340                 return IkiWiki::FailReason->new("$glob does not match $page");
1341         }
1342 } #}}}
1343
1344 sub match_internal ($$;@) { #{{{
1345         return match_glob($_[0], $_[1], @_, internal => 1)
1346 } #}}}
1347
1348 sub match_link ($$;@) { #{{{
1349         my $page=shift;
1350         my $link=lc(shift);
1351         my %params=@_;
1352
1353         my $from=exists $params{location} ? $params{location} : '';
1354
1355         # relative matching
1356         if ($link =~ m!^\.! && defined $from) {
1357                 $from=~s#/?[^/]+$##;
1358                 $link=~s#^\./##;
1359                 $link="$from/$link" if length $from;
1360         }
1361
1362         my $links = $IkiWiki::links{$page};
1363         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1364         my $bestlink = IkiWiki::bestlink($from, $link);
1365         foreach my $p (@{$links}) {
1366                 if (length $bestlink) {
1367                         return IkiWiki::SuccessReason->new("$page links to $link")
1368                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1369                 }
1370                 else {
1371                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1372                                 if match_glob($p, $link, %params);
1373                 }
1374         }
1375         return IkiWiki::FailReason->new("$page does not link to $link");
1376 } #}}}
1377
1378 sub match_backlink ($$;@) { #{{{
1379         return match_link($_[1], $_[0], @_);
1380 } #}}}
1381
1382 sub match_created_before ($$;@) { #{{{
1383         my $page=shift;
1384         my $testpage=shift;
1385
1386         if (exists $IkiWiki::pagectime{$testpage}) {
1387                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1388                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1389                 }
1390                 else {
1391                         return IkiWiki::FailReason->new("$page not created before $testpage");
1392                 }
1393         }
1394         else {
1395                 return IkiWiki::FailReason->new("$testpage has no ctime");
1396         }
1397 } #}}}
1398
1399 sub match_created_after ($$;@) { #{{{
1400         my $page=shift;
1401         my $testpage=shift;
1402
1403         if (exists $IkiWiki::pagectime{$testpage}) {
1404                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1405                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1406                 }
1407                 else {
1408                         return IkiWiki::FailReason->new("$page not created after $testpage");
1409                 }
1410         }
1411         else {
1412                 return IkiWiki::FailReason->new("$testpage has no ctime");
1413         }
1414 } #}}}
1415
1416 sub match_creation_day ($$;@) { #{{{
1417         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1418                 return IkiWiki::SuccessReason->new('creation_day matched');
1419         }
1420         else {
1421                 return IkiWiki::FailReason->new('creation_day did not match');
1422         }
1423 } #}}}
1424
1425 sub match_creation_month ($$;@) { #{{{
1426         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1427                 return IkiWiki::SuccessReason->new('creation_month matched');
1428         }
1429         else {
1430                 return IkiWiki::FailReason->new('creation_month did not match');
1431         }
1432 } #}}}
1433
1434 sub match_creation_year ($$;@) { #{{{
1435         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1436                 return IkiWiki::SuccessReason->new('creation_year matched');
1437         }
1438         else {
1439                 return IkiWiki::FailReason->new('creation_year did not match');
1440         }
1441 } #}}}
1442
1443 1