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