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