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