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