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