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