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