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