untrusted committers code seems to be fully working
[ikiwiki] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use Encode;
8 use HTML::Entities;
9 use URI::Escape q{uri_escape_utf8};
10 use POSIX;
11 use Storable;
12 use open qw{:utf8 :std};
13
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15             %pagestate %wikistate %renderedfiles %oldrenderedfiles
16             %pagesources %destsources %depends %hooks %forcerebuild
17             $gettext_obj %loaded_plugins};
18
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21                  bestlink htmllink readfile writefile pagetype srcfile pagename
22                  displaytime will_render gettext urlto targetpage
23                  add_underlay pagetitle titlepage linkpage newpagefile
24                  inject
25                  %config %links %pagestate %wikistate %renderedfiles
26                  %pagesources %destsources);
27 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
30
31 # Optimisation.
32 use Memoize;
33 memoize("abs2rel");
34 memoize("pagespec_translate");
35 memoize("file_pruned");
36
37 sub getsetup () { #{{{
38         wikiname => {
39                 type => "string",
40                 default => "wiki",
41                 description => "name of the wiki",
42                 safe => 1,
43                 rebuild => 1,
44         },
45         adminemail => {
46                 type => "string",
47                 default => undef,
48                 example => 'me@example.com',
49                 description => "contact email for wiki",
50                 safe => 1,
51                 rebuild => 0,
52         },
53         adminuser => {
54                 type => "string",
55                 default => [],
56                 description => "users who are wiki admins",
57                 safe => 1,
58                 rebuild => 0,
59         },
60         banned_users => {
61                 type => "string",
62                 default => [],
63                 description => "users who are banned from the wiki",
64                 safe => 1,
65                 rebuild => 0,
66         },
67         srcdir => {
68                 type => "string",
69                 default => undef,
70                 example => "$ENV{HOME}/wiki",
71                 description => "where the source of the wiki is located",
72                 safe => 0, # path
73                 rebuild => 1,
74         },
75         destdir => {
76                 type => "string",
77                 default => undef,
78                 example => "/var/www/wiki",
79                 description => "where to build the wiki",
80                 safe => 0, # path
81                 rebuild => 1,
82         },
83         url => {
84                 type => "string",
85                 default => '',
86                 example => "http://example.com/wiki",
87                 description => "base url to the wiki",
88                 safe => 1,
89                 rebuild => 1,
90         },
91         cgiurl => {
92                 type => "string",
93                 default => '',
94                 example => "http://example.com/wiki/ikiwiki.cgi",
95                 description => "url to the ikiwiki.cgi",
96                 safe => 1,
97                 rebuild => 1,
98         },
99         cgi_wrapper => {
100                 type => "string",
101                 default => '',
102                 example => "/var/www/wiki/ikiwiki.cgi",
103                 description => "cgi wrapper to generate",
104                 safe => 0, # file
105                 rebuild => 0,
106         },
107         cgi_wrappermode => {
108                 type => "string",
109                 default => '06755',
110                 description => "mode for cgi_wrapper (can safely be made suid)",
111                 safe => 0,
112                 rebuild => 0,
113         },
114         rcs => {
115                 type => "string",
116                 default => '',
117                 description => "rcs backend to use",
118                 safe => 0, # don't allow overriding
119                 rebuild => 0,
120         },
121         default_plugins => {
122                 type => "internal",
123                 default => [qw{mdwn link inline htmlscrubber passwordauth
124                                 openid signinedit lockedit conditional
125                                 recentchanges parentlinks editpage}],
126                 description => "plugins to enable by default",
127                 safe => 0,
128                 rebuild => 1,
129         },
130         add_plugins => {
131                 type => "string",
132                 default => [],
133                 description => "plugins to add to the default configuration",
134                 safe => 1,
135                 rebuild => 1,
136         },
137         disable_plugins => {
138                 type => "string",
139                 default => [],
140                 description => "plugins to disable",
141                 safe => 1,
142                 rebuild => 1,
143         },
144         templatedir => {
145                 type => "string",
146                 default => "$installdir/share/ikiwiki/templates",
147                 description => "location of template files",
148                 advanced => 1,
149                 safe => 0, # path
150                 rebuild => 1,
151         },
152         underlaydir => {
153                 type => "string",
154                 default => "$installdir/share/ikiwiki/basewiki",
155                 description => "base wiki source location",
156                 advanced => 1,
157                 safe => 0, # path
158                 rebuild => 0,
159         },
160         wrappers => {
161                 type => "internal",
162                 default => [],
163                 description => "wrappers to generate",
164                 safe => 0,
165                 rebuild => 0,
166         },
167         underlaydirs => {
168                 type => "internal",
169                 default => [],
170                 description => "additional underlays to use",
171                 safe => 0,
172                 rebuild => 0,
173         },
174         verbose => {
175                 type => "boolean",
176                 example => 1,
177                 description => "display verbose messages when building?",
178                 safe => 1,
179                 rebuild => 0,
180         },
181         syslog => {
182                 type => "boolean",
183                 example => 1,
184                 description => "log to syslog?",
185                 safe => 1,
186                 rebuild => 0,
187         },
188         usedirs => {
189                 type => "boolean",
190                 default => 1,
191                 description => "create output files named page/index.html?",
192                 safe => 0, # changing requires manual transition
193                 rebuild => 1,
194         },
195         prefix_directives => {
196                 type => "boolean",
197                 default => 0,
198                 description => "use '!'-prefixed preprocessor directives?",
199                 safe => 0, # changing requires manual transition
200                 rebuild => 1,
201         },
202         indexpages => {
203                 type => "boolean",
204                 default => 0,
205                 description => "use page/index.mdwn source files",
206                 safe => 1,
207                 rebuild => 1,
208         },
209         discussion => {
210                 type => "boolean",
211                 default => 1,
212                 description => "enable Discussion pages?",
213                 safe => 1,
214                 rebuild => 1,
215         },
216         sslcookie => {
217                 type => "boolean",
218                 default => 0,
219                 description => "only send cookies over SSL connections?",
220                 advanced => 1,
221                 safe => 1,
222                 rebuild => 0,
223         },
224         default_pageext => {
225                 type => "string",
226                 default => "mdwn",
227                 description => "extension to use for new pages",
228                 safe => 0, # not sanitized
229                 rebuild => 0,
230         },
231         htmlext => {
232                 type => "string",
233                 default => "html",
234                 description => "extension to use for html files",
235                 safe => 0, # not sanitized
236                 rebuild => 1,
237         },
238         timeformat => {
239                 type => "string",
240                 default => '%c',
241                 description => "strftime format string to display date",
242                 advanced => 1,
243                 safe => 1,
244                 rebuild => 1,
245         },
246         locale => {
247                 type => "string",
248                 default => undef,
249                 example => "en_US.UTF-8",
250                 description => "UTF-8 locale to use",
251                 advanced => 1,
252                 safe => 0,
253                 rebuild => 1,
254         },
255         userdir => {
256                 type => "string",
257                 default => "",
258                 example => "users",
259                 description => "put user pages below specified page",
260                 safe => 1,
261                 rebuild => 1,
262         },
263         numbacklinks => {
264                 type => "integer",
265                 default => 10,
266                 description => "how many backlinks to show before hiding excess (0 to show all)",
267                 safe => 1,
268                 rebuild => 1,
269         },
270         hardlink => {
271                 type => "boolean",
272                 default => 0,
273                 description => "attempt to hardlink source files? (optimisation for large files)",
274                 advanced => 1,
275                 safe => 0, # paranoia
276                 rebuild => 0,
277         },
278         umask => {
279                 type => "integer",
280                 description => "",
281                 example => "022",
282                 description => "force ikiwiki to use a particular umask",
283                 advanced => 1,
284                 safe => 0, # paranoia
285                 rebuild => 0,
286         },
287         libdir => {
288                 type => "string",
289                 default => "",
290                 example => "$ENV{HOME}/.ikiwiki/",
291                 description => "extra library and plugin directory",
292                 advanced => 1,
293                 safe => 0, # directory
294                 rebuild => 0,
295         },
296         ENV => {
297                 type => "string", 
298                 default => {},
299                 description => "environment variables",
300                 safe => 0, # paranoia
301                 rebuild => 0,
302         },
303         exclude => {
304                 type => "string",
305                 default => undef,
306                 example => '\.wav$',
307                 description => "regexp of source files to ignore",
308                 advanced => 1,
309                 safe => 0, # regexp
310                 rebuild => 1,
311         },
312         wiki_file_prune_regexps => {
313                 type => "internal",
314                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
315                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
316                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
317                         qr/(^|\/)_MTN\//,
318                         qr/\.dpkg-tmp$/],
319                 description => "regexps of source files to ignore",
320                 safe => 0,
321                 rebuild => 1,
322         },
323         wiki_file_chars => {
324                 type => "string",
325                 description => "specifies the characters that are allowed in source filenames",
326                 default => "-[:alnum:]+/.:_",
327                 safe => 0,
328                 rebuild => 1,
329         },
330         wiki_file_regexp => {
331                 type => "internal",
332                 description => "regexp of legal source files",
333                 safe => 0,
334                 rebuild => 1,
335         },
336         web_commit_regexp => {
337                 type => "internal",
338                 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
339                 description => "regexp to parse web commits from logs",
340                 safe => 0,
341                 rebuild => 0,
342         },
343         cgi => {
344                 type => "internal",
345                 default => 0,
346                 description => "run as a cgi",
347                 safe => 0,
348                 rebuild => 0,
349         },
350         cgi_disable_uploads => {
351                 type => "internal",
352                 default => 1,
353                 description => "whether CGI should accept file uploads",
354                 safe => 0,
355                 rebuild => 0,
356         },
357         post_commit => {
358                 type => "internal",
359                 default => 0,
360                 description => "run as a post-commit hook",
361                 safe => 0,
362                 rebuild => 0,
363         },
364         rebuild => {
365                 type => "internal",
366                 default => 0,
367                 description => "running in rebuild mode",
368                 safe => 0,
369                 rebuild => 0,
370         },
371         setup => {
372                 type => "internal",
373                 default => undef,
374                 description => "running in setup mode",
375                 safe => 0,
376                 rebuild => 0,
377         },
378         refresh => {
379                 type => "internal",
380                 default => 0,
381                 description => "running in refresh mode",
382                 safe => 0,
383                 rebuild => 0,
384         },
385         test_receive => {
386                 type => "internal",
387                 default => 0,
388                 description => "running in receive test mode",
389                 safe => 0,
390                 rebuild => 0,
391         },
392         getctime => {
393                 type => "internal",
394                 default => 0,
395                 description => "running in getctime mode",
396                 safe => 0,
397                 rebuild => 0,
398         },
399         w3mmode => {
400                 type => "internal",
401                 default => 0,
402                 description => "running in w3mmode",
403                 safe => 0,
404                 rebuild => 0,
405         },
406         setupfile => {
407                 type => "internal",
408                 default => undef,
409                 description => "path to setup file",
410                 safe => 0,
411                 rebuild => 0,
412         },
413         allow_symlinks_before_srcdir => {
414                 type => "string",
415                 default => 0,
416                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
417                 safe => 0,
418                 rebuild => 0,
419         },
420 } #}}}
421
422 sub defaultconfig () { #{{{
423         my %s=getsetup();
424         my @ret;
425         foreach my $key (keys %s) {
426                 push @ret, $key, $s{$key}->{default};
427         }
428         use Data::Dumper;
429         return @ret;
430 } #}}}
431
432 sub checkconfig () { #{{{
433         # locale stuff; avoid LC_ALL since it overrides everything
434         if (defined $ENV{LC_ALL}) {
435                 $ENV{LANG} = $ENV{LC_ALL};
436                 delete $ENV{LC_ALL};
437         }
438         if (defined $config{locale}) {
439                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
440                         $ENV{LANG}=$config{locale};
441                         $gettext_obj=undef;
442                 }
443         }
444                 
445         if (! defined $config{wiki_file_regexp}) {
446                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
447         }
448
449         if (ref $config{ENV} eq 'HASH') {
450                 foreach my $val (keys %{$config{ENV}}) {
451                         $ENV{$val}=$config{ENV}{$val};
452                 }
453         }
454
455         if ($config{w3mmode}) {
456                 eval q{use Cwd q{abs_path}};
457                 error($@) if $@;
458                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
459                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
460                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
461                         unless $config{cgiurl} =~ m!file:///!;
462                 $config{url}="file://".$config{destdir};
463         }
464
465         if ($config{cgi} && ! length $config{url}) {
466                 error(gettext("Must specify url to wiki with --url when using --cgi"));
467         }
468         
469         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
470                 unless exists $config{wikistatedir};
471
472         if (defined $config{umask}) {
473                 umask(possibly_foolish_untaint($config{umask}));
474         }
475
476         run_hooks(checkconfig => sub { shift->() });
477
478         return 1;
479 } #}}}
480
481 sub listplugins () { #{{{
482         my %ret;
483
484         foreach my $dir (@INC, $config{libdir}) {
485                 next unless defined $dir && length $dir;
486                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
487                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
488                         $ret{$plugin}=1;
489                 }
490         }
491         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
492                 next unless defined $dir && length $dir;
493                 foreach my $file (glob("$dir/plugins/*")) {
494                         $ret{basename($file)}=1 if -x $file;
495                 }
496         }
497
498         return keys %ret;
499 } #}}}
500
501 sub loadplugins () { #{{{
502         if (defined $config{libdir} && length $config{libdir}) {
503                 unshift @INC, possibly_foolish_untaint($config{libdir});
504         }
505
506         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
507                 loadplugin($plugin);
508         }
509         
510         if ($config{rcs}) {
511                 if (exists $IkiWiki::hooks{rcs}) {
512                         error(gettext("cannot use multiple rcs plugins"));
513                 }
514                 loadplugin($config{rcs});
515         }
516         if (! exists $IkiWiki::hooks{rcs}) {
517                 loadplugin("norcs");
518         }
519
520         run_hooks(getopt => sub { shift->() });
521         if (grep /^-/, @ARGV) {
522                 print STDERR "Unknown option: $_\n"
523                         foreach grep /^-/, @ARGV;
524                 usage();
525         }
526
527         return 1;
528 } #}}}
529
530 sub loadplugin ($) { #{{{
531         my $plugin=shift;
532
533         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
534
535         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
536                          "$installdir/lib/ikiwiki") {
537                 if (defined $dir && -x "$dir/plugins/$plugin") {
538                         eval { require IkiWiki::Plugin::external };
539                         if ($@) {
540                                 my $reason=$@;
541                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
542                         }
543                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
544                         $loaded_plugins{$plugin}=1;
545                         return 1;
546                 }
547         }
548
549         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
550         eval qq{use $mod};
551         if ($@) {
552                 error("Failed to load plugin $mod: $@");
553         }
554         $loaded_plugins{$plugin}=1;
555         return 1;
556 } #}}}
557
558 sub error ($;$) { #{{{
559         my $message=shift;
560         my $cleaner=shift;
561         log_message('err' => $message) if $config{syslog};
562         if (defined $cleaner) {
563                 $cleaner->();
564         }
565         die $message."\n";
566 } #}}}
567
568 sub debug ($) { #{{{
569         return unless $config{verbose};
570         return log_message(debug => @_);
571 } #}}}
572
573 my $log_open=0;
574 sub log_message ($$) { #{{{
575         my $type=shift;
576
577         if ($config{syslog}) {
578                 require Sys::Syslog;
579                 if (! $log_open) {
580                         Sys::Syslog::setlogsock('unix');
581                         Sys::Syslog::openlog('ikiwiki', '', 'user');
582                         $log_open=1;
583                 }
584                 return eval {
585                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
586                 };
587         }
588         elsif (! $config{cgi}) {
589                 return print "@_\n";
590         }
591         else {
592                 return print STDERR "@_\n";
593         }
594 } #}}}
595
596 sub possibly_foolish_untaint ($) { #{{{
597         my $tainted=shift;
598         my ($untainted)=$tainted=~/(.*)/s;
599         return $untainted;
600 } #}}}
601
602 sub basename ($) { #{{{
603         my $file=shift;
604
605         $file=~s!.*/+!!;
606         return $file;
607 } #}}}
608
609 sub dirname ($) { #{{{
610         my $file=shift;
611
612         $file=~s!/*[^/]+$!!;
613         return $file;
614 } #}}}
615
616 sub pagetype ($) { #{{{
617         my $page=shift;
618         
619         if ($page =~ /\.([^.]+)$/) {
620                 return $1 if exists $hooks{htmlize}{$1};
621         }
622         return;
623 } #}}}
624
625 sub isinternal ($) { #{{{
626         my $page=shift;
627         return exists $pagesources{$page} &&
628                 $pagesources{$page} =~ /\._([^.]+)$/;
629 } #}}}
630
631 sub pagename ($) { #{{{
632         my $file=shift;
633
634         my $type=pagetype($file);
635         my $page=$file;
636         $page=~s/\Q.$type\E*$// if defined $type && !$hooks{htmlize}{$type}{keepextension};
637         if ($config{indexpages} && $page=~/(.*)\/index$/) {
638                 $page=$1;
639         }
640         return $page;
641 } #}}}
642
643 sub newpagefile ($$) { #{{{
644         my $page=shift;
645         my $type=shift;
646
647         if (! $config{indexpages} || $page eq 'index') {
648                 return $page.".".$type;
649         }
650         else {
651                 return $page."/index.".$type;
652         }
653 } #}}}
654
655 sub targetpage ($$) { #{{{
656         my $page=shift;
657         my $ext=shift;
658         
659         if (! $config{usedirs} || $page eq 'index') {
660                 return $page.".".$ext;
661         }
662         else {
663                 return $page."/index.".$ext;
664         }
665 } #}}}
666
667 sub htmlpage ($) { #{{{
668         my $page=shift;
669         
670         return targetpage($page, $config{htmlext});
671 } #}}}
672
673 sub srcfile_stat { #{{{
674         my $file=shift;
675         my $nothrow=shift;
676
677         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
678         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
679                 return "$dir/$file", stat(_) if -e "$dir/$file";
680         }
681         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
682         return;
683 } #}}}
684
685 sub srcfile ($;$) { #{{{
686         return (srcfile_stat(@_))[0];
687 } #}}}
688
689 sub add_underlay ($) { #{{{
690         my $dir=shift;
691
692         if ($dir !~ /^\//) {
693                 $dir="$config{underlaydir}/../$dir";
694         }
695
696         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
697                 unshift @{$config{underlaydirs}}, $dir;
698         }
699
700         return 1;
701 } #}}}
702
703 sub readfile ($;$$) { #{{{
704         my $file=shift;
705         my $binary=shift;
706         my $wantfd=shift;
707
708         if (-l $file) {
709                 error("cannot read a symlink ($file)");
710         }
711         
712         local $/=undef;
713         open (my $in, "<", $file) || error("failed to read $file: $!");
714         binmode($in) if ($binary);
715         return \*$in if $wantfd;
716         my $ret=<$in>;
717         close $in || error("failed to read $file: $!");
718         return $ret;
719 } #}}}
720
721 sub prep_writefile ($$) { #{{{
722         my $file=shift;
723         my $destdir=shift;
724         
725         my $test=$file;
726         while (length $test) {
727                 if (-l "$destdir/$test") {
728                         error("cannot write to a symlink ($test)");
729                 }
730                 $test=dirname($test);
731         }
732
733         my $dir=dirname("$destdir/$file");
734         if (! -d $dir) {
735                 my $d="";
736                 foreach my $s (split(m!/+!, $dir)) {
737                         $d.="$s/";
738                         if (! -d $d) {
739                                 mkdir($d) || error("failed to create directory $d: $!");
740                         }
741                 }
742         }
743
744         return 1;
745 } #}}}
746
747 sub writefile ($$$;$$) { #{{{
748         my $file=shift; # can include subdirs
749         my $destdir=shift; # directory to put file in
750         my $content=shift;
751         my $binary=shift;
752         my $writer=shift;
753         
754         prep_writefile($file, $destdir);
755         
756         my $newfile="$destdir/$file.ikiwiki-new";
757         if (-l $newfile) {
758                 error("cannot write to a symlink ($newfile)");
759         }
760         
761         my $cleanup = sub { unlink($newfile) };
762         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
763         binmode($out) if ($binary);
764         if ($writer) {
765                 $writer->(\*$out, $cleanup);
766         }
767         else {
768                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
769         }
770         close $out || error("failed saving $newfile: $!", $cleanup);
771         rename($newfile, "$destdir/$file") || 
772                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
773
774         return 1;
775 } #}}}
776
777 my %cleared;
778 sub will_render ($$;$) { #{{{
779         my $page=shift;
780         my $dest=shift;
781         my $clear=shift;
782
783         # Important security check.
784         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
785             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
786                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
787         }
788
789         if (! $clear || $cleared{$page}) {
790                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
791         }
792         else {
793                 foreach my $old (@{$renderedfiles{$page}}) {
794                         delete $destsources{$old};
795                 }
796                 $renderedfiles{$page}=[$dest];
797                 $cleared{$page}=1;
798         }
799         $destsources{$dest}=$page;
800
801         return 1;
802 } #}}}
803
804 sub bestlink ($$) { #{{{
805         my $page=shift;
806         my $link=shift;
807         
808         my $cwd=$page;
809         if ($link=~s/^\/+//) {
810                 # absolute links
811                 $cwd="";
812         }
813         $link=~s/\/$//;
814
815         do {
816                 my $l=$cwd;
817                 $l.="/" if length $l;
818                 $l.=$link;
819
820                 if (exists $links{$l}) {
821                         return $l;
822                 }
823                 elsif (exists $pagecase{lc $l}) {
824                         return $pagecase{lc $l};
825                 }
826         } while $cwd=~s{/?[^/]+$}{};
827
828         if (length $config{userdir}) {
829                 my $l = "$config{userdir}/".lc($link);
830                 if (exists $links{$l}) {
831                         return $l;
832                 }
833                 elsif (exists $pagecase{lc $l}) {
834                         return $pagecase{lc $l};
835                 }
836         }
837
838         #print STDERR "warning: page $page, broken link: $link\n";
839         return "";
840 } #}}}
841
842 sub isinlinableimage ($) { #{{{
843         my $file=shift;
844         
845         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
846 } #}}}
847
848 sub pagetitle ($;$) { #{{{
849         my $page=shift;
850         my $unescaped=shift;
851
852         if ($unescaped) {
853                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
854         }
855         else {
856                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
857         }
858
859         return $page;
860 } #}}}
861
862 sub titlepage ($) { #{{{
863         my $title=shift;
864         # support use w/o %config set
865         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
866         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
867         return $title;
868 } #}}}
869
870 sub linkpage ($) { #{{{
871         my $link=shift;
872         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
873         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
874         return $link;
875 } #}}}
876
877 sub cgiurl (@) { #{{{
878         my %params=@_;
879
880         return $config{cgiurl}."?".
881                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
882 } #}}}
883
884 sub baseurl (;$) { #{{{
885         my $page=shift;
886
887         return "$config{url}/" if ! defined $page;
888         
889         $page=htmlpage($page);
890         $page=~s/[^\/]+$//;
891         $page=~s/[^\/]+\//..\//g;
892         return $page;
893 } #}}}
894
895 sub abs2rel ($$) { #{{{
896         # Work around very innefficient behavior in File::Spec if abs2rel
897         # is passed two relative paths. It's much faster if paths are
898         # absolute! (Debian bug #376658; fixed in debian unstable now)
899         my $path="/".shift;
900         my $base="/".shift;
901
902         require File::Spec;
903         my $ret=File::Spec->abs2rel($path, $base);
904         $ret=~s/^// if defined $ret;
905         return $ret;
906 } #}}}
907
908 sub displaytime ($;$) { #{{{
909         # Plugins can override this function to mark up the time to
910         # display.
911         return '<span class="date">'.formattime(@_).'</span>';
912 } #}}}
913
914 sub formattime ($;$) { #{{{
915         # Plugins can override this function to format the time.
916         my $time=shift;
917         my $format=shift;
918         if (! defined $format) {
919                 $format=$config{timeformat};
920         }
921
922         # strftime doesn't know about encodings, so make sure
923         # its output is properly treated as utf8
924         return decode_utf8(POSIX::strftime($format, localtime($time)));
925 } #}}}
926
927 sub beautify_urlpath ($) { #{{{
928         my $url=shift;
929
930         if ($config{usedirs}) {
931                 $url =~ s!/index.$config{htmlext}$!/!;
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 rcs_receive () { #{{{
1586         $hooks{rcs}{rcs_receive}{call}->();
1587 } #}}}
1588
1589 sub globlist_to_pagespec ($) { #{{{
1590         my @globlist=split(' ', shift);
1591
1592         my (@spec, @skip);
1593         foreach my $glob (@globlist) {
1594                 if ($glob=~/^!(.*)/) {
1595                         push @skip, $glob;
1596                 }
1597                 else {
1598                         push @spec, $glob;
1599                 }
1600         }
1601
1602         my $spec=join(' or ', @spec);
1603         if (@skip) {
1604                 my $skip=join(' and ', @skip);
1605                 if (length $spec) {
1606                         $spec="$skip and ($spec)";
1607                 }
1608                 else {
1609                         $spec=$skip;
1610                 }
1611         }
1612         return $spec;
1613 } #}}}
1614
1615 sub is_globlist ($) { #{{{
1616         my $s=shift;
1617         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1618 } #}}}
1619
1620 sub safequote ($) { #{{{
1621         my $s=shift;
1622         $s=~s/[{}]//g;
1623         return "q{$s}";
1624 } #}}}
1625
1626 sub add_depends ($$) { #{{{
1627         my $page=shift;
1628         my $pagespec=shift;
1629         
1630         return unless pagespec_valid($pagespec);
1631
1632         if (! exists $depends{$page}) {
1633                 $depends{$page}=$pagespec;
1634         }
1635         else {
1636                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1637         }
1638
1639         return 1;
1640 } # }}}
1641
1642 sub file_pruned ($$) { #{{{
1643         require File::Spec;
1644         my $file=File::Spec->canonpath(shift);
1645         my $base=File::Spec->canonpath(shift);
1646         $file =~ s#^\Q$base\E/+##;
1647
1648         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1649         return $file =~ m/$regexp/ && $file ne $base;
1650 } #}}}
1651
1652 sub gettext { #{{{
1653         # Only use gettext in the rare cases it's needed.
1654         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1655             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1656             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1657                 if (! $gettext_obj) {
1658                         $gettext_obj=eval q{
1659                                 use Locale::gettext q{textdomain};
1660                                 Locale::gettext->domain('ikiwiki')
1661                         };
1662                         if ($@) {
1663                                 print STDERR "$@";
1664                                 $gettext_obj=undef;
1665                                 return shift;
1666                         }
1667                 }
1668                 return $gettext_obj->get(shift);
1669         }
1670         else {
1671                 return shift;
1672         }
1673 } #}}}
1674
1675 sub yesno ($) { #{{{
1676         my $val=shift;
1677
1678         return (defined $val && lc($val) eq gettext("yes"));
1679 } #}}}
1680
1681 sub inject { #{{{
1682         # Injects a new function into the symbol table to replace an
1683         # exported function.
1684         my %params=@_;
1685
1686         # This is deep ugly perl foo, beware.
1687         no strict;
1688         no warnings;
1689         if (! defined $params{parent}) {
1690                 $params{parent}='::';
1691                 $params{old}=\&{$params{name}};
1692                 $params{name}=~s/.*:://;
1693         }
1694         my $parent=$params{parent};
1695         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1696                 $ns = $params{parent} . $ns;
1697                 inject(%params, parent => $ns) unless $ns eq '::main::';
1698                 *{$ns . $params{name}} = $params{call}
1699                         if exists ${$ns}{$params{name}} &&
1700                            \&{${$ns}{$params{name}}} == $params{old};
1701         }
1702         use strict;
1703         use warnings;
1704 } #}}}
1705
1706 sub pagespec_merge ($$) { #{{{
1707         my $a=shift;
1708         my $b=shift;
1709
1710         return $a if $a eq $b;
1711
1712         # Support for old-style GlobLists.
1713         if (is_globlist($a)) {
1714                 $a=globlist_to_pagespec($a);
1715         }
1716         if (is_globlist($b)) {
1717                 $b=globlist_to_pagespec($b);
1718         }
1719
1720         return "($a) or ($b)";
1721 } #}}}
1722
1723 sub pagespec_translate ($) { #{{{
1724         my $spec=shift;
1725
1726         # Support for old-style GlobLists.
1727         if (is_globlist($spec)) {
1728                 $spec=globlist_to_pagespec($spec);
1729         }
1730
1731         # Convert spec to perl code.
1732         my $code="";
1733         while ($spec=~m{
1734                 \s*             # ignore whitespace
1735                 (               # 1: match a single word
1736                         \!              # !
1737                 |
1738                         \(              # (
1739                 |
1740                         \)              # )
1741                 |
1742                         \w+\([^\)]*\)   # command(params)
1743                 |
1744                         [^\s()]+        # any other text
1745                 )
1746                 \s*             # ignore whitespace
1747         }igx) {
1748                 my $word=$1;
1749                 if (lc $word eq 'and') {
1750                         $code.=' &&';
1751                 }
1752                 elsif (lc $word eq 'or') {
1753                         $code.=' ||';
1754                 }
1755                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1756                         $code.=' '.$word;
1757                 }
1758                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1759                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1760                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1761                         }
1762                         else {
1763                                 $code.=' 0';
1764                         }
1765                 }
1766                 else {
1767                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1768                 }
1769         }
1770
1771         if (! length $code) {
1772                 $code=0;
1773         }
1774
1775         no warnings;
1776         return eval 'sub { my $page=shift; '.$code.' }';
1777 } #}}}
1778
1779 sub pagespec_match ($$;@) { #{{{
1780         my $page=shift;
1781         my $spec=shift;
1782         my @params=@_;
1783
1784         # Backwards compatability with old calling convention.
1785         if (@params == 1) {
1786                 unshift @params, 'location';
1787         }
1788
1789         my $sub=pagespec_translate($spec);
1790         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1791         return $sub->($page, @params);
1792 } #}}}
1793
1794 sub pagespec_valid ($) { #{{{
1795         my $spec=shift;
1796
1797         my $sub=pagespec_translate($spec);
1798         return ! $@;
1799 } #}}}
1800
1801 sub glob2re ($) { #{{{
1802         my $re=quotemeta(shift);
1803         $re=~s/\\\*/.*/g;
1804         $re=~s/\\\?/./g;
1805         return $re;
1806 } #}}}
1807
1808 package IkiWiki::FailReason;
1809
1810 use overload ( #{{{
1811         '""'    => sub { ${$_[0]} },
1812         '0+'    => sub { 0 },
1813         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1814         fallback => 1,
1815 ); #}}}
1816
1817 sub new { #{{{
1818         my $class = shift;
1819         my $value = shift;
1820         return bless \$value, $class;
1821 } #}}}
1822
1823 package IkiWiki::SuccessReason;
1824
1825 use overload ( #{{{
1826         '""'    => sub { ${$_[0]} },
1827         '0+'    => sub { 1 },
1828         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1829         fallback => 1,
1830 ); #}}}
1831
1832 sub new { #{{{
1833         my $class = shift;
1834         my $value = shift;
1835         return bless \$value, $class;
1836 }; #}}}
1837
1838 package IkiWiki::PageSpec;
1839
1840 sub match_glob ($$;@) { #{{{
1841         my $page=shift;
1842         my $glob=shift;
1843         my %params=@_;
1844         
1845         my $from=exists $params{location} ? $params{location} : '';
1846         
1847         # relative matching
1848         if ($glob =~ m!^\./!) {
1849                 $from=~s#/?[^/]+$##;
1850                 $glob=~s#^\./##;
1851                 $glob="$from/$glob" if length $from;
1852         }
1853
1854         my $regexp=IkiWiki::glob2re($glob);
1855         if ($page=~/^$regexp$/i) {
1856                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1857                         return IkiWiki::SuccessReason->new("$glob matches $page");
1858                 }
1859                 else {
1860                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1861                 }
1862         }
1863         else {
1864                 return IkiWiki::FailReason->new("$glob does not match $page");
1865         }
1866 } #}}}
1867
1868 sub match_internal ($$;@) { #{{{
1869         return match_glob($_[0], $_[1], @_, internal => 1)
1870 } #}}}
1871
1872 sub match_link ($$;@) { #{{{
1873         my $page=shift;
1874         my $link=lc(shift);
1875         my %params=@_;
1876
1877         my $from=exists $params{location} ? $params{location} : '';
1878
1879         # relative matching
1880         if ($link =~ m!^\.! && defined $from) {
1881                 $from=~s#/?[^/]+$##;
1882                 $link=~s#^\./##;
1883                 $link="$from/$link" if length $from;
1884         }
1885
1886         my $links = $IkiWiki::links{$page};
1887         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1888         my $bestlink = IkiWiki::bestlink($from, $link);
1889         foreach my $p (@{$links}) {
1890                 if (length $bestlink) {
1891                         return IkiWiki::SuccessReason->new("$page links to $link")
1892                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1893                 }
1894                 else {
1895                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1896                                 if match_glob($p, $link, %params);
1897                 }
1898         }
1899         return IkiWiki::FailReason->new("$page does not link to $link");
1900 } #}}}
1901
1902 sub match_backlink ($$;@) { #{{{
1903         return match_link($_[1], $_[0], @_);
1904 } #}}}
1905
1906 sub match_created_before ($$;@) { #{{{
1907         my $page=shift;
1908         my $testpage=shift;
1909
1910         if (exists $IkiWiki::pagectime{$testpage}) {
1911                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1912                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1913                 }
1914                 else {
1915                         return IkiWiki::FailReason->new("$page not created before $testpage");
1916                 }
1917         }
1918         else {
1919                 return IkiWiki::FailReason->new("$testpage has no ctime");
1920         }
1921 } #}}}
1922
1923 sub match_created_after ($$;@) { #{{{
1924         my $page=shift;
1925         my $testpage=shift;
1926
1927         if (exists $IkiWiki::pagectime{$testpage}) {
1928                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1929                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1930                 }
1931                 else {
1932                         return IkiWiki::FailReason->new("$page not created after $testpage");
1933                 }
1934         }
1935         else {
1936                 return IkiWiki::FailReason->new("$testpage has no ctime");
1937         }
1938 } #}}}
1939
1940 sub match_creation_day ($$;@) { #{{{
1941         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1942                 return IkiWiki::SuccessReason->new('creation_day matched');
1943         }
1944         else {
1945                 return IkiWiki::FailReason->new('creation_day did not match');
1946         }
1947 } #}}}
1948
1949 sub match_creation_month ($$;@) { #{{{
1950         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1951                 return IkiWiki::SuccessReason->new('creation_month matched');
1952         }
1953         else {
1954                 return IkiWiki::FailReason->new('creation_month did not match');
1955         }
1956 } #}}}
1957
1958 sub match_creation_year ($$;@) { #{{{
1959         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1960                 return IkiWiki::SuccessReason->new('creation_year matched');
1961         }
1962         else {
1963                 return IkiWiki::FailReason->new('creation_year did not match');
1964         }
1965 } #}}}
1966
1967 sub match_user ($$;@) { #{{{
1968         shift;
1969         my $user=shift;
1970         my %params=@_;
1971         
1972         if (! exists $params{user}) {
1973                 return IkiWiki::FailReason->new("no user specified");
1974         }
1975
1976         if (defined $params{user} && lc $params{user} eq lc $user) {
1977                 return IkiWiki::SuccessReason->new("user is $user");
1978         }
1979         elsif (! defined $params{user}) {
1980                 return IkiWiki::FailReason->new("not logged in");
1981         }
1982         else {
1983                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
1984         }
1985 } #}}}
1986
1987 sub match_admin ($$;@) { #{{{
1988         shift;
1989         shift;
1990         my %params=@_;
1991         
1992         if (! exists $params{user}) {
1993                 return IkiWiki::FailReason->new("no user specified");
1994         }
1995
1996         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
1997                 return IkiWiki::SuccessReason->new("user is an admin");
1998         }
1999         elsif (! defined $params{user}) {
2000                 return IkiWiki::FailReason->new("not logged in");
2001         }
2002         else {
2003                 return IkiWiki::FailReason->new("user is not an admin");
2004         }
2005 } #}}}
2006
2007 sub match_ip ($$;@) { #{{{
2008         shift;
2009         my $ip=shift;
2010         my %params=@_;
2011         
2012         if (! exists $params{ip}) {
2013                 return IkiWiki::FailReason->new("no IP specified");
2014         }
2015
2016         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2017                 return IkiWiki::SuccessReason->new("IP is $ip");
2018         }
2019         else {
2020                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2021         }
2022 } #}}}
2023
2024 1