]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
po plugin: replace tweakurlpath hook with a wrapper function
[ikiwiki.git] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use Encode;
8 use HTML::Entities;
9 use URI::Escape q{uri_escape_utf8};
10 use POSIX;
11 use Storable;
12 use open qw{:utf8 :std};
13
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15             %pagestate %wikistate %renderedfiles %oldrenderedfiles
16             %pagesources %destsources %depends %hooks %forcerebuild
17             $gettext_obj %loaded_plugins};
18
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21                  bestlink htmllink readfile writefile pagetype srcfile pagename
22                  displaytime will_render gettext urlto targetpage
23                  add_underlay pagetitle titlepage linkpage newpagefile
24                  inject
25                  %config %links %pagestate %wikistate %renderedfiles
26                  %pagesources %destsources);
27 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
30
31 # Optimisation.
32 use Memoize;
33 memoize("abs2rel");
34 memoize("pagespec_translate");
35 memoize("file_pruned");
36
37 sub getsetup () { #{{{
38         wikiname => {
39                 type => "string",
40                 default => "wiki",
41                 description => "name of the wiki",
42                 safe => 1,
43                 rebuild => 1,
44         },
45         adminemail => {
46                 type => "string",
47                 default => undef,
48                 example => 'me@example.com',
49                 description => "contact email for wiki",
50                 safe => 1,
51                 rebuild => 0,
52         },
53         adminuser => {
54                 type => "string",
55                 default => [],
56                 description => "users who are wiki admins",
57                 safe => 1,
58                 rebuild => 0,
59         },
60         banned_users => {
61                 type => "string",
62                 default => [],
63                 description => "users who are banned from the wiki",
64                 safe => 1,
65                 rebuild => 0,
66         },
67         srcdir => {
68                 type => "string",
69                 default => undef,
70                 example => "$ENV{HOME}/wiki",
71                 description => "where the source of the wiki is located",
72                 safe => 0, # path
73                 rebuild => 1,
74         },
75         destdir => {
76                 type => "string",
77                 default => undef,
78                 example => "/var/www/wiki",
79                 description => "where to build the wiki",
80                 safe => 0, # path
81                 rebuild => 1,
82         },
83         url => {
84                 type => "string",
85                 default => '',
86                 example => "http://example.com/wiki",
87                 description => "base url to the wiki",
88                 safe => 1,
89                 rebuild => 1,
90         },
91         cgiurl => {
92                 type => "string",
93                 default => '',
94                 example => "http://example.com/wiki/ikiwiki.cgi",
95                 description => "url to the ikiwiki.cgi",
96                 safe => 1,
97                 rebuild => 1,
98         },
99         cgi_wrapper => {
100                 type => "string",
101                 default => '',
102                 example => "/var/www/wiki/ikiwiki.cgi",
103                 description => "cgi wrapper to generate",
104                 safe => 0, # file
105                 rebuild => 0,
106         },
107         cgi_wrappermode => {
108                 type => "string",
109                 default => '06755',
110                 description => "mode for cgi_wrapper (can safely be made suid)",
111                 safe => 0,
112                 rebuild => 0,
113         },
114         rcs => {
115                 type => "string",
116                 default => '',
117                 description => "rcs backend to use",
118                 safe => 0, # don't allow overriding
119                 rebuild => 0,
120         },
121         default_plugins => {
122                 type => "internal",
123                 default => [qw{mdwn link inline htmlscrubber passwordauth
124                                 openid signinedit lockedit conditional
125                                 recentchanges parentlinks editpage}],
126                 description => "plugins to enable by default",
127                 safe => 0,
128                 rebuild => 1,
129         },
130         add_plugins => {
131                 type => "string",
132                 default => [],
133                 description => "plugins to add to the default configuration",
134                 safe => 1,
135                 rebuild => 1,
136         },
137         disable_plugins => {
138                 type => "string",
139                 default => [],
140                 description => "plugins to disable",
141                 safe => 1,
142                 rebuild => 1,
143         },
144         templatedir => {
145                 type => "string",
146                 default => "$installdir/share/ikiwiki/templates",
147                 description => "location of template files",
148                 advanced => 1,
149                 safe => 0, # path
150                 rebuild => 1,
151         },
152         underlaydir => {
153                 type => "string",
154                 default => "$installdir/share/ikiwiki/basewiki",
155                 description => "base wiki source location",
156                 advanced => 1,
157                 safe => 0, # path
158                 rebuild => 0,
159         },
160         wrappers => {
161                 type => "internal",
162                 default => [],
163                 description => "wrappers to generate",
164                 safe => 0,
165                 rebuild => 0,
166         },
167         underlaydirs => {
168                 type => "internal",
169                 default => [],
170                 description => "additional underlays to use",
171                 safe => 0,
172                 rebuild => 0,
173         },
174         verbose => {
175                 type => "boolean",
176                 example => 1,
177                 description => "display verbose messages when building?",
178                 safe => 1,
179                 rebuild => 0,
180         },
181         syslog => {
182                 type => "boolean",
183                 example => 1,
184                 description => "log to syslog?",
185                 safe => 1,
186                 rebuild => 0,
187         },
188         usedirs => {
189                 type => "boolean",
190                 default => 1,
191                 description => "create output files named page/index.html?",
192                 safe => 0, # changing requires manual transition
193                 rebuild => 1,
194         },
195         prefix_directives => {
196                 type => "boolean",
197                 default => 0,
198                 description => "use '!'-prefixed preprocessor directives?",
199                 safe => 0, # changing requires manual transition
200                 rebuild => 1,
201         },
202         indexpages => {
203                 type => "boolean",
204                 default => 0,
205                 description => "use page/index.mdwn source files",
206                 safe => 1,
207                 rebuild => 1,
208         },
209         discussion => {
210                 type => "boolean",
211                 default => 1,
212                 description => "enable Discussion pages?",
213                 safe => 1,
214                 rebuild => 1,
215         },
216         sslcookie => {
217                 type => "boolean",
218                 default => 0,
219                 description => "only send cookies over SSL connections?",
220                 advanced => 1,
221                 safe => 1,
222                 rebuild => 0,
223         },
224         default_pageext => {
225                 type => "string",
226                 default => "mdwn",
227                 description => "extension to use for new pages",
228                 safe => 0, # not sanitized
229                 rebuild => 0,
230         },
231         htmlext => {
232                 type => "string",
233                 default => "html",
234                 description => "extension to use for html files",
235                 safe => 0, # not sanitized
236                 rebuild => 1,
237         },
238         timeformat => {
239                 type => "string",
240                 default => '%c',
241                 description => "strftime format string to display date",
242                 advanced => 1,
243                 safe => 1,
244                 rebuild => 1,
245         },
246         locale => {
247                 type => "string",
248                 default => undef,
249                 example => "en_US.UTF-8",
250                 description => "UTF-8 locale to use",
251                 advanced => 1,
252                 safe => 0,
253                 rebuild => 1,
254         },
255         userdir => {
256                 type => "string",
257                 default => "",
258                 example => "users",
259                 description => "put user pages below specified page",
260                 safe => 1,
261                 rebuild => 1,
262         },
263         numbacklinks => {
264                 type => "integer",
265                 default => 10,
266                 description => "how many backlinks to show before hiding excess (0 to show all)",
267                 safe => 1,
268                 rebuild => 1,
269         },
270         hardlink => {
271                 type => "boolean",
272                 default => 0,
273                 description => "attempt to hardlink source files? (optimisation for large files)",
274                 advanced => 1,
275                 safe => 0, # paranoia
276                 rebuild => 0,
277         },
278         umask => {
279                 type => "integer",
280                 description => "",
281                 example => "022",
282                 description => "force ikiwiki to use a particular umask",
283                 advanced => 1,
284                 safe => 0, # paranoia
285                 rebuild => 0,
286         },
287         libdir => {
288                 type => "string",
289                 default => "",
290                 example => "$ENV{HOME}/.ikiwiki/",
291                 description => "extra library and plugin directory",
292                 advanced => 1,
293                 safe => 0, # directory
294                 rebuild => 0,
295         },
296         ENV => {
297                 type => "string", 
298                 default => {},
299                 description => "environment variables",
300                 safe => 0, # paranoia
301                 rebuild => 0,
302         },
303         exclude => {
304                 type => "string",
305                 default => undef,
306                 example => '\.wav$',
307                 description => "regexp of source files to ignore",
308                 advanced => 1,
309                 safe => 0, # regexp
310                 rebuild => 1,
311         },
312         wiki_file_prune_regexps => {
313                 type => "internal",
314                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
315                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
316                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
317                         qr/(^|\/)_MTN\//,
318                         qr/\.dpkg-tmp$/],
319                 description => "regexps of source files to ignore",
320                 safe => 0,
321                 rebuild => 1,
322         },
323         wiki_file_chars => {
324                 type => "string",
325                 description => "specifies the characters that are allowed in source filenames",
326                 default => "-[:alnum:]+/.:_",
327                 safe => 0,
328                 rebuild => 1,
329         },
330         wiki_file_regexp => {
331                 type => "internal",
332                 description => "regexp of legal source files",
333                 safe => 0,
334                 rebuild => 1,
335         },
336         web_commit_regexp => {
337                 type => "internal",
338                 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
339                 description => "regexp to parse web commits from logs",
340                 safe => 0,
341                 rebuild => 0,
342         },
343         cgi => {
344                 type => "internal",
345                 default => 0,
346                 description => "run as a cgi",
347                 safe => 0,
348                 rebuild => 0,
349         },
350         cgi_disable_uploads => {
351                 type => "internal",
352                 default => 1,
353                 description => "whether CGI should accept file uploads",
354                 safe => 0,
355                 rebuild => 0,
356         },
357         post_commit => {
358                 type => "internal",
359                 default => 0,
360                 description => "run as a post-commit hook",
361                 safe => 0,
362                 rebuild => 0,
363         },
364         rebuild => {
365                 type => "internal",
366                 default => 0,
367                 description => "running in rebuild mode",
368                 safe => 0,
369                 rebuild => 0,
370         },
371         setup => {
372                 type => "internal",
373                 default => undef,
374                 description => "running in setup mode",
375                 safe => 0,
376                 rebuild => 0,
377         },
378         refresh => {
379                 type => "internal",
380                 default => 0,
381                 description => "running in refresh mode",
382                 safe => 0,
383                 rebuild => 0,
384         },
385         test_receive => {
386                 type => "internal",
387                 default => 0,
388                 description => "running in receive test mode",
389                 safe => 0,
390                 rebuild => 0,
391         },
392         getctime => {
393                 type => "internal",
394                 default => 0,
395                 description => "running in getctime mode",
396                 safe => 0,
397                 rebuild => 0,
398         },
399         w3mmode => {
400                 type => "internal",
401                 default => 0,
402                 description => "running in w3mmode",
403                 safe => 0,
404                 rebuild => 0,
405         },
406         setupfile => {
407                 type => "internal",
408                 default => undef,
409                 description => "path to setup file",
410                 safe => 0,
411                 rebuild => 0,
412         },
413         allow_symlinks_before_srcdir => {
414                 type => "boolean",
415                 default => 0,
416                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
417                 safe => 0,
418                 rebuild => 0,
419         },
420 } #}}}
421
422 sub defaultconfig () { #{{{
423         my %s=getsetup();
424         my @ret;
425         foreach my $key (keys %s) {
426                 push @ret, $key, $s{$key}->{default};
427         }
428         use Data::Dumper;
429         return @ret;
430 } #}}}
431
432 sub checkconfig () { #{{{
433         # locale stuff; avoid LC_ALL since it overrides everything
434         if (defined $ENV{LC_ALL}) {
435                 $ENV{LANG} = $ENV{LC_ALL};
436                 delete $ENV{LC_ALL};
437         }
438         if (defined $config{locale}) {
439                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
440                         $ENV{LANG}=$config{locale};
441                         $gettext_obj=undef;
442                 }
443         }
444                 
445         if (! defined $config{wiki_file_regexp}) {
446                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
447         }
448
449         if (ref $config{ENV} eq 'HASH') {
450                 foreach my $val (keys %{$config{ENV}}) {
451                         $ENV{$val}=$config{ENV}{$val};
452                 }
453         }
454
455         if ($config{w3mmode}) {
456                 eval q{use Cwd q{abs_path}};
457                 error($@) if $@;
458                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
459                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
460                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
461                         unless $config{cgiurl} =~ m!file:///!;
462                 $config{url}="file://".$config{destdir};
463         }
464
465         if ($config{cgi} && ! length $config{url}) {
466                 error(gettext("Must specify url to wiki with --url when using --cgi"));
467         }
468         
469         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
470                 unless exists $config{wikistatedir};
471
472         if (defined $config{umask}) {
473                 umask(possibly_foolish_untaint($config{umask}));
474         }
475
476         run_hooks(checkconfig => sub { shift->() });
477
478         return 1;
479 } #}}}
480
481 sub listplugins () { #{{{
482         my %ret;
483
484         foreach my $dir (@INC, $config{libdir}) {
485                 next unless defined $dir && length $dir;
486                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
487                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
488                         $ret{$plugin}=1;
489                 }
490         }
491         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
492                 next unless defined $dir && length $dir;
493                 foreach my $file (glob("$dir/plugins/*")) {
494                         $ret{basename($file)}=1 if -x $file;
495                 }
496         }
497
498         return keys %ret;
499 } #}}}
500
501 sub loadplugins () { #{{{
502         if (defined $config{libdir} && length $config{libdir}) {
503                 unshift @INC, possibly_foolish_untaint($config{libdir});
504         }
505
506         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
507                 loadplugin($plugin);
508         }
509         
510         if ($config{rcs}) {
511                 if (exists $IkiWiki::hooks{rcs}) {
512                         error(gettext("cannot use multiple rcs plugins"));
513                 }
514                 loadplugin($config{rcs});
515         }
516         if (! exists $IkiWiki::hooks{rcs}) {
517                 loadplugin("norcs");
518         }
519
520         run_hooks(getopt => sub { shift->() });
521         if (grep /^-/, @ARGV) {
522                 print STDERR "Unknown option: $_\n"
523                         foreach grep /^-/, @ARGV;
524                 usage();
525         }
526
527         return 1;
528 } #}}}
529
530 sub loadplugin ($) { #{{{
531         my $plugin=shift;
532
533         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
534
535         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
536                          "$installdir/lib/ikiwiki") {
537                 if (defined $dir && -x "$dir/plugins/$plugin") {
538                         eval { require IkiWiki::Plugin::external };
539                         if ($@) {
540                                 my $reason=$@;
541                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
542                         }
543                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
544                         $loaded_plugins{$plugin}=1;
545                         return 1;
546                 }
547         }
548
549         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
550         eval qq{use $mod};
551         if ($@) {
552                 error("Failed to load plugin $mod: $@");
553         }
554         $loaded_plugins{$plugin}=1;
555         return 1;
556 } #}}}
557
558 sub error ($;$) { #{{{
559         my $message=shift;
560         my $cleaner=shift;
561         log_message('err' => $message) if $config{syslog};
562         if (defined $cleaner) {
563                 $cleaner->();
564         }
565         die $message."\n";
566 } #}}}
567
568 sub debug ($) { #{{{
569         return unless $config{verbose};
570         return log_message(debug => @_);
571 } #}}}
572
573 my $log_open=0;
574 sub log_message ($$) { #{{{
575         my $type=shift;
576
577         if ($config{syslog}) {
578                 require Sys::Syslog;
579                 if (! $log_open) {
580                         Sys::Syslog::setlogsock('unix');
581                         Sys::Syslog::openlog('ikiwiki', '', 'user');
582                         $log_open=1;
583                 }
584                 return eval {
585                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
586                 };
587         }
588         elsif (! $config{cgi}) {
589                 return print "@_\n";
590         }
591         else {
592                 return print STDERR "@_\n";
593         }
594 } #}}}
595
596 sub possibly_foolish_untaint ($) { #{{{
597         my $tainted=shift;
598         my ($untainted)=$tainted=~/(.*)/s;
599         return $untainted;
600 } #}}}
601
602 sub basename ($) { #{{{
603         my $file=shift;
604
605         $file=~s!.*/+!!;
606         return $file;
607 } #}}}
608
609 sub dirname ($) { #{{{
610         my $file=shift;
611
612         $file=~s!/*[^/]+$!!;
613         return $file;
614 } #}}}
615
616 sub pagetype ($) { #{{{
617         my $page=shift;
618         
619         if ($page =~ /\.([^.]+)$/) {
620                 return $1 if exists $hooks{htmlize}{$1};
621         }
622         return;
623 } #}}}
624
625 sub isinternal ($) { #{{{
626         my $page=shift;
627         return exists $pagesources{$page} &&
628                 $pagesources{$page} =~ /\._([^.]+)$/;
629 } #}}}
630
631 sub pagename ($) { #{{{
632         my $file=shift;
633
634         my $type=pagetype($file);
635         my $page=$file;
636         $page=~s/\Q.$type\E*$// if defined $type && !$hooks{htmlize}{$type}{keepextension};
637         if ($config{indexpages} && $page=~/(.*)\/index$/) {
638                 $page=$1;
639         }
640         return $page;
641 } #}}}
642
643 sub newpagefile ($$) { #{{{
644         my $page=shift;
645         my $type=shift;
646
647         if (! $config{indexpages} || $page eq 'index') {
648                 return $page.".".$type;
649         }
650         else {
651                 return $page."/index.".$type;
652         }
653 } #}}}
654
655 sub targetpage ($$) { #{{{
656         my $page=shift;
657         my $ext=shift;
658
659         my $targetpage='';
660         run_hooks(targetpage => sub {
661                 $targetpage=shift->(
662                         page => $page,
663                         ext => $ext,
664                 );
665         });
666
667         if (defined $targetpage && (length($targetpage) > 0)) {
668                 return $targetpage;
669         }
670         elsif (! $config{usedirs} || $page eq 'index') {
671                 return $page.".".$ext;
672         }
673         else {
674                 return $page."/index.".$ext;
675         }
676 } #}}}
677
678 sub htmlpage ($) { #{{{
679         my $page=shift;
680         
681         return targetpage($page, $config{htmlext});
682 } #}}}
683
684 sub srcfile_stat { #{{{
685         my $file=shift;
686         my $nothrow=shift;
687
688         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
689         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
690                 return "$dir/$file", stat(_) if -e "$dir/$file";
691         }
692         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
693         return;
694 } #}}}
695
696 sub srcfile ($;$) { #{{{
697         return (srcfile_stat(@_))[0];
698 } #}}}
699
700 sub add_underlay ($) { #{{{
701         my $dir=shift;
702
703         if ($dir !~ /^\//) {
704                 $dir="$config{underlaydir}/../$dir";
705         }
706
707         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
708                 unshift @{$config{underlaydirs}}, $dir;
709         }
710
711         return 1;
712 } #}}}
713
714 sub readfile ($;$$) { #{{{
715         my $file=shift;
716         my $binary=shift;
717         my $wantfd=shift;
718
719         if (-l $file) {
720                 error("cannot read a symlink ($file)");
721         }
722         
723         local $/=undef;
724         open (my $in, "<", $file) || error("failed to read $file: $!");
725         binmode($in) if ($binary);
726         return \*$in if $wantfd;
727         my $ret=<$in>;
728         close $in || error("failed to read $file: $!");
729         return $ret;
730 } #}}}
731
732 sub prep_writefile ($$) { #{{{
733         my $file=shift;
734         my $destdir=shift;
735         
736         my $test=$file;
737         while (length $test) {
738                 if (-l "$destdir/$test") {
739                         error("cannot write to a symlink ($test)");
740                 }
741                 $test=dirname($test);
742         }
743
744         my $dir=dirname("$destdir/$file");
745         if (! -d $dir) {
746                 my $d="";
747                 foreach my $s (split(m!/+!, $dir)) {
748                         $d.="$s/";
749                         if (! -d $d) {
750                                 mkdir($d) || error("failed to create directory $d: $!");
751                         }
752                 }
753         }
754
755         return 1;
756 } #}}}
757
758 sub writefile ($$$;$$) { #{{{
759         my $file=shift; # can include subdirs
760         my $destdir=shift; # directory to put file in
761         my $content=shift;
762         my $binary=shift;
763         my $writer=shift;
764         
765         prep_writefile($file, $destdir);
766         
767         my $newfile="$destdir/$file.ikiwiki-new";
768         if (-l $newfile) {
769                 error("cannot write to a symlink ($newfile)");
770         }
771         
772         my $cleanup = sub { unlink($newfile) };
773         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
774         binmode($out) if ($binary);
775         if ($writer) {
776                 $writer->(\*$out, $cleanup);
777         }
778         else {
779                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
780         }
781         close $out || error("failed saving $newfile: $!", $cleanup);
782         rename($newfile, "$destdir/$file") || 
783                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
784
785         return 1;
786 } #}}}
787
788 my %cleared;
789 sub will_render ($$;$) { #{{{
790         my $page=shift;
791         my $dest=shift;
792         my $clear=shift;
793
794         # Important security check.
795         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
796             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
797                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
798         }
799
800         if (! $clear || $cleared{$page}) {
801                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
802         }
803         else {
804                 foreach my $old (@{$renderedfiles{$page}}) {
805                         delete $destsources{$old};
806                 }
807                 $renderedfiles{$page}=[$dest];
808                 $cleared{$page}=1;
809         }
810         $destsources{$dest}=$page;
811
812         return 1;
813 } #}}}
814
815 sub bestlink ($$) { #{{{
816         my $page=shift;
817         my $link=shift;
818         
819         my $cwd=$page;
820         if ($link=~s/^\/+//) {
821                 # absolute links
822                 $cwd="";
823         }
824         $link=~s/\/$//;
825
826         do {
827                 my $l=$cwd;
828                 $l.="/" if length $l;
829                 $l.=$link;
830
831                 if (exists $links{$l}) {
832                         return $l;
833                 }
834                 elsif (exists $pagecase{lc $l}) {
835                         return $pagecase{lc $l};
836                 }
837         } while $cwd=~s{/?[^/]+$}{};
838
839         if (length $config{userdir}) {
840                 my $l = "$config{userdir}/".lc($link);
841                 if (exists $links{$l}) {
842                         return $l;
843                 }
844                 elsif (exists $pagecase{lc $l}) {
845                         return $pagecase{lc $l};
846                 }
847         }
848
849         #print STDERR "warning: page $page, broken link: $link\n";
850         return "";
851 } #}}}
852
853 sub isinlinableimage ($) { #{{{
854         my $file=shift;
855         
856         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
857 } #}}}
858
859 sub pagetitle ($;$) { #{{{
860         my $page=shift;
861         my $unescaped=shift;
862
863         if ($unescaped) {
864                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
865         }
866         else {
867                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
868         }
869
870         return $page;
871 } #}}}
872
873 sub titlepage ($) { #{{{
874         my $title=shift;
875         # support use w/o %config set
876         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
877         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
878         return $title;
879 } #}}}
880
881 sub linkpage ($) { #{{{
882         my $link=shift;
883         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
884         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
885         return $link;
886 } #}}}
887
888 sub cgiurl (@) { #{{{
889         my %params=@_;
890
891         return $config{cgiurl}."?".
892                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
893 } #}}}
894
895 sub baseurl (;$) { #{{{
896         my $page=shift;
897
898         return "$config{url}/" if ! defined $page;
899         
900         $page=htmlpage($page);
901         $page=~s/[^\/]+$//;
902         $page=~s/[^\/]+\//..\//g;
903         return $page;
904 } #}}}
905
906 sub abs2rel ($$) { #{{{
907         # Work around very innefficient behavior in File::Spec if abs2rel
908         # is passed two relative paths. It's much faster if paths are
909         # absolute! (Debian bug #376658; fixed in debian unstable now)
910         my $path="/".shift;
911         my $base="/".shift;
912
913         require File::Spec;
914         my $ret=File::Spec->abs2rel($path, $base);
915         $ret=~s/^// if defined $ret;
916         return $ret;
917 } #}}}
918
919 sub displaytime ($;$) { #{{{
920         # Plugins can override this function to mark up the time to
921         # display.
922         return '<span class="date">'.formattime(@_).'</span>';
923 } #}}}
924
925 sub formattime ($;$) { #{{{
926         # Plugins can override this function to format the time.
927         my $time=shift;
928         my $format=shift;
929         if (! defined $format) {
930                 $format=$config{timeformat};
931         }
932
933         # strftime doesn't know about encodings, so make sure
934         # its output is properly treated as utf8
935         return decode_utf8(POSIX::strftime($format, localtime($time)));
936 } #}}}
937
938 sub beautify_urlpath ($) { #{{{
939         my $url=shift;
940
941         if ($config{usedirs}) {
942                 $url =~ s!/index.$config{htmlext}$!/!;
943         }
944
945         # Ensure url is not an empty link, and
946         # if it's relative, make that explicit to avoid colon confusion.
947         if ($url !~ /^\//) {
948                 $url="./$url";
949         }
950
951         return $url;
952 } #}}}
953
954 sub urlto ($$;$) { #{{{
955         my $to=shift;
956         my $from=shift;
957         my $absolute=shift;
958         
959         if (! length $to) {
960                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
961         }
962
963         if (! $destsources{$to}) {
964                 $to=htmlpage($to);
965         }
966
967         if ($absolute) {
968                 return $config{url}.beautify_urlpath("/".$to);
969         }
970
971         my $link = abs2rel($to, dirname(htmlpage($from)));
972
973         return beautify_urlpath($link);
974 } #}}}
975
976 sub htmllink ($$$;@) { #{{{
977         my $lpage=shift; # the page doing the linking
978         my $page=shift; # the page that will contain the link (different for inline)
979         my $link=shift;
980         my %opts=@_;
981
982         $link=~s/\/$//;
983
984         my $bestlink;
985         if (! $opts{forcesubpage}) {
986                 $bestlink=bestlink($lpage, $link);
987         }
988         else {
989                 $bestlink="$lpage/".lc($link);
990         }
991
992         my $linktext;
993         if (defined $opts{linktext}) {
994                 $linktext=$opts{linktext};
995         }
996         else {
997                 $linktext=pagetitle(basename($link));
998         }
999         
1000         return "<span class=\"selflink\">$linktext</span>"
1001                 if length $bestlink && $page eq $bestlink &&
1002                    ! defined $opts{anchor};
1003         
1004         if (! $destsources{$bestlink}) {
1005                 $bestlink=htmlpage($bestlink);
1006
1007                 if (! $destsources{$bestlink}) {
1008                         return $linktext unless length $config{cgiurl};
1009                         return "<span class=\"createlink\"><a href=\"".
1010                                 cgiurl(
1011                                         do => "create",
1012                                         page => lc($link),
1013                                         from => $lpage
1014                                 ).
1015                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
1016                 }
1017         }
1018         
1019         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1020         $bestlink=beautify_urlpath($bestlink);
1021         
1022         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1023                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1024         }
1025
1026         if (defined $opts{anchor}) {
1027                 $bestlink.="#".$opts{anchor};
1028         }
1029
1030         my @attrs;
1031         if (defined $opts{rel}) {
1032                 push @attrs, ' rel="'.$opts{rel}.'"';
1033         }
1034         if (defined $opts{class}) {
1035                 push @attrs, ' class="'.$opts{class}.'"';
1036         }
1037
1038         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1039 } #}}}
1040
1041 sub userlink ($) { #{{{
1042         my $user=shift;
1043
1044         my $oiduser=eval { openiduser($user) };
1045         if (defined $oiduser) {
1046                 return "<a href=\"$user\">$oiduser</a>";
1047         }
1048         else {
1049                 eval q{use CGI 'escapeHTML'};
1050                 error($@) if $@;
1051
1052                 return htmllink("", "", escapeHTML(
1053                         length $config{userdir} ? $config{userdir}."/".$user : $user
1054                 ), noimageinline => 1);
1055         }
1056 } #}}}
1057
1058 sub htmlize ($$$$) { #{{{
1059         my $page=shift;
1060         my $destpage=shift;
1061         my $type=shift;
1062         my $content=shift;
1063         
1064         my $oneline = $content !~ /\n/;
1065
1066         if (exists $hooks{htmlize}{$type}) {
1067                 $content=$hooks{htmlize}{$type}{call}->(
1068                         page => $page,
1069                         content => $content,
1070                 );
1071         }
1072         else {
1073                 error("htmlization of $type not supported");
1074         }
1075
1076         run_hooks(sanitize => sub {
1077                 $content=shift->(
1078                         page => $page,
1079                         destpage => $destpage,
1080                         content => $content,
1081                 );
1082         });
1083         
1084         if ($oneline) {
1085                 # hack to get rid of enclosing junk added by markdown
1086                 # and other htmlizers
1087                 $content=~s/^<p>//i;
1088                 $content=~s/<\/p>$//i;
1089                 chomp $content;
1090         }
1091
1092         return $content;
1093 } #}}}
1094
1095 sub linkify ($$$) { #{{{
1096         my $page=shift;
1097         my $destpage=shift;
1098         my $content=shift;
1099
1100         run_hooks(linkify => sub {
1101                 $content=shift->(
1102                         page => $page,
1103                         destpage => $destpage,
1104                         content => $content,
1105                 );
1106         });
1107         
1108         return $content;
1109 } #}}}
1110
1111 our %preprocessing;
1112 our $preprocess_preview=0;
1113 sub preprocess ($$$;$$) { #{{{
1114         my $page=shift; # the page the data comes from
1115         my $destpage=shift; # the page the data will appear in (different for inline)
1116         my $content=shift;
1117         my $scan=shift;
1118         my $preview=shift;
1119
1120         # Using local because it needs to be set within any nested calls
1121         # of this function.
1122         local $preprocess_preview=$preview if defined $preview;
1123
1124         my $handle=sub {
1125                 my $escape=shift;
1126                 my $prefix=shift;
1127                 my $command=shift;
1128                 my $params=shift;
1129                 $params="" if ! defined $params;
1130
1131                 if (length $escape) {
1132                         return "[[$prefix$command $params]]";
1133                 }
1134                 elsif (exists $hooks{preprocess}{$command}) {
1135                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1136                         # Note: preserve order of params, some plugins may
1137                         # consider it significant.
1138                         my @params;
1139                         while ($params =~ m{
1140                                 (?:([-\w]+)=)?          # 1: named parameter key?
1141                                 (?:
1142                                         """(.*?)"""     # 2: triple-quoted value
1143                                 |
1144                                         "([^"]+)"       # 3: single-quoted value
1145                                 |
1146                                         (\S+)           # 4: unquoted value
1147                                 )
1148                                 (?:\s+|$)               # delimiter to next param
1149                         }sgx) {
1150                                 my $key=$1;
1151                                 my $val;
1152                                 if (defined $2) {
1153                                         $val=$2;
1154                                         $val=~s/\r\n/\n/mg;
1155                                         $val=~s/^\n+//g;
1156                                         $val=~s/\n+$//g;
1157                                 }
1158                                 elsif (defined $3) {
1159                                         $val=$3;
1160                                 }
1161                                 elsif (defined $4) {
1162                                         $val=$4;
1163                                 }
1164
1165                                 if (defined $key) {
1166                                         push @params, $key, $val;
1167                                 }
1168                                 else {
1169                                         push @params, $val, '';
1170                                 }
1171                         }
1172                         if ($preprocessing{$page}++ > 3) {
1173                                 # Avoid loops of preprocessed pages preprocessing
1174                                 # other pages that preprocess them, etc.
1175                                 return "[[!$command <span class=\"error\">".
1176                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1177                                                 $page, $preprocessing{$page}).
1178                                         "</span>]]";
1179                         }
1180                         my $ret;
1181                         if (! $scan) {
1182                                 $ret=eval {
1183                                         $hooks{preprocess}{$command}{call}->(
1184                                                 @params,
1185                                                 page => $page,
1186                                                 destpage => $destpage,
1187                                                 preview => $preprocess_preview,
1188                                         );
1189                                 };
1190                                 if ($@) {
1191                                         chomp $@;
1192                                         $ret="[[!$command <span class=\"error\">".
1193                                                 gettext("Error").": $@"."</span>]]";
1194                                 }
1195                         }
1196                         else {
1197                                 # use void context during scan pass
1198                                 eval {
1199                                         $hooks{preprocess}{$command}{call}->(
1200                                                 @params,
1201                                                 page => $page,
1202                                                 destpage => $destpage,
1203                                                 preview => $preprocess_preview,
1204                                         );
1205                                 };
1206                                 $ret="";
1207                         }
1208                         $preprocessing{$page}--;
1209                         return $ret;
1210                 }
1211                 else {
1212                         return "[[$prefix$command $params]]";
1213                 }
1214         };
1215         
1216         my $regex;
1217         if ($config{prefix_directives}) {
1218                 $regex = qr{
1219                         (\\?)           # 1: escape?
1220                         \[\[(!)         # directive open; 2: prefix
1221                         ([-\w]+)        # 3: command
1222                         (               # 4: the parameters..
1223                                 \s+     # Must have space if parameters present
1224                                 (?:
1225                                         (?:[-\w]+=)?            # named parameter key?
1226                                         (?:
1227                                                 """.*?"""       # triple-quoted value
1228                                                 |
1229                                                 "[^"]+"         # single-quoted value
1230                                                 |
1231                                                 [^\s\]]+        # unquoted value
1232                                         )
1233                                         \s*                     # whitespace or end
1234                                                                 # of directive
1235                                 )
1236                         *)?             # 0 or more parameters
1237                         \]\]            # directive closed
1238                 }sx;
1239         }
1240         else {
1241                 $regex = qr{
1242                         (\\?)           # 1: escape?
1243                         \[\[(!?)        # directive open; 2: optional prefix
1244                         ([-\w]+)        # 3: command
1245                         \s+
1246                         (               # 4: the parameters..
1247                                 (?:
1248                                         (?:[-\w]+=)?            # named parameter key?
1249                                         (?:
1250                                                 """.*?"""       # triple-quoted value
1251                                                 |
1252                                                 "[^"]+"         # single-quoted value
1253                                                 |
1254                                                 [^\s\]]+        # unquoted value
1255                                         )
1256                                         \s*                     # whitespace or end
1257                                                                 # of directive
1258                                 )
1259                         *)              # 0 or more parameters
1260                         \]\]            # directive closed
1261                 }sx;
1262         }
1263
1264         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1265         return $content;
1266 } #}}}
1267
1268 sub filter ($$$) { #{{{
1269         my $page=shift;
1270         my $destpage=shift;
1271         my $content=shift;
1272
1273         run_hooks(filter => sub {
1274                 $content=shift->(page => $page, destpage => $destpage, 
1275                         content => $content);
1276         });
1277
1278         return $content;
1279 } #}}}
1280
1281 sub indexlink () { #{{{
1282         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1283 } #}}}
1284
1285 my $wikilock;
1286
1287 sub lockwiki (;$) { #{{{
1288         my $wait=@_ ? shift : 1;
1289         # Take an exclusive lock on the wiki to prevent multiple concurrent
1290         # run issues. The lock will be dropped on program exit.
1291         if (! -d $config{wikistatedir}) {
1292                 mkdir($config{wikistatedir});
1293         }
1294         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1295                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1296         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1297                 if ($wait) {
1298                         debug("wiki seems to be locked, waiting for lock");
1299                         my $wait=600; # arbitrary, but don't hang forever to 
1300                                       # prevent process pileup
1301                         for (1..$wait) {
1302                                 return if flock($wikilock, 2 | 4);
1303                                 sleep 1;
1304                         }
1305                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1306                 }
1307                 else {
1308                         return 0;
1309                 }
1310         }
1311         return 1;
1312 } #}}}
1313
1314 sub unlockwiki () { #{{{
1315         return close($wikilock) if $wikilock;
1316         return;
1317 } #}}}
1318
1319 my $commitlock;
1320
1321 sub commit_hook_enabled () { #{{{
1322         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1323                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1324         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1325                 close($commitlock) || error("failed closing commitlock: $!");
1326                 return 0;
1327         }
1328         close($commitlock) || error("failed closing commitlock: $!");
1329         return 1;
1330 } #}}}
1331
1332 sub disable_commit_hook () { #{{{
1333         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1334                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1335         if (! flock($commitlock, 2)) { # LOCK_EX
1336                 error("failed to get commit lock");
1337         }
1338         return 1;
1339 } #}}}
1340
1341 sub enable_commit_hook () { #{{{
1342         return close($commitlock) if $commitlock;
1343         return;
1344 } #}}}
1345
1346 sub loadindex () { #{{{
1347         %oldrenderedfiles=%pagectime=();
1348         if (! $config{rebuild}) {
1349                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1350                 %destsources=%renderedfiles=%pagecase=%pagestate=();
1351         }
1352         my $in;
1353         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1354                 if (-e "$config{wikistatedir}/index") {
1355                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1356                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1357                 }
1358                 else {
1359                         return;
1360                 }
1361         }
1362
1363         my $index=Storable::fd_retrieve($in);
1364         if (! defined $index) {
1365                 return 0;
1366         }
1367
1368         my $pages;
1369         if (exists $index->{version} && ! ref $index->{version}) {
1370                 $pages=$index->{page};
1371                 %wikistate=%{$index->{state}};
1372         }
1373         else {
1374                 $pages=$index;
1375                 %wikistate=();
1376         }
1377
1378         foreach my $src (keys %$pages) {
1379                 my $d=$pages->{$src};
1380                 my $page=pagename($src);
1381                 $pagectime{$page}=$d->{ctime};
1382                 if (! $config{rebuild}) {
1383                         $pagesources{$page}=$src;
1384                         $pagemtime{$page}=$d->{mtime};
1385                         $renderedfiles{$page}=$d->{dest};
1386                         if (exists $d->{links} && ref $d->{links}) {
1387                                 $links{$page}=$d->{links};
1388                                 $oldlinks{$page}=[@{$d->{links}}];
1389                         }
1390                         if (exists $d->{depends}) {
1391                                 $depends{$page}=$d->{depends};
1392                         }
1393                         if (exists $d->{state}) {
1394                                 $pagestate{$page}=$d->{state};
1395                         }
1396                 }
1397                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1398         }
1399         foreach my $page (keys %pagesources) {
1400                 $pagecase{lc $page}=$page;
1401         }
1402         foreach my $page (keys %renderedfiles) {
1403                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1404         }
1405         return close($in);
1406 } #}}}
1407
1408 sub saveindex () { #{{{
1409         run_hooks(savestate => sub { shift->() });
1410
1411         my %hookids;
1412         foreach my $type (keys %hooks) {
1413                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1414         }
1415         my @hookids=keys %hookids;
1416
1417         if (! -d $config{wikistatedir}) {
1418                 mkdir($config{wikistatedir});
1419         }
1420         my $newfile="$config{wikistatedir}/indexdb.new";
1421         my $cleanup = sub { unlink($newfile) };
1422         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1423
1424         my %index;
1425         foreach my $page (keys %pagemtime) {
1426                 next unless $pagemtime{$page};
1427                 my $src=$pagesources{$page};
1428
1429                 $index{page}{$src}={
1430                         ctime => $pagectime{$page},
1431                         mtime => $pagemtime{$page},
1432                         dest => $renderedfiles{$page},
1433                         links => $links{$page},
1434                 };
1435
1436                 if (exists $depends{$page}) {
1437                         $index{page}{$src}{depends} = $depends{$page};
1438                 }
1439
1440                 if (exists $pagestate{$page}) {
1441                         foreach my $id (@hookids) {
1442                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1443                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1444                                 }
1445                         }
1446                 }
1447         }
1448
1449         $index{state}={};
1450         foreach my $id (@hookids) {
1451                 foreach my $key (keys %{$wikistate{$id}}) {
1452                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1453                 }
1454         }
1455         
1456         $index{version}="3";
1457         my $ret=Storable::nstore_fd(\%index, $out);
1458         return if ! defined $ret || ! $ret;
1459         close $out || error("failed saving to $newfile: $!", $cleanup);
1460         rename($newfile, "$config{wikistatedir}/indexdb") ||
1461                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1462         
1463         return 1;
1464 } #}}}
1465
1466 sub template_file ($) { #{{{
1467         my $template=shift;
1468
1469         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1470                 return "$dir/$template" if -e "$dir/$template";
1471         }
1472         return;
1473 } #}}}
1474
1475 sub template_params (@) { #{{{
1476         my $filename=template_file(shift);
1477
1478         if (! defined $filename) {
1479                 return if wantarray;
1480                 return "";
1481         }
1482
1483         my @ret=(
1484                 filter => sub {
1485                         my $text_ref = shift;
1486                         ${$text_ref} = decode_utf8(${$text_ref});
1487                 },
1488                 filename => $filename,
1489                 loop_context_vars => 1,
1490                 die_on_bad_params => 0,
1491                 @_
1492         );
1493         return wantarray ? @ret : {@ret};
1494 } #}}}
1495
1496 sub template ($;@) { #{{{
1497         require HTML::Template;
1498         return HTML::Template->new(template_params(@_));
1499 } #}}}
1500
1501 sub misctemplate ($$;@) { #{{{
1502         my $title=shift;
1503         my $pagebody=shift;
1504         
1505         my $template=template("misc.tmpl");
1506         $template->param(
1507                 title => $title,
1508                 indexlink => indexlink(),
1509                 wikiname => $config{wikiname},
1510                 pagebody => $pagebody,
1511                 baseurl => baseurl(),
1512                 @_,
1513         );
1514         run_hooks(pagetemplate => sub {
1515                 shift->(page => "", destpage => "", template => $template);
1516         });
1517         return $template->output;
1518 }#}}}
1519
1520 sub hook (@) { # {{{
1521         my %param=@_;
1522         
1523         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1524                 error 'hook requires type, call, and id parameters';
1525         }
1526
1527         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1528         
1529         $hooks{$param{type}}{$param{id}}=\%param;
1530         return 1;
1531 } # }}}
1532
1533 sub run_hooks ($$) { # {{{
1534         # Calls the given sub for each hook of the given type,
1535         # passing it the hook function to call.
1536         my $type=shift;
1537         my $sub=shift;
1538
1539         if (exists $hooks{$type}) {
1540                 my @deferred;
1541                 foreach my $id (keys %{$hooks{$type}}) {
1542                         if ($hooks{$type}{$id}{last}) {
1543                                 push @deferred, $id;
1544                                 next;
1545                         }
1546                         $sub->($hooks{$type}{$id}{call});
1547                 }
1548                 foreach my $id (@deferred) {
1549                         $sub->($hooks{$type}{$id}{call});
1550                 }
1551         }
1552
1553         return 1;
1554 } #}}}
1555
1556 sub rcs_update () { #{{{
1557         $hooks{rcs}{rcs_update}{call}->(@_);
1558 } #}}}
1559
1560 sub rcs_prepedit ($) { #{{{
1561         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1562 } #}}}
1563
1564 sub rcs_commit ($$$;$$) { #{{{
1565         $hooks{rcs}{rcs_commit}{call}->(@_);
1566 } #}}}
1567
1568 sub rcs_commit_staged ($$$) { #{{{
1569         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1570 } #}}}
1571
1572 sub rcs_add ($) { #{{{
1573         $hooks{rcs}{rcs_add}{call}->(@_);
1574 } #}}}
1575
1576 sub rcs_remove ($) { #{{{
1577         $hooks{rcs}{rcs_remove}{call}->(@_);
1578 } #}}}
1579
1580 sub rcs_rename ($$) { #{{{
1581         $hooks{rcs}{rcs_rename}{call}->(@_);
1582 } #}}}
1583
1584 sub rcs_recentchanges ($) { #{{{
1585         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1586 } #}}}
1587
1588 sub rcs_diff ($) { #{{{
1589         $hooks{rcs}{rcs_diff}{call}->(@_);
1590 } #}}}
1591
1592 sub rcs_getctime ($) { #{{{
1593         $hooks{rcs}{rcs_getctime}{call}->(@_);
1594 } #}}}
1595
1596 sub rcs_receive () { #{{{
1597         $hooks{rcs}{rcs_receive}{call}->();
1598 } #}}}
1599
1600 sub globlist_to_pagespec ($) { #{{{
1601         my @globlist=split(' ', shift);
1602
1603         my (@spec, @skip);
1604         foreach my $glob (@globlist) {
1605                 if ($glob=~/^!(.*)/) {
1606                         push @skip, $glob;
1607                 }
1608                 else {
1609                         push @spec, $glob;
1610                 }
1611         }
1612
1613         my $spec=join(' or ', @spec);
1614         if (@skip) {
1615                 my $skip=join(' and ', @skip);
1616                 if (length $spec) {
1617                         $spec="$skip and ($spec)";
1618                 }
1619                 else {
1620                         $spec=$skip;
1621                 }
1622         }
1623         return $spec;
1624 } #}}}
1625
1626 sub is_globlist ($) { #{{{
1627         my $s=shift;
1628         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1629 } #}}}
1630
1631 sub safequote ($) { #{{{
1632         my $s=shift;
1633         $s=~s/[{}]//g;
1634         return "q{$s}";
1635 } #}}}
1636
1637 sub add_depends ($$) { #{{{
1638         my $page=shift;
1639         my $pagespec=shift;
1640         
1641         return unless pagespec_valid($pagespec);
1642
1643         if (! exists $depends{$page}) {
1644                 $depends{$page}=$pagespec;
1645         }
1646         else {
1647                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1648         }
1649
1650         return 1;
1651 } # }}}
1652
1653 sub file_pruned ($$) { #{{{
1654         require File::Spec;
1655         my $file=File::Spec->canonpath(shift);
1656         my $base=File::Spec->canonpath(shift);
1657         $file =~ s#^\Q$base\E/+##;
1658
1659         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1660         return $file =~ m/$regexp/ && $file ne $base;
1661 } #}}}
1662
1663 sub gettext { #{{{
1664         # Only use gettext in the rare cases it's needed.
1665         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1666             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1667             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1668                 if (! $gettext_obj) {
1669                         $gettext_obj=eval q{
1670                                 use Locale::gettext q{textdomain};
1671                                 Locale::gettext->domain('ikiwiki')
1672                         };
1673                         if ($@) {
1674                                 print STDERR "$@";
1675                                 $gettext_obj=undef;
1676                                 return shift;
1677                         }
1678                 }
1679                 return $gettext_obj->get(shift);
1680         }
1681         else {
1682                 return shift;
1683         }
1684 } #}}}
1685
1686 sub yesno ($) { #{{{
1687         my $val=shift;
1688
1689         return (defined $val && lc($val) eq gettext("yes"));
1690 } #}}}
1691
1692 sub inject { #{{{
1693         # Injects a new function into the symbol table to replace an
1694         # exported function.
1695         my %params=@_;
1696
1697         # This is deep ugly perl foo, beware.
1698         no strict;
1699         no warnings;
1700         if (! defined $params{parent}) {
1701                 $params{parent}='::';
1702                 $params{old}=\&{$params{name}};
1703                 $params{name}=~s/.*:://;
1704         }
1705         my $parent=$params{parent};
1706         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1707                 $ns = $params{parent} . $ns;
1708                 inject(%params, parent => $ns) unless $ns eq '::main::';
1709                 *{$ns . $params{name}} = $params{call}
1710                         if exists ${$ns}{$params{name}} &&
1711                            \&{${$ns}{$params{name}}} == $params{old};
1712         }
1713         use strict;
1714         use warnings;
1715 } #}}}
1716
1717 sub pagespec_merge ($$) { #{{{
1718         my $a=shift;
1719         my $b=shift;
1720
1721         return $a if $a eq $b;
1722
1723         # Support for old-style GlobLists.
1724         if (is_globlist($a)) {
1725                 $a=globlist_to_pagespec($a);
1726         }
1727         if (is_globlist($b)) {
1728                 $b=globlist_to_pagespec($b);
1729         }
1730
1731         return "($a) or ($b)";
1732 } #}}}
1733
1734 sub pagespec_translate ($) { #{{{
1735         my $spec=shift;
1736
1737         # Support for old-style GlobLists.
1738         if (is_globlist($spec)) {
1739                 $spec=globlist_to_pagespec($spec);
1740         }
1741
1742         # Convert spec to perl code.
1743         my $code="";
1744         while ($spec=~m{
1745                 \s*             # ignore whitespace
1746                 (               # 1: match a single word
1747                         \!              # !
1748                 |
1749                         \(              # (
1750                 |
1751                         \)              # )
1752                 |
1753                         \w+\([^\)]*\)   # command(params)
1754                 |
1755                         [^\s()]+        # any other text
1756                 )
1757                 \s*             # ignore whitespace
1758         }igx) {
1759                 my $word=$1;
1760                 if (lc $word eq 'and') {
1761                         $code.=' &&';
1762                 }
1763                 elsif (lc $word eq 'or') {
1764                         $code.=' ||';
1765                 }
1766                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1767                         $code.=' '.$word;
1768                 }
1769                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1770                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1771                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1772                         }
1773                         else {
1774                                 $code.=' 0';
1775                         }
1776                 }
1777                 else {
1778                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1779                 }
1780         }
1781
1782         if (! length $code) {
1783                 $code=0;
1784         }
1785
1786         no warnings;
1787         return eval 'sub { my $page=shift; '.$code.' }';
1788 } #}}}
1789
1790 sub pagespec_match ($$;@) { #{{{
1791         my $page=shift;
1792         my $spec=shift;
1793         my @params=@_;
1794
1795         # Backwards compatability with old calling convention.
1796         if (@params == 1) {
1797                 unshift @params, 'location';
1798         }
1799
1800         my $sub=pagespec_translate($spec);
1801         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1802         return $sub->($page, @params);
1803 } #}}}
1804
1805 sub pagespec_valid ($) { #{{{
1806         my $spec=shift;
1807
1808         my $sub=pagespec_translate($spec);
1809         return ! $@;
1810 } #}}}
1811
1812 sub glob2re ($) { #{{{
1813         my $re=quotemeta(shift);
1814         $re=~s/\\\*/.*/g;
1815         $re=~s/\\\?/./g;
1816         return $re;
1817 } #}}}
1818
1819 package IkiWiki::FailReason;
1820
1821 use overload ( #{{{
1822         '""'    => sub { ${$_[0]} },
1823         '0+'    => sub { 0 },
1824         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1825         fallback => 1,
1826 ); #}}}
1827
1828 sub new { #{{{
1829         my $class = shift;
1830         my $value = shift;
1831         return bless \$value, $class;
1832 } #}}}
1833
1834 package IkiWiki::SuccessReason;
1835
1836 use overload ( #{{{
1837         '""'    => sub { ${$_[0]} },
1838         '0+'    => sub { 1 },
1839         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1840         fallback => 1,
1841 ); #}}}
1842
1843 sub new { #{{{
1844         my $class = shift;
1845         my $value = shift;
1846         return bless \$value, $class;
1847 }; #}}}
1848
1849 package IkiWiki::PageSpec;
1850
1851 sub match_glob ($$;@) { #{{{
1852         my $page=shift;
1853         my $glob=shift;
1854         my %params=@_;
1855         
1856         my $from=exists $params{location} ? $params{location} : '';
1857         
1858         # relative matching
1859         if ($glob =~ m!^\./!) {
1860                 $from=~s#/?[^/]+$##;
1861                 $glob=~s#^\./##;
1862                 $glob="$from/$glob" if length $from;
1863         }
1864
1865         my $regexp=IkiWiki::glob2re($glob);
1866         if ($page=~/^$regexp$/i) {
1867                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1868                         return IkiWiki::SuccessReason->new("$glob matches $page");
1869                 }
1870                 else {
1871                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1872                 }
1873         }
1874         else {
1875                 return IkiWiki::FailReason->new("$glob does not match $page");
1876         }
1877 } #}}}
1878
1879 sub match_internal ($$;@) { #{{{
1880         return match_glob($_[0], $_[1], @_, internal => 1)
1881 } #}}}
1882
1883 sub match_link ($$;@) { #{{{
1884         my $page=shift;
1885         my $link=lc(shift);
1886         my %params=@_;
1887
1888         my $from=exists $params{location} ? $params{location} : '';
1889
1890         # relative matching
1891         if ($link =~ m!^\.! && defined $from) {
1892                 $from=~s#/?[^/]+$##;
1893                 $link=~s#^\./##;
1894                 $link="$from/$link" if length $from;
1895         }
1896
1897         my $links = $IkiWiki::links{$page};
1898         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1899         my $bestlink = IkiWiki::bestlink($from, $link);
1900         foreach my $p (@{$links}) {
1901                 if (length $bestlink) {
1902                         return IkiWiki::SuccessReason->new("$page links to $link")
1903                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1904                 }
1905                 else {
1906                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1907                                 if match_glob($p, $link, %params);
1908                 }
1909         }
1910         return IkiWiki::FailReason->new("$page does not link to $link");
1911 } #}}}
1912
1913 sub match_backlink ($$;@) { #{{{
1914         return match_link($_[1], $_[0], @_);
1915 } #}}}
1916
1917 sub match_created_before ($$;@) { #{{{
1918         my $page=shift;
1919         my $testpage=shift;
1920
1921         if (exists $IkiWiki::pagectime{$testpage}) {
1922                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1923                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1924                 }
1925                 else {
1926                         return IkiWiki::FailReason->new("$page not created before $testpage");
1927                 }
1928         }
1929         else {
1930                 return IkiWiki::FailReason->new("$testpage has no ctime");
1931         }
1932 } #}}}
1933
1934 sub match_created_after ($$;@) { #{{{
1935         my $page=shift;
1936         my $testpage=shift;
1937
1938         if (exists $IkiWiki::pagectime{$testpage}) {
1939                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1940                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1941                 }
1942                 else {
1943                         return IkiWiki::FailReason->new("$page not created after $testpage");
1944                 }
1945         }
1946         else {
1947                 return IkiWiki::FailReason->new("$testpage has no ctime");
1948         }
1949 } #}}}
1950
1951 sub match_creation_day ($$;@) { #{{{
1952         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1953                 return IkiWiki::SuccessReason->new('creation_day matched');
1954         }
1955         else {
1956                 return IkiWiki::FailReason->new('creation_day did not match');
1957         }
1958 } #}}}
1959
1960 sub match_creation_month ($$;@) { #{{{
1961         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1962                 return IkiWiki::SuccessReason->new('creation_month matched');
1963         }
1964         else {
1965                 return IkiWiki::FailReason->new('creation_month did not match');
1966         }
1967 } #}}}
1968
1969 sub match_creation_year ($$;@) { #{{{
1970         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1971                 return IkiWiki::SuccessReason->new('creation_year matched');
1972         }
1973         else {
1974                 return IkiWiki::FailReason->new('creation_year did not match');
1975         }
1976 } #}}}
1977
1978 sub match_user ($$;@) { #{{{
1979         shift;
1980         my $user=shift;
1981         my %params=@_;
1982         
1983         if (! exists $params{user}) {
1984                 return IkiWiki::FailReason->new("no user specified");
1985         }
1986
1987         if (defined $params{user} && lc $params{user} eq lc $user) {
1988                 return IkiWiki::SuccessReason->new("user is $user");
1989         }
1990         elsif (! defined $params{user}) {
1991                 return IkiWiki::FailReason->new("not logged in");
1992         }
1993         else {
1994                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
1995         }
1996 } #}}}
1997
1998 sub match_admin ($$;@) { #{{{
1999         shift;
2000         shift;
2001         my %params=@_;
2002         
2003         if (! exists $params{user}) {
2004                 return IkiWiki::FailReason->new("no user specified");
2005         }
2006
2007         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2008                 return IkiWiki::SuccessReason->new("user is an admin");
2009         }
2010         elsif (! defined $params{user}) {
2011                 return IkiWiki::FailReason->new("not logged in");
2012         }
2013         else {
2014                 return IkiWiki::FailReason->new("user is not an admin");
2015         }
2016 } #}}}
2017
2018 sub match_ip ($$;@) { #{{{
2019         shift;
2020         my $ip=shift;
2021         my %params=@_;
2022         
2023         if (! exists $params{ip}) {
2024                 return IkiWiki::FailReason->new("no IP specified");
2025         }
2026
2027         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2028                 return IkiWiki::SuccessReason->new("IP is $ip");
2029         }
2030         else {
2031                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2032         }
2033 } #}}}
2034
2035 1