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