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