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