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