Merge commit 'origin/master' into prv/po
[ikiwiki] / 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         my $res=undef;
819         
820         my $cwd=$page;
821         if ($link=~s/^\/+//) {
822                 # absolute links
823                 $cwd="";
824         }
825         $link=~s/\/$//;
826
827         do {
828                 my $l=$cwd;
829                 $l.="/" if length $l;
830                 $l.=$link;
831
832                 if (exists $links{$l}) {
833                         $res=$l;
834                 }
835                 elsif (exists $pagecase{lc $l}) {
836                         $res=$pagecase{lc $l};
837                 }
838         } while ($cwd=~s{/?[^/]+$}{} && ! defined $res);
839
840         if (! defined $res && length $config{userdir}) {
841                 my $l = "$config{userdir}/".lc($link);
842                 if (exists $links{$l}) {
843                         $res=$l;
844                 }
845                 elsif (exists $pagecase{lc $l}) {
846                         $res=$pagecase{lc $l};
847                 }
848         }
849
850         if (defined $res) {
851                 run_hooks(tweakbestlink => sub {
852                         $res=shift->(
853                                 page => $page,
854                                 link => $res);
855                 });
856                 return $res;
857         }
858         else {
859                 #print STDERR "warning: page $page, broken link: $link\n";
860                 return "";
861         }
862 } #}}}
863
864 sub isinlinableimage ($) { #{{{
865         my $file=shift;
866         
867         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
868 } #}}}
869
870 sub pagetitle ($;$) { #{{{
871         my $page=shift;
872         my $unescaped=shift;
873
874         if ($unescaped) {
875                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
876         }
877         else {
878                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
879         }
880
881         return $page;
882 } #}}}
883
884 sub titlepage ($) { #{{{
885         my $title=shift;
886         # support use w/o %config set
887         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
888         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
889         return $title;
890 } #}}}
891
892 sub linkpage ($) { #{{{
893         my $link=shift;
894         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
895         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
896         return $link;
897 } #}}}
898
899 sub cgiurl (@) { #{{{
900         my %params=@_;
901
902         return $config{cgiurl}."?".
903                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
904 } #}}}
905
906 sub baseurl (;$) { #{{{
907         my $page=shift;
908
909         return "$config{url}/" if ! defined $page;
910         
911         $page=htmlpage($page);
912         $page=~s/[^\/]+$//;
913         $page=~s/[^\/]+\//..\//g;
914         return $page;
915 } #}}}
916
917 sub abs2rel ($$) { #{{{
918         # Work around very innefficient behavior in File::Spec if abs2rel
919         # is passed two relative paths. It's much faster if paths are
920         # absolute! (Debian bug #376658; fixed in debian unstable now)
921         my $path="/".shift;
922         my $base="/".shift;
923
924         require File::Spec;
925         my $ret=File::Spec->abs2rel($path, $base);
926         $ret=~s/^// if defined $ret;
927         return $ret;
928 } #}}}
929
930 sub displaytime ($;$) { #{{{
931         # Plugins can override this function to mark up the time to
932         # display.
933         return '<span class="date">'.formattime(@_).'</span>';
934 } #}}}
935
936 sub formattime ($;$) { #{{{
937         # Plugins can override this function to format the time.
938         my $time=shift;
939         my $format=shift;
940         if (! defined $format) {
941                 $format=$config{timeformat};
942         }
943
944         # strftime doesn't know about encodings, so make sure
945         # its output is properly treated as utf8
946         return decode_utf8(POSIX::strftime($format, localtime($time)));
947 } #}}}
948
949 sub beautify_urlpath ($) { #{{{
950         my $url=shift;
951
952         if ($config{usedirs}) {
953                 $url =~ s!/index.$config{htmlext}$!/!;
954         }
955
956         run_hooks(tweakurlpath => sub {
957                 $url=shift->(url => $url);
958         });
959
960         # Ensure url is not an empty link, and
961         # if it's relative, make that explicit to avoid colon confusion.
962         if ($url !~ /^\//) {
963                 $url="./$url";
964         }
965
966         return $url;
967 } #}}}
968
969 sub urlto ($$;$) { #{{{
970         my $to=shift;
971         my $from=shift;
972         my $absolute=shift;
973         
974         if (! length $to) {
975                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
976         }
977
978         if (! $destsources{$to}) {
979                 $to=htmlpage($to);
980         }
981
982         if ($absolute) {
983                 return $config{url}.beautify_urlpath("/".$to);
984         }
985
986         my $link = abs2rel($to, dirname(htmlpage($from)));
987
988         return beautify_urlpath($link);
989 } #}}}
990
991 sub htmllink ($$$;@) { #{{{
992         my $lpage=shift; # the page doing the linking
993         my $page=shift; # the page that will contain the link (different for inline)
994         my $link=shift;
995         my %opts=@_;
996
997         $link=~s/\/$//;
998
999         my $bestlink;
1000         if (! $opts{forcesubpage}) {
1001                 $bestlink=bestlink($lpage, $link);
1002         }
1003         else {
1004                 $bestlink="$lpage/".lc($link);
1005         }
1006
1007         my $linktext;
1008         if (defined $opts{linktext}) {
1009                 $linktext=$opts{linktext};
1010         }
1011         else {
1012                 $linktext=pagetitle(basename($link));
1013         }
1014         
1015         return "<span class=\"selflink\">$linktext</span>"
1016                 if length $bestlink && $page eq $bestlink &&
1017                    ! defined $opts{anchor};
1018         
1019         if (! $destsources{$bestlink}) {
1020                 $bestlink=htmlpage($bestlink);
1021
1022                 if (! $destsources{$bestlink}) {
1023                         return $linktext unless length $config{cgiurl};
1024                         return "<span class=\"createlink\"><a href=\"".
1025                                 cgiurl(
1026                                         do => "create",
1027                                         page => lc($link),
1028                                         from => $lpage
1029                                 ).
1030                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
1031                 }
1032         }
1033         
1034         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1035         $bestlink=beautify_urlpath($bestlink);
1036         
1037         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1038                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1039         }
1040
1041         if (defined $opts{anchor}) {
1042                 $bestlink.="#".$opts{anchor};
1043         }
1044
1045         my @attrs;
1046         if (defined $opts{rel}) {
1047                 push @attrs, ' rel="'.$opts{rel}.'"';
1048         }
1049         if (defined $opts{class}) {
1050                 push @attrs, ' class="'.$opts{class}.'"';
1051         }
1052
1053         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1054 } #}}}
1055
1056 sub userlink ($) { #{{{
1057         my $user=shift;
1058
1059         my $oiduser=eval { openiduser($user) };
1060         if (defined $oiduser) {
1061                 return "<a href=\"$user\">$oiduser</a>";
1062         }
1063         else {
1064                 eval q{use CGI 'escapeHTML'};
1065                 error($@) if $@;
1066
1067                 return htmllink("", "", escapeHTML(
1068                         length $config{userdir} ? $config{userdir}."/".$user : $user
1069                 ), noimageinline => 1);
1070         }
1071 } #}}}
1072
1073 sub htmlize ($$$$) { #{{{
1074         my $page=shift;
1075         my $destpage=shift;
1076         my $type=shift;
1077         my $content=shift;
1078         
1079         my $oneline = $content !~ /\n/;
1080
1081         if (exists $hooks{htmlize}{$type}) {
1082                 $content=$hooks{htmlize}{$type}{call}->(
1083                         page => $page,
1084                         content => $content,
1085                 );
1086         }
1087         else {
1088                 error("htmlization of $type not supported");
1089         }
1090
1091         run_hooks(sanitize => sub {
1092                 $content=shift->(
1093                         page => $page,
1094                         destpage => $destpage,
1095                         content => $content,
1096                 );
1097         });
1098         
1099         if ($oneline) {
1100                 # hack to get rid of enclosing junk added by markdown
1101                 # and other htmlizers
1102                 $content=~s/^<p>//i;
1103                 $content=~s/<\/p>$//i;
1104                 chomp $content;
1105         }
1106
1107         return $content;
1108 } #}}}
1109
1110 sub linkify ($$$) { #{{{
1111         my $page=shift;
1112         my $destpage=shift;
1113         my $content=shift;
1114
1115         run_hooks(linkify => sub {
1116                 $content=shift->(
1117                         page => $page,
1118                         destpage => $destpage,
1119                         content => $content,
1120                 );
1121         });
1122         
1123         return $content;
1124 } #}}}
1125
1126 our %preprocessing;
1127 our $preprocess_preview=0;
1128 sub preprocess ($$$;$$) { #{{{
1129         my $page=shift; # the page the data comes from
1130         my $destpage=shift; # the page the data will appear in (different for inline)
1131         my $content=shift;
1132         my $scan=shift;
1133         my $preview=shift;
1134
1135         # Using local because it needs to be set within any nested calls
1136         # of this function.
1137         local $preprocess_preview=$preview if defined $preview;
1138
1139         my $handle=sub {
1140                 my $escape=shift;
1141                 my $prefix=shift;
1142                 my $command=shift;
1143                 my $params=shift;
1144                 $params="" if ! defined $params;
1145
1146                 if (length $escape) {
1147                         return "[[$prefix$command $params]]";
1148                 }
1149                 elsif (exists $hooks{preprocess}{$command}) {
1150                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1151                         # Note: preserve order of params, some plugins may
1152                         # consider it significant.
1153                         my @params;
1154                         while ($params =~ m{
1155                                 (?:([-\w]+)=)?          # 1: named parameter key?
1156                                 (?:
1157                                         """(.*?)"""     # 2: triple-quoted value
1158                                 |
1159                                         "([^"]+)"       # 3: single-quoted value
1160                                 |
1161                                         (\S+)           # 4: unquoted value
1162                                 )
1163                                 (?:\s+|$)               # delimiter to next param
1164                         }sgx) {
1165                                 my $key=$1;
1166                                 my $val;
1167                                 if (defined $2) {
1168                                         $val=$2;
1169                                         $val=~s/\r\n/\n/mg;
1170                                         $val=~s/^\n+//g;
1171                                         $val=~s/\n+$//g;
1172                                 }
1173                                 elsif (defined $3) {
1174                                         $val=$3;
1175                                 }
1176                                 elsif (defined $4) {
1177                                         $val=$4;
1178                                 }
1179
1180                                 if (defined $key) {
1181                                         push @params, $key, $val;
1182                                 }
1183                                 else {
1184                                         push @params, $val, '';
1185                                 }
1186                         }
1187                         if ($preprocessing{$page}++ > 3) {
1188                                 # Avoid loops of preprocessed pages preprocessing
1189                                 # other pages that preprocess them, etc.
1190                                 return "[[!$command <span class=\"error\">".
1191                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1192                                                 $page, $preprocessing{$page}).
1193                                         "</span>]]";
1194                         }
1195                         my $ret;
1196                         if (! $scan) {
1197                                 $ret=eval {
1198                                         $hooks{preprocess}{$command}{call}->(
1199                                                 @params,
1200                                                 page => $page,
1201                                                 destpage => $destpage,
1202                                                 preview => $preprocess_preview,
1203                                         );
1204                                 };
1205                                 if ($@) {
1206                                         chomp $@;
1207                                         $ret="[[!$command <span class=\"error\">".
1208                                                 gettext("Error").": $@"."</span>]]";
1209                                 }
1210                         }
1211                         else {
1212                                 # use void context during scan pass
1213                                 eval {
1214                                         $hooks{preprocess}{$command}{call}->(
1215                                                 @params,
1216                                                 page => $page,
1217                                                 destpage => $destpage,
1218                                                 preview => $preprocess_preview,
1219                                         );
1220                                 };
1221                                 $ret="";
1222                         }
1223                         $preprocessing{$page}--;
1224                         return $ret;
1225                 }
1226                 else {
1227                         return "[[$prefix$command $params]]";
1228                 }
1229         };
1230         
1231         my $regex;
1232         if ($config{prefix_directives}) {
1233                 $regex = qr{
1234                         (\\?)           # 1: escape?
1235                         \[\[(!)         # directive open; 2: prefix
1236                         ([-\w]+)        # 3: command
1237                         (               # 4: the parameters..
1238                                 \s+     # Must have space if parameters present
1239                                 (?:
1240                                         (?:[-\w]+=)?            # named parameter key?
1241                                         (?:
1242                                                 """.*?"""       # triple-quoted value
1243                                                 |
1244                                                 "[^"]+"         # single-quoted value
1245                                                 |
1246                                                 [^\s\]]+        # unquoted value
1247                                         )
1248                                         \s*                     # whitespace or end
1249                                                                 # of directive
1250                                 )
1251                         *)?             # 0 or more parameters
1252                         \]\]            # directive closed
1253                 }sx;
1254         }
1255         else {
1256                 $regex = qr{
1257                         (\\?)           # 1: escape?
1258                         \[\[(!?)        # directive open; 2: optional prefix
1259                         ([-\w]+)        # 3: command
1260                         \s+
1261                         (               # 4: the parameters..
1262                                 (?:
1263                                         (?:[-\w]+=)?            # named parameter key?
1264                                         (?:
1265                                                 """.*?"""       # triple-quoted value
1266                                                 |
1267                                                 "[^"]+"         # single-quoted value
1268                                                 |
1269                                                 [^\s\]]+        # unquoted value
1270                                         )
1271                                         \s*                     # whitespace or end
1272                                                                 # of directive
1273                                 )
1274                         *)              # 0 or more parameters
1275                         \]\]            # directive closed
1276                 }sx;
1277         }
1278
1279         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1280         return $content;
1281 } #}}}
1282
1283 sub filter ($$$) { #{{{
1284         my $page=shift;
1285         my $destpage=shift;
1286         my $content=shift;
1287
1288         run_hooks(filter => sub {
1289                 $content=shift->(page => $page, destpage => $destpage, 
1290                         content => $content);
1291         });
1292
1293         return $content;
1294 } #}}}
1295
1296 sub indexlink () { #{{{
1297         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1298 } #}}}
1299
1300 my $wikilock;
1301
1302 sub lockwiki (;$) { #{{{
1303         my $wait=@_ ? shift : 1;
1304         # Take an exclusive lock on the wiki to prevent multiple concurrent
1305         # run issues. The lock will be dropped on program exit.
1306         if (! -d $config{wikistatedir}) {
1307                 mkdir($config{wikistatedir});
1308         }
1309         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1310                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1311         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1312                 if ($wait) {
1313                         debug("wiki seems to be locked, waiting for lock");
1314                         my $wait=600; # arbitrary, but don't hang forever to 
1315                                       # prevent process pileup
1316                         for (1..$wait) {
1317                                 return if flock($wikilock, 2 | 4);
1318                                 sleep 1;
1319                         }
1320                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1321                 }
1322                 else {
1323                         return 0;
1324                 }
1325         }
1326         return 1;
1327 } #}}}
1328
1329 sub unlockwiki () { #{{{
1330         return close($wikilock) if $wikilock;
1331         return;
1332 } #}}}
1333
1334 my $commitlock;
1335
1336 sub commit_hook_enabled () { #{{{
1337         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1338                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1339         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1340                 close($commitlock) || error("failed closing commitlock: $!");
1341                 return 0;
1342         }
1343         close($commitlock) || error("failed closing commitlock: $!");
1344         return 1;
1345 } #}}}
1346
1347 sub disable_commit_hook () { #{{{
1348         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1349                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1350         if (! flock($commitlock, 2)) { # LOCK_EX
1351                 error("failed to get commit lock");
1352         }
1353         return 1;
1354 } #}}}
1355
1356 sub enable_commit_hook () { #{{{
1357         return close($commitlock) if $commitlock;
1358         return;
1359 } #}}}
1360
1361 sub loadindex () { #{{{
1362         %oldrenderedfiles=%pagectime=();
1363         if (! $config{rebuild}) {
1364                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1365                 %destsources=%renderedfiles=%pagecase=%pagestate=();
1366         }
1367         my $in;
1368         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1369                 if (-e "$config{wikistatedir}/index") {
1370                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1371                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1372                 }
1373                 else {
1374                         return;
1375                 }
1376         }
1377
1378         my $index=Storable::fd_retrieve($in);
1379         if (! defined $index) {
1380                 return 0;
1381         }
1382
1383         my $pages;
1384         if (exists $index->{version} && ! ref $index->{version}) {
1385                 $pages=$index->{page};
1386                 %wikistate=%{$index->{state}};
1387         }
1388         else {
1389                 $pages=$index;
1390                 %wikistate=();
1391         }
1392
1393         foreach my $src (keys %$pages) {
1394                 my $d=$pages->{$src};
1395                 my $page=pagename($src);
1396                 $pagectime{$page}=$d->{ctime};
1397                 if (! $config{rebuild}) {
1398                         $pagesources{$page}=$src;
1399                         $pagemtime{$page}=$d->{mtime};
1400                         $renderedfiles{$page}=$d->{dest};
1401                         if (exists $d->{links} && ref $d->{links}) {
1402                                 $links{$page}=$d->{links};
1403                                 $oldlinks{$page}=[@{$d->{links}}];
1404                         }
1405                         if (exists $d->{depends}) {
1406                                 $depends{$page}=$d->{depends};
1407                         }
1408                         if (exists $d->{state}) {
1409                                 $pagestate{$page}=$d->{state};
1410                         }
1411                 }
1412                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1413         }
1414         foreach my $page (keys %pagesources) {
1415                 $pagecase{lc $page}=$page;
1416         }
1417         foreach my $page (keys %renderedfiles) {
1418                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1419         }
1420         return close($in);
1421 } #}}}
1422
1423 sub saveindex () { #{{{
1424         run_hooks(savestate => sub { shift->() });
1425
1426         my %hookids;
1427         foreach my $type (keys %hooks) {
1428                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1429         }
1430         my @hookids=keys %hookids;
1431
1432         if (! -d $config{wikistatedir}) {
1433                 mkdir($config{wikistatedir});
1434         }
1435         my $newfile="$config{wikistatedir}/indexdb.new";
1436         my $cleanup = sub { unlink($newfile) };
1437         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1438
1439         my %index;
1440         foreach my $page (keys %pagemtime) {
1441                 next unless $pagemtime{$page};
1442                 my $src=$pagesources{$page};
1443
1444                 $index{page}{$src}={
1445                         ctime => $pagectime{$page},
1446                         mtime => $pagemtime{$page},
1447                         dest => $renderedfiles{$page},
1448                         links => $links{$page},
1449                 };
1450
1451                 if (exists $depends{$page}) {
1452                         $index{page}{$src}{depends} = $depends{$page};
1453                 }
1454
1455                 if (exists $pagestate{$page}) {
1456                         foreach my $id (@hookids) {
1457                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1458                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1459                                 }
1460                         }
1461                 }
1462         }
1463
1464         $index{state}={};
1465         foreach my $id (@hookids) {
1466                 foreach my $key (keys %{$wikistate{$id}}) {
1467                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1468                 }
1469         }
1470         
1471         $index{version}="3";
1472         my $ret=Storable::nstore_fd(\%index, $out);
1473         return if ! defined $ret || ! $ret;
1474         close $out || error("failed saving to $newfile: $!", $cleanup);
1475         rename($newfile, "$config{wikistatedir}/indexdb") ||
1476                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1477         
1478         return 1;
1479 } #}}}
1480
1481 sub template_file ($) { #{{{
1482         my $template=shift;
1483
1484         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1485                 return "$dir/$template" if -e "$dir/$template";
1486         }
1487         return;
1488 } #}}}
1489
1490 sub template_params (@) { #{{{
1491         my $filename=template_file(shift);
1492
1493         if (! defined $filename) {
1494                 return if wantarray;
1495                 return "";
1496         }
1497
1498         my @ret=(
1499                 filter => sub {
1500                         my $text_ref = shift;
1501                         ${$text_ref} = decode_utf8(${$text_ref});
1502                 },
1503                 filename => $filename,
1504                 loop_context_vars => 1,
1505                 die_on_bad_params => 0,
1506                 @_
1507         );
1508         return wantarray ? @ret : {@ret};
1509 } #}}}
1510
1511 sub template ($;@) { #{{{
1512         require HTML::Template;
1513         return HTML::Template->new(template_params(@_));
1514 } #}}}
1515
1516 sub misctemplate ($$;@) { #{{{
1517         my $title=shift;
1518         my $pagebody=shift;
1519         
1520         my $template=template("misc.tmpl");
1521         $template->param(
1522                 title => $title,
1523                 indexlink => indexlink(),
1524                 wikiname => $config{wikiname},
1525                 pagebody => $pagebody,
1526                 baseurl => baseurl(),
1527                 @_,
1528         );
1529         run_hooks(pagetemplate => sub {
1530                 shift->(page => "", destpage => "", template => $template);
1531         });
1532         return $template->output;
1533 }#}}}
1534
1535 sub hook (@) { # {{{
1536         my %param=@_;
1537         
1538         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1539                 error 'hook requires type, call, and id parameters';
1540         }
1541
1542         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1543         
1544         $hooks{$param{type}}{$param{id}}=\%param;
1545         return 1;
1546 } # }}}
1547
1548 sub run_hooks ($$) { # {{{
1549         # Calls the given sub for each hook of the given type,
1550         # passing it the hook function to call.
1551         my $type=shift;
1552         my $sub=shift;
1553
1554         if (exists $hooks{$type}) {
1555                 my @deferred;
1556                 foreach my $id (keys %{$hooks{$type}}) {
1557                         if ($hooks{$type}{$id}{last}) {
1558                                 push @deferred, $id;
1559                                 next;
1560                         }
1561                         $sub->($hooks{$type}{$id}{call});
1562                 }
1563                 foreach my $id (@deferred) {
1564                         $sub->($hooks{$type}{$id}{call});
1565                 }
1566         }
1567
1568         return 1;
1569 } #}}}
1570
1571 sub rcs_update () { #{{{
1572         $hooks{rcs}{rcs_update}{call}->(@_);
1573 } #}}}
1574
1575 sub rcs_prepedit ($) { #{{{
1576         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1577 } #}}}
1578
1579 sub rcs_commit ($$$;$$) { #{{{
1580         $hooks{rcs}{rcs_commit}{call}->(@_);
1581 } #}}}
1582
1583 sub rcs_commit_staged ($$$) { #{{{
1584         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1585 } #}}}
1586
1587 sub rcs_add ($) { #{{{
1588         $hooks{rcs}{rcs_add}{call}->(@_);
1589 } #}}}
1590
1591 sub rcs_remove ($) { #{{{
1592         $hooks{rcs}{rcs_remove}{call}->(@_);
1593 } #}}}
1594
1595 sub rcs_rename ($$) { #{{{
1596         $hooks{rcs}{rcs_rename}{call}->(@_);
1597 } #}}}
1598
1599 sub rcs_recentchanges ($) { #{{{
1600         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1601 } #}}}
1602
1603 sub rcs_diff ($) { #{{{
1604         $hooks{rcs}{rcs_diff}{call}->(@_);
1605 } #}}}
1606
1607 sub rcs_getctime ($) { #{{{
1608         $hooks{rcs}{rcs_getctime}{call}->(@_);
1609 } #}}}
1610
1611 sub rcs_receive () { #{{{
1612         $hooks{rcs}{rcs_receive}{call}->();
1613 } #}}}
1614
1615 sub globlist_to_pagespec ($) { #{{{
1616         my @globlist=split(' ', shift);
1617
1618         my (@spec, @skip);
1619         foreach my $glob (@globlist) {
1620                 if ($glob=~/^!(.*)/) {
1621                         push @skip, $glob;
1622                 }
1623                 else {
1624                         push @spec, $glob;
1625                 }
1626         }
1627
1628         my $spec=join(' or ', @spec);
1629         if (@skip) {
1630                 my $skip=join(' and ', @skip);
1631                 if (length $spec) {
1632                         $spec="$skip and ($spec)";
1633                 }
1634                 else {
1635                         $spec=$skip;
1636                 }
1637         }
1638         return $spec;
1639 } #}}}
1640
1641 sub is_globlist ($) { #{{{
1642         my $s=shift;
1643         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1644 } #}}}
1645
1646 sub safequote ($) { #{{{
1647         my $s=shift;
1648         $s=~s/[{}]//g;
1649         return "q{$s}";
1650 } #}}}
1651
1652 sub add_depends ($$) { #{{{
1653         my $page=shift;
1654         my $pagespec=shift;
1655         
1656         return unless pagespec_valid($pagespec);
1657
1658         if (! exists $depends{$page}) {
1659                 $depends{$page}=$pagespec;
1660         }
1661         else {
1662                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1663         }
1664
1665         return 1;
1666 } # }}}
1667
1668 sub file_pruned ($$) { #{{{
1669         require File::Spec;
1670         my $file=File::Spec->canonpath(shift);
1671         my $base=File::Spec->canonpath(shift);
1672         $file =~ s#^\Q$base\E/+##;
1673
1674         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1675         return $file =~ m/$regexp/ && $file ne $base;
1676 } #}}}
1677
1678 sub gettext { #{{{
1679         # Only use gettext in the rare cases it's needed.
1680         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1681             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1682             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1683                 if (! $gettext_obj) {
1684                         $gettext_obj=eval q{
1685                                 use Locale::gettext q{textdomain};
1686                                 Locale::gettext->domain('ikiwiki')
1687                         };
1688                         if ($@) {
1689                                 print STDERR "$@";
1690                                 $gettext_obj=undef;
1691                                 return shift;
1692                         }
1693                 }
1694                 return $gettext_obj->get(shift);
1695         }
1696         else {
1697                 return shift;
1698         }
1699 } #}}}
1700
1701 sub yesno ($) { #{{{
1702         my $val=shift;
1703
1704         return (defined $val && lc($val) eq gettext("yes"));
1705 } #}}}
1706
1707 sub inject { #{{{
1708         # Injects a new function into the symbol table to replace an
1709         # exported function.
1710         my %params=@_;
1711
1712         # This is deep ugly perl foo, beware.
1713         no strict;
1714         no warnings;
1715         if (! defined $params{parent}) {
1716                 $params{parent}='::';
1717                 $params{old}=\&{$params{name}};
1718                 $params{name}=~s/.*:://;
1719         }
1720         my $parent=$params{parent};
1721         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1722                 $ns = $params{parent} . $ns;
1723                 inject(%params, parent => $ns) unless $ns eq '::main::';
1724                 *{$ns . $params{name}} = $params{call}
1725                         if exists ${$ns}{$params{name}} &&
1726                            \&{${$ns}{$params{name}}} == $params{old};
1727         }
1728         use strict;
1729         use warnings;
1730 } #}}}
1731
1732 sub pagespec_merge ($$) { #{{{
1733         my $a=shift;
1734         my $b=shift;
1735
1736         return $a if $a eq $b;
1737
1738         # Support for old-style GlobLists.
1739         if (is_globlist($a)) {
1740                 $a=globlist_to_pagespec($a);
1741         }
1742         if (is_globlist($b)) {
1743                 $b=globlist_to_pagespec($b);
1744         }
1745
1746         return "($a) or ($b)";
1747 } #}}}
1748
1749 sub pagespec_translate ($) { #{{{
1750         my $spec=shift;
1751
1752         # Support for old-style GlobLists.
1753         if (is_globlist($spec)) {
1754                 $spec=globlist_to_pagespec($spec);
1755         }
1756
1757         # Convert spec to perl code.
1758         my $code="";
1759         while ($spec=~m{
1760                 \s*             # ignore whitespace
1761                 (               # 1: match a single word
1762                         \!              # !
1763                 |
1764                         \(              # (
1765                 |
1766                         \)              # )
1767                 |
1768                         \w+\([^\)]*\)   # command(params)
1769                 |
1770                         [^\s()]+        # any other text
1771                 )
1772                 \s*             # ignore whitespace
1773         }igx) {
1774                 my $word=$1;
1775                 if (lc $word eq 'and') {
1776                         $code.=' &&';
1777                 }
1778                 elsif (lc $word eq 'or') {
1779                         $code.=' ||';
1780                 }
1781                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1782                         $code.=' '.$word;
1783                 }
1784                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1785                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1786                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1787                         }
1788                         else {
1789                                 $code.=' 0';
1790                         }
1791                 }
1792                 else {
1793                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1794                 }
1795         }
1796
1797         if (! length $code) {
1798                 $code=0;
1799         }
1800
1801         no warnings;
1802         return eval 'sub { my $page=shift; '.$code.' }';
1803 } #}}}
1804
1805 sub pagespec_match ($$;@) { #{{{
1806         my $page=shift;
1807         my $spec=shift;
1808         my @params=@_;
1809
1810         # Backwards compatability with old calling convention.
1811         if (@params == 1) {
1812                 unshift @params, 'location';
1813         }
1814
1815         my $sub=pagespec_translate($spec);
1816         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1817         return $sub->($page, @params);
1818 } #}}}
1819
1820 sub pagespec_valid ($) { #{{{
1821         my $spec=shift;
1822
1823         my $sub=pagespec_translate($spec);
1824         return ! $@;
1825 } #}}}
1826
1827 sub glob2re ($) { #{{{
1828         my $re=quotemeta(shift);
1829         $re=~s/\\\*/.*/g;
1830         $re=~s/\\\?/./g;
1831         return $re;
1832 } #}}}
1833
1834 package IkiWiki::FailReason;
1835
1836 use overload ( #{{{
1837         '""'    => sub { ${$_[0]} },
1838         '0+'    => sub { 0 },
1839         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
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::SuccessReason;
1850
1851 use overload ( #{{{
1852         '""'    => sub { ${$_[0]} },
1853         '0+'    => sub { 1 },
1854         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1855         fallback => 1,
1856 ); #}}}
1857
1858 sub new { #{{{
1859         my $class = shift;
1860         my $value = shift;
1861         return bless \$value, $class;
1862 }; #}}}
1863
1864 package IkiWiki::PageSpec;
1865
1866 sub match_glob ($$;@) { #{{{
1867         my $page=shift;
1868         my $glob=shift;
1869         my %params=@_;
1870         
1871         my $from=exists $params{location} ? $params{location} : '';
1872         
1873         # relative matching
1874         if ($glob =~ m!^\./!) {
1875                 $from=~s#/?[^/]+$##;
1876                 $glob=~s#^\./##;
1877                 $glob="$from/$glob" if length $from;
1878         }
1879
1880         my $regexp=IkiWiki::glob2re($glob);
1881         if ($page=~/^$regexp$/i) {
1882                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1883                         return IkiWiki::SuccessReason->new("$glob matches $page");
1884                 }
1885                 else {
1886                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1887                 }
1888         }
1889         else {
1890                 return IkiWiki::FailReason->new("$glob does not match $page");
1891         }
1892 } #}}}
1893
1894 sub match_internal ($$;@) { #{{{
1895         return match_glob($_[0], $_[1], @_, internal => 1)
1896 } #}}}
1897
1898 sub match_link ($$;@) { #{{{
1899         my $page=shift;
1900         my $link=lc(shift);
1901         my %params=@_;
1902
1903         my $from=exists $params{location} ? $params{location} : '';
1904
1905         # relative matching
1906         if ($link =~ m!^\.! && defined $from) {
1907                 $from=~s#/?[^/]+$##;
1908                 $link=~s#^\./##;
1909                 $link="$from/$link" if length $from;
1910         }
1911
1912         my $links = $IkiWiki::links{$page};
1913         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1914         my $bestlink = IkiWiki::bestlink($from, $link);
1915         foreach my $p (@{$links}) {
1916                 if (length $bestlink) {
1917                         return IkiWiki::SuccessReason->new("$page links to $link")
1918                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1919                 }
1920                 else {
1921                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1922                                 if match_glob($p, $link, %params);
1923                 }
1924         }
1925         return IkiWiki::FailReason->new("$page does not link to $link");
1926 } #}}}
1927
1928 sub match_backlink ($$;@) { #{{{
1929         return match_link($_[1], $_[0], @_);
1930 } #}}}
1931
1932 sub match_created_before ($$;@) { #{{{
1933         my $page=shift;
1934         my $testpage=shift;
1935
1936         if (exists $IkiWiki::pagectime{$testpage}) {
1937                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1938                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1939                 }
1940                 else {
1941                         return IkiWiki::FailReason->new("$page not created before $testpage");
1942                 }
1943         }
1944         else {
1945                 return IkiWiki::FailReason->new("$testpage has no ctime");
1946         }
1947 } #}}}
1948
1949 sub match_created_after ($$;@) { #{{{
1950         my $page=shift;
1951         my $testpage=shift;
1952
1953         if (exists $IkiWiki::pagectime{$testpage}) {
1954                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1955                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1956                 }
1957                 else {
1958                         return IkiWiki::FailReason->new("$page not created after $testpage");
1959                 }
1960         }
1961         else {
1962                 return IkiWiki::FailReason->new("$testpage has no ctime");
1963         }
1964 } #}}}
1965
1966 sub match_creation_day ($$;@) { #{{{
1967         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1968                 return IkiWiki::SuccessReason->new('creation_day matched');
1969         }
1970         else {
1971                 return IkiWiki::FailReason->new('creation_day did not match');
1972         }
1973 } #}}}
1974
1975 sub match_creation_month ($$;@) { #{{{
1976         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1977                 return IkiWiki::SuccessReason->new('creation_month matched');
1978         }
1979         else {
1980                 return IkiWiki::FailReason->new('creation_month did not match');
1981         }
1982 } #}}}
1983
1984 sub match_creation_year ($$;@) { #{{{
1985         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1986                 return IkiWiki::SuccessReason->new('creation_year matched');
1987         }
1988         else {
1989                 return IkiWiki::FailReason->new('creation_year did not match');
1990         }
1991 } #}}}
1992
1993 sub match_user ($$;@) { #{{{
1994         shift;
1995         my $user=shift;
1996         my %params=@_;
1997         
1998         if (! exists $params{user}) {
1999                 return IkiWiki::FailReason->new("no user specified");
2000         }
2001
2002         if (defined $params{user} && lc $params{user} eq lc $user) {
2003                 return IkiWiki::SuccessReason->new("user is $user");
2004         }
2005         elsif (! defined $params{user}) {
2006                 return IkiWiki::FailReason->new("not logged in");
2007         }
2008         else {
2009                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2010         }
2011 } #}}}
2012
2013 sub match_admin ($$;@) { #{{{
2014         shift;
2015         shift;
2016         my %params=@_;
2017         
2018         if (! exists $params{user}) {
2019                 return IkiWiki::FailReason->new("no user specified");
2020         }
2021
2022         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2023                 return IkiWiki::SuccessReason->new("user is an admin");
2024         }
2025         elsif (! defined $params{user}) {
2026                 return IkiWiki::FailReason->new("not logged in");
2027         }
2028         else {
2029                 return IkiWiki::FailReason->new("user is not an admin");
2030         }
2031 } #}}}
2032
2033 sub match_ip ($$;@) { #{{{
2034         shift;
2035         my $ip=shift;
2036         my %params=@_;
2037         
2038         if (! exists $params{ip}) {
2039                 return IkiWiki::FailReason->new("no IP specified");
2040         }
2041
2042         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2043                 return IkiWiki::SuccessReason->new("IP is $ip");
2044         }
2045         else {
2046                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2047         }
2048 } #}}}
2049
2050 1