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