link fix
[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 %depends_simple %hooks
17             %forcerebuild %loaded_plugins %typedlinks %oldtypedlinks};
18
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage deptype
21                  add_depends pagespec_match pagespec_match_list bestlink
22                  htmllink readfile writefile pagetype srcfile pagename
23                  displaytime will_render gettext ngettext urlto targetpage
24                  add_underlay pagetitle titlepage linkpage newpagefile
25                  inject add_link
26                  %config %links %pagestate %wikistate %renderedfiles
27                  %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
31
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
35 our $DEPEND_LINKS=4;
36
37 # Optimisation.
38 use Memoize;
39 memoize("abs2rel");
40 memoize("sortspec_translate");
41 memoize("pagespec_translate");
42 memoize("template_file");
43
44 sub getsetup () {
45         wikiname => {
46                 type => "string",
47                 default => "wiki",
48                 description => "name of the wiki",
49                 safe => 1,
50                 rebuild => 1,
51         },
52         adminemail => {
53                 type => "string",
54                 default => undef,
55                 example => 'me@example.com',
56                 description => "contact email for wiki",
57                 safe => 1,
58                 rebuild => 0,
59         },
60         adminuser => {
61                 type => "string",
62                 default => [],
63                 description => "users who are wiki admins",
64                 safe => 1,
65                 rebuild => 0,
66         },
67         banned_users => {
68                 type => "string",
69                 default => [],
70                 description => "users who are banned from the wiki",
71                 safe => 1,
72                 rebuild => 0,
73         },
74         srcdir => {
75                 type => "string",
76                 default => undef,
77                 example => "$ENV{HOME}/wiki",
78                 description => "where the source of the wiki is located",
79                 safe => 0, # path
80                 rebuild => 1,
81         },
82         destdir => {
83                 type => "string",
84                 default => undef,
85                 example => "/var/www/wiki",
86                 description => "where to build the wiki",
87                 safe => 0, # path
88                 rebuild => 1,
89         },
90         url => {
91                 type => "string",
92                 default => '',
93                 example => "http://example.com/wiki",
94                 description => "base url to the wiki",
95                 safe => 1,
96                 rebuild => 1,
97         },
98         cgiurl => {
99                 type => "string",
100                 default => '',
101                 example => "http://example.com/wiki/ikiwiki.cgi",
102                 description => "url to the ikiwiki.cgi",
103                 safe => 1,
104                 rebuild => 1,
105         },
106         cgi_wrapper => {
107                 type => "string",
108                 default => '',
109                 example => "/var/www/wiki/ikiwiki.cgi",
110                 description => "filename of cgi wrapper to generate",
111                 safe => 0, # file
112                 rebuild => 0,
113         },
114         cgi_wrappermode => {
115                 type => "string",
116                 default => '06755',
117                 description => "mode for cgi_wrapper (can safely be made suid)",
118                 safe => 0,
119                 rebuild => 0,
120         },
121         rcs => {
122                 type => "string",
123                 default => '',
124                 description => "rcs backend to use",
125                 safe => 0, # don't allow overriding
126                 rebuild => 0,
127         },
128         default_plugins => {
129                 type => "internal",
130                 default => [qw{mdwn link inline meta htmlscrubber passwordauth
131                                 openid signinedit lockedit conditional
132                                 recentchanges parentlinks editpage}],
133                 description => "plugins to enable by default",
134                 safe => 0,
135                 rebuild => 1,
136         },
137         add_plugins => {
138                 type => "string",
139                 default => [],
140                 description => "plugins to add to the default configuration",
141                 safe => 1,
142                 rebuild => 1,
143         },
144         disable_plugins => {
145                 type => "string",
146                 default => [],
147                 description => "plugins to disable",
148                 safe => 1,
149                 rebuild => 1,
150         },
151         templatedir => {
152                 type => "string",
153                 default => "$installdir/share/ikiwiki/templates",
154                 description => "location of template files",
155                 advanced => 1,
156                 safe => 0, # path
157                 rebuild => 1,
158         },
159         templatedirs => {
160                 type => "internal",
161                 default => [],
162                 description => "additional directories containing template files",
163                 safe => 0,
164                 rebuild => 0,
165         },
166         underlaydir => {
167                 type => "string",
168                 default => "$installdir/share/ikiwiki/basewiki",
169                 description => "base wiki source location",
170                 advanced => 1,
171                 safe => 0, # path
172                 rebuild => 0,
173         },
174         underlaydirbase => {
175                 type => "internal",
176                 default => "$installdir/share/ikiwiki",
177                 description => "parent directory containing additional underlays",
178                 safe => 0,
179                 rebuild => 0,
180         },
181         wrappers => {
182                 type => "internal",
183                 default => [],
184                 description => "wrappers to generate",
185                 safe => 0,
186                 rebuild => 0,
187         },
188         underlaydirs => {
189                 type => "internal",
190                 default => [],
191                 description => "additional underlays to use",
192                 safe => 0,
193                 rebuild => 0,
194         },
195         verbose => {
196                 type => "boolean",
197                 example => 1,
198                 description => "display verbose messages?",
199                 safe => 1,
200                 rebuild => 0,
201         },
202         syslog => {
203                 type => "boolean",
204                 example => 1,
205                 description => "log to syslog?",
206                 safe => 1,
207                 rebuild => 0,
208         },
209         usedirs => {
210                 type => "boolean",
211                 default => 1,
212                 description => "create output files named page/index.html?",
213                 safe => 0, # changing requires manual transition
214                 rebuild => 1,
215         },
216         prefix_directives => {
217                 type => "boolean",
218                 default => 1,
219                 description => "use '!'-prefixed preprocessor directives?",
220                 safe => 0, # changing requires manual transition
221                 rebuild => 1,
222         },
223         indexpages => {
224                 type => "boolean",
225                 default => 0,
226                 description => "use page/index.mdwn source files",
227                 safe => 1,
228                 rebuild => 1,
229         },
230         discussion => {
231                 type => "boolean",
232                 default => 1,
233                 description => "enable Discussion pages?",
234                 safe => 1,
235                 rebuild => 1,
236         },
237         discussionpage => {
238                 type => "string",
239                 default => gettext("Discussion"),
240                 description => "name of Discussion pages",
241                 safe => 1,
242                 rebuild => 1,
243         },
244         sslcookie => {
245                 type => "boolean",
246                 default => 0,
247                 description => "only send cookies over SSL connections?",
248                 advanced => 1,
249                 safe => 1,
250                 rebuild => 0,
251         },
252         default_pageext => {
253                 type => "string",
254                 default => "mdwn",
255                 description => "extension to use for new pages",
256                 safe => 0, # not sanitized
257                 rebuild => 0,
258         },
259         htmlext => {
260                 type => "string",
261                 default => "html",
262                 description => "extension to use for html files",
263                 safe => 0, # not sanitized
264                 rebuild => 1,
265         },
266         timeformat => {
267                 type => "string",
268                 default => '%c',
269                 description => "strftime format string to display date",
270                 advanced => 1,
271                 safe => 1,
272                 rebuild => 1,
273         },
274         locale => {
275                 type => "string",
276                 default => undef,
277                 example => "en_US.UTF-8",
278                 description => "UTF-8 locale to use",
279                 advanced => 1,
280                 safe => 0,
281                 rebuild => 1,
282         },
283         userdir => {
284                 type => "string",
285                 default => "",
286                 example => "users",
287                 description => "put user pages below specified page",
288                 safe => 1,
289                 rebuild => 1,
290         },
291         numbacklinks => {
292                 type => "integer",
293                 default => 10,
294                 description => "how many backlinks to show before hiding excess (0 to show all)",
295                 safe => 1,
296                 rebuild => 1,
297         },
298         hardlink => {
299                 type => "boolean",
300                 default => 0,
301                 description => "attempt to hardlink source files? (optimisation for large files)",
302                 advanced => 1,
303                 safe => 0, # paranoia
304                 rebuild => 0,
305         },
306         umask => {
307                 type => "integer",
308                 example => "022",
309                 description => "force ikiwiki to use a particular umask",
310                 advanced => 1,
311                 safe => 0, # paranoia
312                 rebuild => 0,
313         },
314         wrappergroup => {
315                 type => "string",
316                 example => "ikiwiki",
317                 description => "group for wrappers to run in",
318                 advanced => 1,
319                 safe => 0, # paranoia
320                 rebuild => 0,
321         },
322         libdir => {
323                 type => "string",
324                 default => "",
325                 example => "$ENV{HOME}/.ikiwiki/",
326                 description => "extra library and plugin directory",
327                 advanced => 1,
328                 safe => 0, # directory
329                 rebuild => 0,
330         },
331         ENV => {
332                 type => "string", 
333                 default => {},
334                 description => "environment variables",
335                 safe => 0, # paranoia
336                 rebuild => 0,
337         },
338         include => {
339                 type => "string",
340                 default => undef,
341                 example => '^\.htaccess$',
342                 description => "regexp of normally excluded files to include",
343                 advanced => 1,
344                 safe => 0, # regexp
345                 rebuild => 1,
346         },
347         exclude => {
348                 type => "string",
349                 default => undef,
350                 example => '^(*\.private|Makefile)$',
351                 description => "regexp of files that should be skipped",
352                 advanced => 1,
353                 safe => 0, # regexp
354                 rebuild => 1,
355         },
356         wiki_file_prune_regexps => {
357                 type => "internal",
358                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
359                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
360                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
361                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
362                         qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
363                 description => "regexps of source files to ignore",
364                 safe => 0,
365                 rebuild => 1,
366         },
367         wiki_file_chars => {
368                 type => "string",
369                 description => "specifies the characters that are allowed in source filenames",
370                 default => "-[:alnum:]+/.:_",
371                 safe => 0,
372                 rebuild => 1,
373         },
374         wiki_file_regexp => {
375                 type => "internal",
376                 description => "regexp of legal source files",
377                 safe => 0,
378                 rebuild => 1,
379         },
380         web_commit_regexp => {
381                 type => "internal",
382                 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
383                 description => "regexp to parse web commits from logs",
384                 safe => 0,
385                 rebuild => 0,
386         },
387         cgi => {
388                 type => "internal",
389                 default => 0,
390                 description => "run as a cgi",
391                 safe => 0,
392                 rebuild => 0,
393         },
394         cgi_disable_uploads => {
395                 type => "internal",
396                 default => 1,
397                 description => "whether CGI should accept file uploads",
398                 safe => 0,
399                 rebuild => 0,
400         },
401         post_commit => {
402                 type => "internal",
403                 default => 0,
404                 description => "run as a post-commit hook",
405                 safe => 0,
406                 rebuild => 0,
407         },
408         rebuild => {
409                 type => "internal",
410                 default => 0,
411                 description => "running in rebuild mode",
412                 safe => 0,
413                 rebuild => 0,
414         },
415         setup => {
416                 type => "internal",
417                 default => undef,
418                 description => "running in setup mode",
419                 safe => 0,
420                 rebuild => 0,
421         },
422         clean => {
423                 type => "internal",
424                 default => 0,
425                 description => "running in clean mode",
426                 safe => 0,
427                 rebuild => 0,
428         },
429         refresh => {
430                 type => "internal",
431                 default => 0,
432                 description => "running in refresh mode",
433                 safe => 0,
434                 rebuild => 0,
435         },
436         test_receive => {
437                 type => "internal",
438                 default => 0,
439                 description => "running in receive test mode",
440                 safe => 0,
441                 rebuild => 0,
442         },
443         gettime => {
444                 type => "internal",
445                 description => "running in gettime mode",
446                 safe => 0,
447                 rebuild => 0,
448         },
449         w3mmode => {
450                 type => "internal",
451                 default => 0,
452                 description => "running in w3mmode",
453                 safe => 0,
454                 rebuild => 0,
455         },
456         wikistatedir => {
457                 type => "internal",
458                 default => undef,
459                 description => "path to the .ikiwiki directory holding ikiwiki state",
460                 safe => 0,
461                 rebuild => 0,
462         },
463         setupfile => {
464                 type => "internal",
465                 default => undef,
466                 description => "path to setup file",
467                 safe => 0,
468                 rebuild => 0,
469         },
470         setuptype => {
471                 type => "internal",
472                 default => "Standard",
473                 description => "perl class to use to dump setup file",
474                 safe => 0,
475                 rebuild => 0,
476         },
477         allow_symlinks_before_srcdir => {
478                 type => "boolean",
479                 default => 0,
480                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
481                 safe => 0,
482                 rebuild => 0,
483         },
484 }
485
486 sub defaultconfig () {
487         my %s=getsetup();
488         my @ret;
489         foreach my $key (keys %s) {
490                 push @ret, $key, $s{$key}->{default};
491         }
492         use Data::Dumper;
493         return @ret;
494 }
495
496 sub checkconfig () {
497         # locale stuff; avoid LC_ALL since it overrides everything
498         if (defined $ENV{LC_ALL}) {
499                 $ENV{LANG} = $ENV{LC_ALL};
500                 delete $ENV{LC_ALL};
501         }
502         if (defined $config{locale}) {
503                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
504                         $ENV{LANG}=$config{locale};
505                         define_gettext();
506                 }
507         }
508                 
509         if (! defined $config{wiki_file_regexp}) {
510                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
511         }
512
513         if (ref $config{ENV} eq 'HASH') {
514                 foreach my $val (keys %{$config{ENV}}) {
515                         $ENV{$val}=$config{ENV}{$val};
516                 }
517         }
518
519         if ($config{w3mmode}) {
520                 eval q{use Cwd q{abs_path}};
521                 error($@) if $@;
522                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
523                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
524                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
525                         unless $config{cgiurl} =~ m!file:///!;
526                 $config{url}="file://".$config{destdir};
527         }
528
529         if ($config{cgi} && ! length $config{url}) {
530                 error(gettext("Must specify url to wiki with --url when using --cgi"));
531         }
532         
533         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
534                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
535
536         if (defined $config{umask}) {
537                 umask(possibly_foolish_untaint($config{umask}));
538         }
539
540         run_hooks(checkconfig => sub { shift->() });
541
542         return 1;
543 }
544
545 sub listplugins () {
546         my %ret;
547
548         foreach my $dir (@INC, $config{libdir}) {
549                 next unless defined $dir && length $dir;
550                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
551                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
552                         $ret{$plugin}=1;
553                 }
554         }
555         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
556                 next unless defined $dir && length $dir;
557                 foreach my $file (glob("$dir/plugins/*")) {
558                         $ret{basename($file)}=1 if -x $file;
559                 }
560         }
561
562         return keys %ret;
563 }
564
565 sub loadplugins () {
566         if (defined $config{libdir} && length $config{libdir}) {
567                 unshift @INC, possibly_foolish_untaint($config{libdir});
568         }
569
570         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
571                 loadplugin($plugin);
572         }
573         
574         if ($config{rcs}) {
575                 if (exists $hooks{rcs}) {
576                         error(gettext("cannot use multiple rcs plugins"));
577                 }
578                 loadplugin($config{rcs});
579         }
580         if (! exists $hooks{rcs}) {
581                 loadplugin("norcs");
582         }
583
584         run_hooks(getopt => sub { shift->() });
585         if (grep /^-/, @ARGV) {
586                 print STDERR "Unknown option (or missing parameter): $_\n"
587                         foreach grep /^-/, @ARGV;
588                 usage();
589         }
590
591         return 1;
592 }
593
594 sub loadplugin ($) {
595         my $plugin=shift;
596
597         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
598
599         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
600                          "$installdir/lib/ikiwiki") {
601                 if (defined $dir && -x "$dir/plugins/$plugin") {
602                         eval { require IkiWiki::Plugin::external };
603                         if ($@) {
604                                 my $reason=$@;
605                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
606                         }
607                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
608                         $loaded_plugins{$plugin}=1;
609                         return 1;
610                 }
611         }
612
613         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
614         eval qq{use $mod};
615         if ($@) {
616                 error("Failed to load plugin $mod: $@");
617         }
618         $loaded_plugins{$plugin}=1;
619         return 1;
620 }
621
622 sub error ($;$) {
623         my $message=shift;
624         my $cleaner=shift;
625         log_message('err' => $message) if $config{syslog};
626         if (defined $cleaner) {
627                 $cleaner->();
628         }
629         die $message."\n";
630 }
631
632 sub debug ($) {
633         return unless $config{verbose};
634         return log_message(debug => @_);
635 }
636
637 my $log_open=0;
638 sub log_message ($$) {
639         my $type=shift;
640
641         if ($config{syslog}) {
642                 require Sys::Syslog;
643                 if (! $log_open) {
644                         Sys::Syslog::setlogsock('unix');
645                         Sys::Syslog::openlog('ikiwiki', '', 'user');
646                         $log_open=1;
647                 }
648                 return eval {
649                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
650                 };
651         }
652         elsif (! $config{cgi}) {
653                 return print "@_\n";
654         }
655         else {
656                 return print STDERR "@_\n";
657         }
658 }
659
660 sub possibly_foolish_untaint ($) {
661         my $tainted=shift;
662         my ($untainted)=$tainted=~/(.*)/s;
663         return $untainted;
664 }
665
666 sub basename ($) {
667         my $file=shift;
668
669         $file=~s!.*/+!!;
670         return $file;
671 }
672
673 sub dirname ($) {
674         my $file=shift;
675
676         $file=~s!/*[^/]+$!!;
677         return $file;
678 }
679
680 sub isinternal ($) {
681         my $page=shift;
682         return exists $pagesources{$page} &&
683                 $pagesources{$page} =~ /\._([^.]+)$/;
684 }
685
686 sub pagetype ($) {
687         my $file=shift;
688         
689         if ($file =~ /\.([^.]+)$/) {
690                 return $1 if exists $hooks{htmlize}{$1};
691         }
692         my $base=basename($file);
693         if (exists $hooks{htmlize}{$base} &&
694             $hooks{htmlize}{$base}{noextension}) {
695                 return $base;
696         }
697         return;
698 }
699
700 my %pagename_cache;
701
702 sub pagename ($) {
703         my $file=shift;
704
705         if (exists $pagename_cache{$file}) {
706                 return $pagename_cache{$file};
707         }
708
709         my $type=pagetype($file);
710         my $page=$file;
711         $page=~s/\Q.$type\E*$//
712                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
713                         && !$hooks{htmlize}{$type}{noextension};
714         if ($config{indexpages} && $page=~/(.*)\/index$/) {
715                 $page=$1;
716         }
717
718         $pagename_cache{$file} = $page;
719         return $page;
720 }
721
722 sub newpagefile ($$) {
723         my $page=shift;
724         my $type=shift;
725
726         if (! $config{indexpages} || $page eq 'index') {
727                 return $page.".".$type;
728         }
729         else {
730                 return $page."/index.".$type;
731         }
732 }
733
734 sub targetpage ($$;$) {
735         my $page=shift;
736         my $ext=shift;
737         my $filename=shift;
738         
739         if (defined $filename) {
740                 return $page."/".$filename.".".$ext;
741         }
742         elsif (! $config{usedirs} || $page eq 'index') {
743                 return $page.".".$ext;
744         }
745         else {
746                 return $page."/index.".$ext;
747         }
748 }
749
750 sub htmlpage ($) {
751         my $page=shift;
752         
753         return targetpage($page, $config{htmlext});
754 }
755
756 sub srcfile_stat {
757         my $file=shift;
758         my $nothrow=shift;
759
760         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
761         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
762                 return "$dir/$file", stat(_) if -e "$dir/$file";
763         }
764         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
765         return;
766 }
767
768 sub srcfile ($;$) {
769         return (srcfile_stat(@_))[0];
770 }
771
772 sub add_underlay ($) {
773         my $dir=shift;
774
775         if ($dir !~ /^\//) {
776                 $dir="$config{underlaydirbase}/$dir";
777         }
778
779         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
780                 unshift @{$config{underlaydirs}}, $dir;
781         }
782
783         return 1;
784 }
785
786 sub readfile ($;$$) {
787         my $file=shift;
788         my $binary=shift;
789         my $wantfd=shift;
790
791         if (-l $file) {
792                 error("cannot read a symlink ($file)");
793         }
794         
795         local $/=undef;
796         open (my $in, "<", $file) || error("failed to read $file: $!");
797         binmode($in) if ($binary);
798         return \*$in if $wantfd;
799         my $ret=<$in>;
800         # check for invalid utf-8, and toss it back to avoid crashes
801         if (! utf8::valid($ret)) {
802                 $ret=encode_utf8($ret);
803         }
804         close $in || error("failed to read $file: $!");
805         return $ret;
806 }
807
808 sub prep_writefile ($$) {
809         my $file=shift;
810         my $destdir=shift;
811         
812         my $test=$file;
813         while (length $test) {
814                 if (-l "$destdir/$test") {
815                         error("cannot write to a symlink ($test)");
816                 }
817                 $test=dirname($test);
818         }
819
820         my $dir=dirname("$destdir/$file");
821         if (! -d $dir) {
822                 my $d="";
823                 foreach my $s (split(m!/+!, $dir)) {
824                         $d.="$s/";
825                         if (! -d $d) {
826                                 mkdir($d) || error("failed to create directory $d: $!");
827                         }
828                 }
829         }
830
831         return 1;
832 }
833
834 sub writefile ($$$;$$) {
835         my $file=shift; # can include subdirs
836         my $destdir=shift; # directory to put file in
837         my $content=shift;
838         my $binary=shift;
839         my $writer=shift;
840         
841         prep_writefile($file, $destdir);
842         
843         my $newfile="$destdir/$file.ikiwiki-new";
844         if (-l $newfile) {
845                 error("cannot write to a symlink ($newfile)");
846         }
847         
848         my $cleanup = sub { unlink($newfile) };
849         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
850         binmode($out) if ($binary);
851         if ($writer) {
852                 $writer->(\*$out, $cleanup);
853         }
854         else {
855                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
856         }
857         close $out || error("failed saving $newfile: $!", $cleanup);
858         rename($newfile, "$destdir/$file") || 
859                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
860
861         return 1;
862 }
863
864 my %cleared;
865 sub will_render ($$;$) {
866         my $page=shift;
867         my $dest=shift;
868         my $clear=shift;
869
870         # Important security check.
871         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
872             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
873                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
874         }
875
876         if (! $clear || $cleared{$page}) {
877                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
878         }
879         else {
880                 foreach my $old (@{$renderedfiles{$page}}) {
881                         delete $destsources{$old};
882                 }
883                 $renderedfiles{$page}=[$dest];
884                 $cleared{$page}=1;
885         }
886         $destsources{$dest}=$page;
887
888         return 1;
889 }
890
891 sub bestlink ($$) {
892         my $page=shift;
893         my $link=shift;
894         
895         my $cwd=$page;
896         if ($link=~s/^\/+//) {
897                 # absolute links
898                 $cwd="";
899         }
900         $link=~s/\/$//;
901
902         do {
903                 my $l=$cwd;
904                 $l.="/" if length $l;
905                 $l.=$link;
906
907                 if (exists $pagesources{$l}) {
908                         return $l;
909                 }
910                 elsif (exists $pagecase{lc $l}) {
911                         return $pagecase{lc $l};
912                 }
913         } while $cwd=~s{/?[^/]+$}{};
914
915         if (length $config{userdir}) {
916                 my $l = "$config{userdir}/".lc($link);
917                 if (exists $pagesources{$l}) {
918                         return $l;
919                 }
920                 elsif (exists $pagecase{lc $l}) {
921                         return $pagecase{lc $l};
922                 }
923         }
924
925         #print STDERR "warning: page $page, broken link: $link\n";
926         return "";
927 }
928
929 sub isinlinableimage ($) {
930         my $file=shift;
931         
932         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
933 }
934
935 sub pagetitle ($;$) {
936         my $page=shift;
937         my $unescaped=shift;
938
939         if ($unescaped) {
940                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
941         }
942         else {
943                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
944         }
945
946         return $page;
947 }
948
949 sub titlepage ($) {
950         my $title=shift;
951         # support use w/o %config set
952         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
953         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
954         return $title;
955 }
956
957 sub linkpage ($) {
958         my $link=shift;
959         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
960         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
961         return $link;
962 }
963
964 sub cgiurl (@) {
965         my %params=@_;
966
967         my $cgiurl=$config{cgiurl};
968         if (exists $params{cgiurl}) {
969                 $cgiurl=$params{cgiurl};
970                 delete $params{cgiurl};
971         }
972         return $cgiurl."?".
973                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
974 }
975
976 sub baseurl (;$) {
977         my $page=shift;
978
979         return "$config{url}/" if ! defined $page;
980         
981         $page=htmlpage($page);
982         $page=~s/[^\/]+$//;
983         $page=~s/[^\/]+\//..\//g;
984         return $page;
985 }
986
987 sub abs2rel ($$) {
988         # Work around very innefficient behavior in File::Spec if abs2rel
989         # is passed two relative paths. It's much faster if paths are
990         # absolute! (Debian bug #376658; fixed in debian unstable now)
991         my $path="/".shift;
992         my $base="/".shift;
993
994         require File::Spec;
995         my $ret=File::Spec->abs2rel($path, $base);
996         $ret=~s/^// if defined $ret;
997         return $ret;
998 }
999
1000 sub displaytime ($;$) {
1001         # Plugins can override this function to mark up the time to
1002         # display.
1003         return '<span class="date">'.formattime(@_).'</span>';
1004 }
1005
1006 sub formattime ($;$) {
1007         # Plugins can override this function to format the time.
1008         my $time=shift;
1009         my $format=shift;
1010         if (! defined $format) {
1011                 $format=$config{timeformat};
1012         }
1013
1014         # strftime doesn't know about encodings, so make sure
1015         # its output is properly treated as utf8
1016         return decode_utf8(POSIX::strftime($format, localtime($time)));
1017 }
1018
1019 sub beautify_urlpath ($) {
1020         my $url=shift;
1021
1022         # Ensure url is not an empty link, and if necessary,
1023         # add ./ to avoid colon confusion.
1024         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1025                 $url="./$url";
1026         }
1027
1028         if ($config{usedirs}) {
1029                 $url =~ s!/index.$config{htmlext}$!/!;
1030         }
1031
1032         return $url;
1033 }
1034
1035 sub urlto ($$;$) {
1036         my $to=shift;
1037         my $from=shift;
1038         my $absolute=shift;
1039         
1040         if (! length $to) {
1041                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1042         }
1043
1044         if (! $destsources{$to}) {
1045                 $to=htmlpage($to);
1046         }
1047
1048         if ($absolute) {
1049                 return $config{url}.beautify_urlpath("/".$to);
1050         }
1051
1052         my $link = abs2rel($to, dirname(htmlpage($from)));
1053
1054         return beautify_urlpath($link);
1055 }
1056
1057 sub htmllink ($$$;@) {
1058         my $lpage=shift; # the page doing the linking
1059         my $page=shift; # the page that will contain the link (different for inline)
1060         my $link=shift;
1061         my %opts=@_;
1062
1063         $link=~s/\/$//;
1064
1065         my $bestlink;
1066         if (! $opts{forcesubpage}) {
1067                 $bestlink=bestlink($lpage, $link);
1068         }
1069         else {
1070                 $bestlink="$lpage/".lc($link);
1071         }
1072
1073         my $linktext;
1074         if (defined $opts{linktext}) {
1075                 $linktext=$opts{linktext};
1076         }
1077         else {
1078                 $linktext=pagetitle(basename($link));
1079         }
1080         
1081         return "<span class=\"selflink\">$linktext</span>"
1082                 if length $bestlink && $page eq $bestlink &&
1083                    ! defined $opts{anchor};
1084         
1085         if (! $destsources{$bestlink}) {
1086                 $bestlink=htmlpage($bestlink);
1087
1088                 if (! $destsources{$bestlink}) {
1089                         my $cgilink = "";
1090                         if (length $config{cgiurl}) {
1091                                 $cgilink = "<a href=\"".
1092                                         cgiurl(
1093                                                 do => "create",
1094                                                 page => lc($link),
1095                                                 from => $lpage
1096                                         )."\" rel=\"nofollow\">?</a>";
1097                         }
1098                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1099                 }
1100         }
1101         
1102         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1103         $bestlink=beautify_urlpath($bestlink);
1104         
1105         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1106                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1107         }
1108
1109         if (defined $opts{anchor}) {
1110                 $bestlink.="#".$opts{anchor};
1111         }
1112
1113         my @attrs;
1114         foreach my $attr (qw{rel class title}) {
1115                 if (defined $opts{$attr}) {
1116                         push @attrs, " $attr=\"$opts{$attr}\"";
1117                 }
1118         }
1119
1120         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1121 }
1122
1123 sub userpage ($) {
1124         my $user=shift;
1125         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1126 }
1127
1128 sub openiduser ($) {
1129         my $user=shift;
1130
1131         if ($user =~ m!^https?://! &&
1132             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1133                 my $display;
1134
1135                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1136                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1137                 }
1138                 else {
1139                         # backcompat with old version
1140                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1141                         $display=$oid->display;
1142                 }
1143
1144                 # Convert "user.somehost.com" to "user [somehost.com]"
1145                 # (also "user.somehost.co.uk")
1146                 if ($display !~ /\[/) {
1147                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1148                 }
1149                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1150                 # (also "https://somehost.com/user/")
1151                 if ($display !~ /\[/) {
1152                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1153                 }
1154                 $display=~s!^https?://!!; # make sure this is removed
1155                 eval q{use CGI 'escapeHTML'};
1156                 error($@) if $@;
1157                 return escapeHTML($display);
1158         }
1159         return;
1160 }
1161
1162 sub htmlize ($$$$) {
1163         my $page=shift;
1164         my $destpage=shift;
1165         my $type=shift;
1166         my $content=shift;
1167         
1168         my $oneline = $content !~ /\n/;
1169         
1170         if (exists $hooks{htmlize}{$type}) {
1171                 $content=$hooks{htmlize}{$type}{call}->(
1172                         page => $page,
1173                         content => $content,
1174                 );
1175         }
1176         else {
1177                 error("htmlization of $type not supported");
1178         }
1179
1180         run_hooks(sanitize => sub {
1181                 $content=shift->(
1182                         page => $page,
1183                         destpage => $destpage,
1184                         content => $content,
1185                 );
1186         });
1187         
1188         if ($oneline) {
1189                 # hack to get rid of enclosing junk added by markdown
1190                 # and other htmlizers/sanitizers
1191                 $content=~s/^<p>//i;
1192                 $content=~s/<\/p>\n*$//i;
1193         }
1194
1195         return $content;
1196 }
1197
1198 sub linkify ($$$) {
1199         my $page=shift;
1200         my $destpage=shift;
1201         my $content=shift;
1202
1203         run_hooks(linkify => sub {
1204                 $content=shift->(
1205                         page => $page,
1206                         destpage => $destpage,
1207                         content => $content,
1208                 );
1209         });
1210         
1211         return $content;
1212 }
1213
1214 our %preprocessing;
1215 our $preprocess_preview=0;
1216 sub preprocess ($$$;$$) {
1217         my $page=shift; # the page the data comes from
1218         my $destpage=shift; # the page the data will appear in (different for inline)
1219         my $content=shift;
1220         my $scan=shift;
1221         my $preview=shift;
1222
1223         # Using local because it needs to be set within any nested calls
1224         # of this function.
1225         local $preprocess_preview=$preview if defined $preview;
1226
1227         my $handle=sub {
1228                 my $escape=shift;
1229                 my $prefix=shift;
1230                 my $command=shift;
1231                 my $params=shift;
1232                 $params="" if ! defined $params;
1233
1234                 if (length $escape) {
1235                         return "[[$prefix$command $params]]";
1236                 }
1237                 elsif (exists $hooks{preprocess}{$command}) {
1238                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1239                         # Note: preserve order of params, some plugins may
1240                         # consider it significant.
1241                         my @params;
1242                         while ($params =~ m{
1243                                 (?:([-\w]+)=)?          # 1: named parameter key?
1244                                 (?:
1245                                         """(.*?)"""     # 2: triple-quoted value
1246                                 |
1247                                         "([^"]*?)"      # 3: single-quoted value
1248                                 |
1249                                         (\S+)           # 4: unquoted value
1250                                 )
1251                                 (?:\s+|$)               # delimiter to next param
1252                         }sgx) {
1253                                 my $key=$1;
1254                                 my $val;
1255                                 if (defined $2) {
1256                                         $val=$2;
1257                                         $val=~s/\r\n/\n/mg;
1258                                         $val=~s/^\n+//g;
1259                                         $val=~s/\n+$//g;
1260                                 }
1261                                 elsif (defined $3) {
1262                                         $val=$3;
1263                                 }
1264                                 elsif (defined $4) {
1265                                         $val=$4;
1266                                 }
1267
1268                                 if (defined $key) {
1269                                         push @params, $key, $val;
1270                                 }
1271                                 else {
1272                                         push @params, $val, '';
1273                                 }
1274                         }
1275                         if ($preprocessing{$page}++ > 3) {
1276                                 # Avoid loops of preprocessed pages preprocessing
1277                                 # other pages that preprocess them, etc.
1278                                 return "[[!$command <span class=\"error\">".
1279                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1280                                                 $page, $preprocessing{$page}).
1281                                         "</span>]]";
1282                         }
1283                         my $ret;
1284                         if (! $scan) {
1285                                 $ret=eval {
1286                                         $hooks{preprocess}{$command}{call}->(
1287                                                 @params,
1288                                                 page => $page,
1289                                                 destpage => $destpage,
1290                                                 preview => $preprocess_preview,
1291                                         );
1292                                 };
1293                                 if ($@) {
1294                                         my $error=$@;
1295                                         chomp $error;
1296                                         $ret="[[!$command <span class=\"error\">".
1297                                                 gettext("Error").": $error"."</span>]]";
1298                                 }
1299                         }
1300                         else {
1301                                 # use void context during scan pass
1302                                 eval {
1303                                         $hooks{preprocess}{$command}{call}->(
1304                                                 @params,
1305                                                 page => $page,
1306                                                 destpage => $destpage,
1307                                                 preview => $preprocess_preview,
1308                                         );
1309                                 };
1310                                 $ret="";
1311                         }
1312                         $preprocessing{$page}--;
1313                         return $ret;
1314                 }
1315                 else {
1316                         return "[[$prefix$command $params]]";
1317                 }
1318         };
1319         
1320         my $regex;
1321         if ($config{prefix_directives}) {
1322                 $regex = qr{
1323                         (\\?)           # 1: escape?
1324                         \[\[(!)         # directive open; 2: prefix
1325                         ([-\w]+)        # 3: command
1326                         (               # 4: the parameters..
1327                                 \s+     # Must have space if parameters present
1328                                 (?:
1329                                         (?:[-\w]+=)?            # named parameter key?
1330                                         (?:
1331                                                 """.*?"""       # triple-quoted value
1332                                                 |
1333                                                 "[^"]*?"        # single-quoted value
1334                                                 |
1335                                                 [^"\s\]]+       # unquoted value
1336                                         )
1337                                         \s*                     # whitespace or end
1338                                                                 # of directive
1339                                 )
1340                         *)?             # 0 or more parameters
1341                         \]\]            # directive closed
1342                 }sx;
1343         }
1344         else {
1345                 $regex = qr{
1346                         (\\?)           # 1: escape?
1347                         \[\[(!?)        # directive open; 2: optional prefix
1348                         ([-\w]+)        # 3: command
1349                         \s+
1350                         (               # 4: the parameters..
1351                                 (?:
1352                                         (?:[-\w]+=)?            # named parameter key?
1353                                         (?:
1354                                                 """.*?"""       # triple-quoted value
1355                                                 |
1356                                                 "[^"]*?"        # single-quoted value
1357                                                 |
1358                                                 [^"\s\]]+       # unquoted value
1359                                         )
1360                                         \s*                     # whitespace or end
1361                                                                 # of directive
1362                                 )
1363                         *)              # 0 or more parameters
1364                         \]\]            # directive closed
1365                 }sx;
1366         }
1367
1368         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1369         return $content;
1370 }
1371
1372 sub filter ($$$) {
1373         my $page=shift;
1374         my $destpage=shift;
1375         my $content=shift;
1376
1377         run_hooks(filter => sub {
1378                 $content=shift->(page => $page, destpage => $destpage, 
1379                         content => $content);
1380         });
1381
1382         return $content;
1383 }
1384
1385 sub indexlink () {
1386         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1387 }
1388
1389 sub check_canedit ($$$;$) {
1390         my $page=shift;
1391         my $q=shift;
1392         my $session=shift;
1393         my $nonfatal=shift;
1394         
1395         my $canedit;
1396         run_hooks(canedit => sub {
1397                 return if defined $canedit;
1398                 my $ret=shift->($page, $q, $session);
1399                 if (defined $ret) {
1400                         if ($ret eq "") {
1401                                 $canedit=1;
1402                         }
1403                         elsif (ref $ret eq 'CODE') {
1404                                 $ret->() unless $nonfatal;
1405                                 $canedit=0;
1406                         }
1407                         elsif (defined $ret) {
1408                                 error($ret) unless $nonfatal;
1409                                 $canedit=0;
1410                         }
1411                 }
1412         });
1413         return defined $canedit ? $canedit : 1;
1414 }
1415
1416 sub check_content (@) {
1417         my %params=@_;
1418         
1419         return 1 if ! exists $hooks{checkcontent}; # optimisation
1420
1421         if (exists $pagesources{$params{page}}) {
1422                 my @diff;
1423                 my %old=map { $_ => 1 }
1424                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1425                 foreach my $line (split("\n", $params{content})) {
1426                         push @diff, $line if ! exists $old{$line};
1427                 }
1428                 $params{diff}=join("\n", @diff);
1429         }
1430
1431         my $ok;
1432         run_hooks(checkcontent => sub {
1433                 return if defined $ok;
1434                 my $ret=shift->(%params);
1435                 if (defined $ret) {
1436                         if ($ret eq "") {
1437                                 $ok=1;
1438                         }
1439                         elsif (ref $ret eq 'CODE') {
1440                                 $ret->() unless $params{nonfatal};
1441                                 $ok=0;
1442                         }
1443                         elsif (defined $ret) {
1444                                 error($ret) unless $params{nonfatal};
1445                                 $ok=0;
1446                         }
1447                 }
1448
1449         });
1450         return defined $ok ? $ok : 1;
1451 }
1452
1453 my $wikilock;
1454
1455 sub lockwiki () {
1456         # Take an exclusive lock on the wiki to prevent multiple concurrent
1457         # run issues. The lock will be dropped on program exit.
1458         if (! -d $config{wikistatedir}) {
1459                 mkdir($config{wikistatedir});
1460         }
1461         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1462                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1463         if (! flock($wikilock, 2)) { # LOCK_EX
1464                 error("failed to get lock");
1465         }
1466         return 1;
1467 }
1468
1469 sub unlockwiki () {
1470         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1471         return close($wikilock) if $wikilock;
1472         return;
1473 }
1474
1475 my $commitlock;
1476
1477 sub commit_hook_enabled () {
1478         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1479                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1480         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1481                 close($commitlock) || error("failed closing commitlock: $!");
1482                 return 0;
1483         }
1484         close($commitlock) || error("failed closing commitlock: $!");
1485         return 1;
1486 }
1487
1488 sub disable_commit_hook () {
1489         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1490                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1491         if (! flock($commitlock, 2)) { # LOCK_EX
1492                 error("failed to get commit lock");
1493         }
1494         return 1;
1495 }
1496
1497 sub enable_commit_hook () {
1498         return close($commitlock) if $commitlock;
1499         return;
1500 }
1501
1502 sub loadindex () {
1503         %oldrenderedfiles=%pagectime=();
1504         if (! $config{rebuild}) {
1505                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1506                 %destsources=%renderedfiles=%pagecase=%pagestate=
1507                 %depends_simple=%typedlinks=%oldtypedlinks=();
1508         }
1509         my $in;
1510         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1511                 if (-e "$config{wikistatedir}/index") {
1512                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1513                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1514                 }
1515                 else {
1516                         $config{gettime}=1; # first build
1517                         return;
1518                 }
1519         }
1520
1521         my $index=Storable::fd_retrieve($in);
1522         if (! defined $index) {
1523                 return 0;
1524         }
1525
1526         my $pages;
1527         if (exists $index->{version} && ! ref $index->{version}) {
1528                 $pages=$index->{page};
1529                 %wikistate=%{$index->{state}};
1530         }
1531         else {
1532                 $pages=$index;
1533                 %wikistate=();
1534         }
1535
1536         foreach my $src (keys %$pages) {
1537                 my $d=$pages->{$src};
1538                 my $page=pagename($src);
1539                 $pagectime{$page}=$d->{ctime};
1540                 if (! $config{rebuild}) {
1541                         $pagesources{$page}=$src;
1542                         $pagemtime{$page}=$d->{mtime};
1543                         $renderedfiles{$page}=$d->{dest};
1544                         if (exists $d->{links} && ref $d->{links}) {
1545                                 $links{$page}=$d->{links};
1546                                 $oldlinks{$page}=[@{$d->{links}}];
1547                         }
1548                         if (ref $d->{depends_simple} eq 'ARRAY') {
1549                                 # old format
1550                                 $depends_simple{$page}={
1551                                         map { $_ => 1 } @{$d->{depends_simple}}
1552                                 };
1553                         }
1554                         elsif (exists $d->{depends_simple}) {
1555                                 $depends_simple{$page}=$d->{depends_simple};
1556                         }
1557                         if (exists $d->{dependslist}) {
1558                                 # old format
1559                                 $depends{$page}={
1560                                         map { $_ => $DEPEND_CONTENT }
1561                                                 @{$d->{dependslist}}
1562                                 };
1563                         }
1564                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1565                                 # old format
1566                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1567                         }
1568                         elsif (exists $d->{depends}) {
1569                                 $depends{$page}=$d->{depends};
1570                         }
1571                         if (exists $d->{state}) {
1572                                 $pagestate{$page}=$d->{state};
1573                         }
1574                         if (exists $d->{typedlinks}) {
1575                                 $typedlinks{$page}=$d->{typedlinks};
1576
1577                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1578                                         next unless %$links;
1579                                         $oldtypedlinks{$page}{$type} = {%$links};
1580                                 }
1581                         }
1582                 }
1583                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1584         }
1585         foreach my $page (keys %pagesources) {
1586                 $pagecase{lc $page}=$page;
1587         }
1588         foreach my $page (keys %renderedfiles) {
1589                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1590         }
1591         return close($in);
1592 }
1593
1594 sub saveindex () {
1595         run_hooks(savestate => sub { shift->() });
1596
1597         my %hookids;
1598         foreach my $type (keys %hooks) {
1599                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1600         }
1601         my @hookids=keys %hookids;
1602
1603         if (! -d $config{wikistatedir}) {
1604                 mkdir($config{wikistatedir});
1605         }
1606         my $newfile="$config{wikistatedir}/indexdb.new";
1607         my $cleanup = sub { unlink($newfile) };
1608         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1609
1610         my %index;
1611         foreach my $page (keys %pagemtime) {
1612                 next unless $pagemtime{$page};
1613                 my $src=$pagesources{$page};
1614
1615                 $index{page}{$src}={
1616                         ctime => $pagectime{$page},
1617                         mtime => $pagemtime{$page},
1618                         dest => $renderedfiles{$page},
1619                         links => $links{$page},
1620                 };
1621
1622                 if (exists $depends{$page}) {
1623                         $index{page}{$src}{depends} = $depends{$page};
1624                 }
1625
1626                 if (exists $depends_simple{$page}) {
1627                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1628                 }
1629
1630                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1631                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1632                 }
1633
1634                 if (exists $pagestate{$page}) {
1635                         foreach my $id (@hookids) {
1636                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1637                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1638                                 }
1639                         }
1640                 }
1641         }
1642
1643         $index{state}={};
1644         foreach my $id (@hookids) {
1645                 foreach my $key (keys %{$wikistate{$id}}) {
1646                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1647                 }
1648         }
1649         
1650         $index{version}="3";
1651         my $ret=Storable::nstore_fd(\%index, $out);
1652         return if ! defined $ret || ! $ret;
1653         close $out || error("failed saving to $newfile: $!", $cleanup);
1654         rename($newfile, "$config{wikistatedir}/indexdb") ||
1655                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1656         
1657         return 1;
1658 }
1659
1660 sub template_file ($) {
1661         my $template=shift;
1662
1663         foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1664                          "$installdir/share/ikiwiki/templates") {
1665                 return "$dir/$template" if -e "$dir/$template";
1666         }
1667         return;
1668 }
1669
1670 sub template_params (@) {
1671         my $filename=template_file(shift);
1672
1673         if (! defined $filename) {
1674                 return if wantarray;
1675                 return "";
1676         }
1677
1678         my @ret=(
1679                 filter => sub {
1680                         my $text_ref = shift;
1681                         ${$text_ref} = decode_utf8(${$text_ref});
1682                 },
1683                 filename => $filename,
1684                 loop_context_vars => 1,
1685                 die_on_bad_params => 0,
1686                 @_
1687         );
1688         return wantarray ? @ret : {@ret};
1689 }
1690
1691 sub template ($;@) {
1692         require HTML::Template;
1693         return HTML::Template->new(template_params(@_));
1694 }
1695
1696 sub misctemplate ($$;@) {
1697         my $title=shift;
1698         my $pagebody=shift;
1699         
1700         my $template=template("misc.tmpl");
1701         $template->param(
1702                 title => $title,
1703                 indexlink => indexlink(),
1704                 wikiname => $config{wikiname},
1705                 pagebody => $pagebody,
1706                 baseurl => baseurl(),
1707                 @_,
1708         );
1709         run_hooks(pagetemplate => sub {
1710                 shift->(page => "", destpage => "", template => $template);
1711         });
1712         return $template->output;
1713 }
1714
1715 sub hook (@) {
1716         my %param=@_;
1717         
1718         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1719                 error 'hook requires type, call, and id parameters';
1720         }
1721
1722         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1723         
1724         $hooks{$param{type}}{$param{id}}=\%param;
1725         return 1;
1726 }
1727
1728 sub run_hooks ($$) {
1729         # Calls the given sub for each hook of the given type,
1730         # passing it the hook function to call.
1731         my $type=shift;
1732         my $sub=shift;
1733
1734         if (exists $hooks{$type}) {
1735                 my (@first, @middle, @last);
1736                 foreach my $id (keys %{$hooks{$type}}) {
1737                         if ($hooks{$type}{$id}{first}) {
1738                                 push @first, $id;
1739                         }
1740                         elsif ($hooks{$type}{$id}{last}) {
1741                                 push @last, $id;
1742                         }
1743                         else {
1744                                 push @middle, $id;
1745                         }
1746                 }
1747                 foreach my $id (@first, @middle, @last) {
1748                         $sub->($hooks{$type}{$id}{call});
1749                 }
1750         }
1751
1752         return 1;
1753 }
1754
1755 sub rcs_update () {
1756         $hooks{rcs}{rcs_update}{call}->(@_);
1757 }
1758
1759 sub rcs_prepedit ($) {
1760         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1761 }
1762
1763 sub rcs_commit ($$$;$$) {
1764         $hooks{rcs}{rcs_commit}{call}->(@_);
1765 }
1766
1767 sub rcs_commit_staged ($$$) {
1768         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1769 }
1770
1771 sub rcs_add ($) {
1772         $hooks{rcs}{rcs_add}{call}->(@_);
1773 }
1774
1775 sub rcs_remove ($) {
1776         $hooks{rcs}{rcs_remove}{call}->(@_);
1777 }
1778
1779 sub rcs_rename ($$) {
1780         $hooks{rcs}{rcs_rename}{call}->(@_);
1781 }
1782
1783 sub rcs_recentchanges ($) {
1784         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1785 }
1786
1787 sub rcs_diff ($) {
1788         $hooks{rcs}{rcs_diff}{call}->(@_);
1789 }
1790
1791 sub rcs_getctime ($) {
1792         $hooks{rcs}{rcs_getctime}{call}->(@_);
1793 }
1794
1795 sub rcs_getmtime ($) {
1796         $hooks{rcs}{rcs_getmtime}{call}->(@_);
1797 }
1798
1799 sub rcs_receive () {
1800         $hooks{rcs}{rcs_receive}{call}->();
1801 }
1802
1803 sub add_depends ($$;$) {
1804         my $page=shift;
1805         my $pagespec=shift;
1806         my $deptype=shift || $DEPEND_CONTENT;
1807
1808         # Is the pagespec a simple page name?
1809         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1810             $pagespec !~ /[\s*?()!]/) {
1811                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1812                 return 1;
1813         }
1814
1815         # Add explicit dependencies for influences.
1816         my $sub=pagespec_translate($pagespec);
1817         return unless defined $sub;
1818         foreach my $p (keys %pagesources) {
1819                 my $r=$sub->($p, location => $page);
1820                 my $i=$r->influences;
1821                 foreach my $k (keys %$i) {
1822                         $depends_simple{$page}{lc $k} |= $i->{$k};
1823                 }
1824                 last if $r->influences_static;
1825         }
1826
1827         $depends{$page}{$pagespec} |= $deptype;
1828         return 1;
1829 }
1830
1831 sub deptype (@) {
1832         my $deptype=0;
1833         foreach my $type (@_) {
1834                 if ($type eq 'presence') {
1835                         $deptype |= $DEPEND_PRESENCE;
1836                 }
1837                 elsif ($type eq 'links') { 
1838                         $deptype |= $DEPEND_LINKS;
1839                 }
1840                 elsif ($type eq 'content') {
1841                         $deptype |= $DEPEND_CONTENT;
1842                 }
1843         }
1844         return $deptype;
1845 }
1846
1847 my $file_prune_regexp;
1848 sub file_pruned ($) {
1849         my $file=shift;
1850
1851         if (defined $config{include} && length $config{include}) {
1852                 return 0 if $file =~ m/$config{include}/;
1853         }
1854
1855         if (! defined $file_prune_regexp) {
1856                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1857                 $file_prune_regexp=qr/$file_prune_regexp/;
1858         }
1859         return $file =~ m/$file_prune_regexp/;
1860 }
1861
1862 sub define_gettext () {
1863         # If translation is needed, redefine the gettext function to do it.
1864         # Otherwise, it becomes a quick no-op.
1865         my $gettext_obj;
1866         my $getobj;
1867         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1868             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1869             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1870                 $getobj=sub {
1871                         $gettext_obj=eval q{
1872                                 use Locale::gettext q{textdomain};
1873                                 Locale::gettext->domain('ikiwiki')
1874                         };
1875                 };
1876         }
1877
1878         no warnings 'redefine';
1879         *gettext=sub {
1880                 $getobj->() if $getobj;
1881                 if ($gettext_obj) {
1882                         $gettext_obj->get(shift);
1883                 }
1884                 else {
1885                         return shift;
1886                 }
1887         };
1888         *ngettext=sub {
1889                 $getobj->() if $getobj;
1890                 if ($gettext_obj) {
1891                         $gettext_obj->nget(@_);
1892                 }
1893                 else {
1894                         return ($_[2] == 1 ? $_[0] : $_[1])
1895                 }
1896         };
1897 }
1898
1899 sub gettext {
1900         define_gettext();
1901         gettext(@_);
1902 }
1903
1904 sub ngettext {
1905         define_gettext();
1906         ngettext(@_);
1907 }
1908
1909 sub yesno ($) {
1910         my $val=shift;
1911
1912         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1913 }
1914
1915 sub inject {
1916         # Injects a new function into the symbol table to replace an
1917         # exported function.
1918         my %params=@_;
1919
1920         # This is deep ugly perl foo, beware.
1921         no strict;
1922         no warnings;
1923         if (! defined $params{parent}) {
1924                 $params{parent}='::';
1925                 $params{old}=\&{$params{name}};
1926                 $params{name}=~s/.*:://;
1927         }
1928         my $parent=$params{parent};
1929         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1930                 $ns = $params{parent} . $ns;
1931                 inject(%params, parent => $ns) unless $ns eq '::main::';
1932                 *{$ns . $params{name}} = $params{call}
1933                         if exists ${$ns}{$params{name}} &&
1934                            \&{${$ns}{$params{name}}} == $params{old};
1935         }
1936         use strict;
1937         use warnings;
1938 }
1939
1940 sub add_link ($$;$) {
1941         my $page=shift;
1942         my $link=shift;
1943         my $type=shift;
1944
1945         push @{$links{$page}}, $link
1946                 unless grep { $_ eq $link } @{$links{$page}};
1947
1948         if (defined $type) {
1949                 $typedlinks{$page}{$type}{$link} = 1;
1950         }
1951 }
1952
1953 sub sortspec_translate ($$) {
1954         my $spec = shift;
1955         my $reverse = shift;
1956
1957         my $code = "";
1958         my @data;
1959         while ($spec =~ m{
1960                 \s*
1961                 (-?)            # group 1: perhaps negated
1962                 \s*
1963                 (               # group 2: a word
1964                         \w+\([^\)]*\)   # command(params)
1965                         |
1966                         [^\s]+          # or anything else
1967                 )
1968                 \s*
1969         }gx) {
1970                 my $negated = $1;
1971                 my $word = $2;
1972                 my $params = undef;
1973
1974                 if ($word =~ m/^(\w+)\((.*)\)$/) {
1975                         # command with parameters
1976                         $params = $2;
1977                         $word = $1;
1978                 }
1979                 elsif ($word !~ m/^\w+$/) {
1980                         error(sprintf(gettext("invalid sort type %s"), $word));
1981                 }
1982
1983                 if (length $code) {
1984                         $code .= " || ";
1985                 }
1986
1987                 if ($negated) {
1988                         $code .= "-";
1989                 }
1990
1991                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
1992                         if (defined $params) {
1993                                 push @data, $params;
1994                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
1995                         }
1996                         else {
1997                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
1998                         }
1999                 }
2000                 else {
2001                         error(sprintf(gettext("unknown sort type %s"), $word));
2002                 }
2003         }
2004
2005         if (! length $code) {
2006                 # undefined sorting method... sort arbitrarily
2007                 return sub { 0 };
2008         }
2009
2010         if ($reverse) {
2011                 $code="-($code)";
2012         }
2013
2014         no warnings;
2015         return eval 'sub { '.$code.' }';
2016 }
2017
2018 sub pagespec_translate ($) {
2019         my $spec=shift;
2020
2021         # Convert spec to perl code.
2022         my $code="";
2023         my @data;
2024         while ($spec=~m{
2025                 \s*             # ignore whitespace
2026                 (               # 1: match a single word
2027                         \!              # !
2028                 |
2029                         \(              # (
2030                 |
2031                         \)              # )
2032                 |
2033                         \w+\([^\)]*\)   # command(params)
2034                 |
2035                         [^\s()]+        # any other text
2036                 )
2037                 \s*             # ignore whitespace
2038         }gx) {
2039                 my $word=$1;
2040                 if (lc $word eq 'and') {
2041                         $code.=' &';
2042                 }
2043                 elsif (lc $word eq 'or') {
2044                         $code.=' |';
2045                 }
2046                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2047                         $code.=' '.$word;
2048                 }
2049                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2050                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2051                                 push @data, $2;
2052                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2053                         }
2054                         else {
2055                                 push @data, qq{unknown function in pagespec "$word"};
2056                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2057                         }
2058                 }
2059                 else {
2060                         push @data, $word;
2061                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2062                 }
2063         }
2064
2065         if (! length $code) {
2066                 $code="IkiWiki::FailReason->new('empty pagespec')";
2067         }
2068
2069         no warnings;
2070         return eval 'sub { my $page=shift; '.$code.' }';
2071 }
2072
2073 sub pagespec_match ($$;@) {
2074         my $page=shift;
2075         my $spec=shift;
2076         my @params=@_;
2077
2078         # Backwards compatability with old calling convention.
2079         if (@params == 1) {
2080                 unshift @params, 'location';
2081         }
2082
2083         my $sub=pagespec_translate($spec);
2084         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2085                 if ! defined $sub;
2086         return $sub->($page, @params);
2087 }
2088
2089 sub pagespec_match_list ($$;@) {
2090         my $page=shift;
2091         my $pagespec=shift;
2092         my %params=@_;
2093
2094         # Backwards compatability with old calling convention.
2095         if (ref $page) {
2096                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2097                 $params{list}=$page;
2098                 $page=$params{location}; # ugh!
2099         }
2100
2101         my $sub=pagespec_translate($pagespec);
2102         error "syntax error in pagespec \"$pagespec\""
2103                 if ! defined $sub;
2104         my $sort=sortspec_translate($params{sort}, $params{reverse})
2105                 if defined $params{sort};
2106
2107         my @candidates;
2108         if (exists $params{list}) {
2109                 @candidates=exists $params{filter}
2110                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2111                         : @{$params{list}};
2112         }
2113         else {
2114                 @candidates=exists $params{filter}
2115                         ? grep { ! $params{filter}->($_) } keys %pagesources
2116                         : keys %pagesources;
2117         }
2118         
2119         # clear params, remainder is passed to pagespec
2120         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2121         my $num=$params{num};
2122         delete @params{qw{num deptype reverse sort filter list}};
2123         
2124         # when only the top matches will be returned, it's efficient to
2125         # sort before matching to pagespec,
2126         if (defined $num && defined $sort) {
2127                 @candidates=IkiWiki::SortSpec::sort_pages(
2128                         $sort, @candidates);
2129         }
2130         
2131         my @matches;
2132         my $firstfail;
2133         my $count=0;
2134         my $accum=IkiWiki::SuccessReason->new();
2135         foreach my $p (@candidates) {
2136                 my $r=$sub->($p, %params, location => $page);
2137                 error(sprintf(gettext("cannot match pages: %s"), $r))
2138                         if $r->isa("IkiWiki::ErrorReason");
2139                 $accum |= $r;
2140                 if ($r) {
2141                         push @matches, $p;
2142                         last if defined $num && ++$count == $num;
2143                 }
2144         }
2145
2146         # Add simple dependencies for accumulated influences.
2147         my $i=$accum->influences;
2148         foreach my $k (keys %$i) {
2149                 $depends_simple{$page}{lc $k} |= $i->{$k};
2150         }
2151
2152         # when all matches will be returned, it's efficient to
2153         # sort after matching
2154         if (! defined $num && defined $sort) {
2155                 return IkiWiki::SortSpec::sort_pages(
2156                         $sort, @matches);
2157         }
2158         else {
2159                 return @matches;
2160         }
2161 }
2162
2163 sub pagespec_valid ($) {
2164         my $spec=shift;
2165
2166         return defined pagespec_translate($spec);
2167 }
2168
2169 sub glob2re ($) {
2170         my $re=quotemeta(shift);
2171         $re=~s/\\\*/.*/g;
2172         $re=~s/\\\?/./g;
2173         return $re;
2174 }
2175
2176 package IkiWiki::FailReason;
2177
2178 use overload (
2179         '""'    => sub { $_[0][0] },
2180         '0+'    => sub { 0 },
2181         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2182         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2183         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2184         fallback => 1,
2185 );
2186
2187 our @ISA = 'IkiWiki::SuccessReason';
2188
2189 package IkiWiki::SuccessReason;
2190
2191 use overload (
2192         '""'    => sub { $_[0][0] },
2193         '0+'    => sub { 1 },
2194         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2195         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2196         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2197         fallback => 1,
2198 );
2199
2200 sub new {
2201         my $class = shift;
2202         my $value = shift;
2203         return bless [$value, {@_}], $class;
2204 }
2205
2206 sub influences {
2207         my $this=shift;
2208         $this->[1]={@_} if @_;
2209         my %i=%{$this->[1]};
2210         delete $i{""};
2211         return \%i;
2212 }
2213
2214 sub influences_static {
2215         return ! $_[0][1]->{""};
2216 }
2217
2218 sub merge_influences {
2219         my $this=shift;
2220         my $other=shift;
2221         my $anded=shift;
2222
2223         if (! $anded || (($this || %{$this->[1]}) &&
2224                          ($other || %{$other->[1]}))) {
2225                 foreach my $influence (keys %{$other->[1]}) {
2226                         $this->[1]{$influence} |= $other->[1]{$influence};
2227                 }
2228         }
2229         else {
2230                 # influence blocker
2231                 $this->[1]={};
2232         }
2233 }
2234
2235 package IkiWiki::ErrorReason;
2236
2237 our @ISA = 'IkiWiki::FailReason';
2238
2239 package IkiWiki::PageSpec;
2240
2241 sub derel ($$) {
2242         my $path=shift;
2243         my $from=shift;
2244
2245         if ($path =~ m!^\./!) {
2246                 $from=~s#/?[^/]+$## if defined $from;
2247                 $path=~s#^\./##;
2248                 $path="$from/$path" if defined $from && length $from;
2249         }
2250
2251         return $path;
2252 }
2253
2254 sub match_glob ($$;@) {
2255         my $page=shift;
2256         my $glob=shift;
2257         my %params=@_;
2258         
2259         $glob=derel($glob, $params{location});
2260
2261         my $regexp=IkiWiki::glob2re($glob);
2262         if ($page=~/^$regexp$/i) {
2263                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2264                         return IkiWiki::SuccessReason->new("$glob matches $page");
2265                 }
2266                 else {
2267                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2268                 }
2269         }
2270         else {
2271                 return IkiWiki::FailReason->new("$glob does not match $page");
2272         }
2273 }
2274
2275 sub match_internal ($$;@) {
2276         return match_glob($_[0], $_[1], @_, internal => 1)
2277 }
2278
2279 sub match_link ($$;@) {
2280         my $page=shift;
2281         my $link=lc(shift);
2282         my %params=@_;
2283
2284         $link=derel($link, $params{location});
2285         my $from=exists $params{location} ? $params{location} : '';
2286         my $linktype=$params{linktype};
2287         my $qualifier='';
2288         if (defined $linktype) {
2289                 $qualifier=" with type $linktype";
2290         }
2291
2292         my $links = $IkiWiki::links{$page};
2293         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2294                 unless $links && @{$links};
2295         my $bestlink = IkiWiki::bestlink($from, $link);
2296         foreach my $p (@{$links}) {
2297                 if (length $bestlink) {
2298                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && $bestlink eq IkiWiki::bestlink($page, $p)) {
2299                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2300                         }
2301                 }
2302                 else {
2303                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && match_glob($p, $link, %params)) {
2304                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2305                         }
2306                         my ($p_rel)=$p=~/^\/?(.*)/;
2307                         $link=~s/^\///;
2308                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p_rel}) && match_glob($p_rel, $link, %params)) {
2309                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2310                         }
2311                 }
2312         }
2313         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2314 }
2315
2316 sub match_backlink ($$;@) {
2317         my $ret=match_link($_[1], $_[0], @_);
2318         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2319         return $ret;
2320 }
2321
2322 sub match_created_before ($$;@) {
2323         my $page=shift;
2324         my $testpage=shift;
2325         my %params=@_;
2326         
2327         $testpage=derel($testpage, $params{location});
2328
2329         if (exists $IkiWiki::pagectime{$testpage}) {
2330                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2331                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2332                 }
2333                 else {
2334                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2335                 }
2336         }
2337         else {
2338                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2339         }
2340 }
2341
2342 sub match_created_after ($$;@) {
2343         my $page=shift;
2344         my $testpage=shift;
2345         my %params=@_;
2346         
2347         $testpage=derel($testpage, $params{location});
2348
2349         if (exists $IkiWiki::pagectime{$testpage}) {
2350                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2351                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2352                 }
2353                 else {
2354                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2355                 }
2356         }
2357         else {
2358                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2359         }
2360 }
2361
2362 sub match_creation_day ($$;@) {
2363         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2364                 return IkiWiki::SuccessReason->new('creation_day matched');
2365         }
2366         else {
2367                 return IkiWiki::FailReason->new('creation_day did not match');
2368         }
2369 }
2370
2371 sub match_creation_month ($$;@) {
2372         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2373                 return IkiWiki::SuccessReason->new('creation_month matched');
2374         }
2375         else {
2376                 return IkiWiki::FailReason->new('creation_month did not match');
2377         }
2378 }
2379
2380 sub match_creation_year ($$;@) {
2381         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2382                 return IkiWiki::SuccessReason->new('creation_year matched');
2383         }
2384         else {
2385                 return IkiWiki::FailReason->new('creation_year did not match');
2386         }
2387 }
2388
2389 sub match_user ($$;@) {
2390         shift;
2391         my $user=shift;
2392         my %params=@_;
2393         
2394         my $regexp=IkiWiki::glob2re($user);
2395         
2396         if (! exists $params{user}) {
2397                 return IkiWiki::ErrorReason->new("no user specified");
2398         }
2399
2400         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2401                 return IkiWiki::SuccessReason->new("user is $user");
2402         }
2403         elsif (! defined $params{user}) {
2404                 return IkiWiki::FailReason->new("not logged in");
2405         }
2406         else {
2407                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2408         }
2409 }
2410
2411 sub match_admin ($$;@) {
2412         shift;
2413         shift;
2414         my %params=@_;
2415         
2416         if (! exists $params{user}) {
2417                 return IkiWiki::ErrorReason->new("no user specified");
2418         }
2419
2420         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2421                 return IkiWiki::SuccessReason->new("user is an admin");
2422         }
2423         elsif (! defined $params{user}) {
2424                 return IkiWiki::FailReason->new("not logged in");
2425         }
2426         else {
2427                 return IkiWiki::FailReason->new("user is not an admin");
2428         }
2429 }
2430
2431 sub match_ip ($$;@) {
2432         shift;
2433         my $ip=shift;
2434         my %params=@_;
2435         
2436         if (! exists $params{ip}) {
2437                 return IkiWiki::ErrorReason->new("no IP specified");
2438         }
2439
2440         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2441                 return IkiWiki::SuccessReason->new("IP is $ip");
2442         }
2443         else {
2444                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2445         }
2446 }
2447
2448 package IkiWiki::SortSpec;
2449
2450 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2451 # are easily available in this namespace, for cmp functions to use them.
2452 sub sort_pages {
2453         my $f=shift;
2454         sort $f @_
2455 }
2456
2457 sub cmp_title {
2458         IkiWiki::pagetitle(IkiWiki::basename($a))
2459         cmp
2460         IkiWiki::pagetitle(IkiWiki::basename($b))
2461 }
2462
2463 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2464 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
2465
2466 1