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