Merge remote branch 'davrieb/autotag' 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 %del_hash};
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/\/\./,
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         if (@_) {
1850                 require File::Spec;
1851                 $file=File::Spec->canonpath($file);
1852                 my $base=File::Spec->canonpath(shift);
1853                 return if $file eq $base;
1854                 $file =~ s#^\Q$base\E/+##;
1855         }
1856
1857         if (defined $config{include} && length $config{include}) {
1858                 return 0 if $file =~ m/$config{include}/;
1859         }
1860
1861         if (! defined $file_prune_regexp) {
1862                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1863                 $file_prune_regexp=qr/$file_prune_regexp/;
1864         }
1865         return $file =~ m/$file_prune_regexp/;
1866 }
1867
1868 sub define_gettext () {
1869         # If translation is needed, redefine the gettext function to do it.
1870         # Otherwise, it becomes a quick no-op.
1871         my $gettext_obj;
1872         my $getobj;
1873         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1874             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1875             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1876                 $getobj=sub {
1877                         $gettext_obj=eval q{
1878                                 use Locale::gettext q{textdomain};
1879                                 Locale::gettext->domain('ikiwiki')
1880                         };
1881                 };
1882         }
1883
1884         no warnings 'redefine';
1885         *gettext=sub {
1886                 $getobj->() if $getobj;
1887                 if ($gettext_obj) {
1888                         $gettext_obj->get(shift);
1889                 }
1890                 else {
1891                         return shift;
1892                 }
1893         };
1894         *ngettext=sub {
1895                 $getobj->() if $getobj;
1896                 if ($gettext_obj) {
1897                         $gettext_obj->nget(@_);
1898                 }
1899                 else {
1900                         return ($_[2] == 1 ? $_[0] : $_[1])
1901                 }
1902         };
1903 }
1904
1905 sub gettext {
1906         define_gettext();
1907         gettext(@_);
1908 }
1909
1910 sub ngettext {
1911         define_gettext();
1912         ngettext(@_);
1913 }
1914
1915 sub yesno ($) {
1916         my $val=shift;
1917
1918         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1919 }
1920
1921 sub inject {
1922         # Injects a new function into the symbol table to replace an
1923         # exported function.
1924         my %params=@_;
1925
1926         # This is deep ugly perl foo, beware.
1927         no strict;
1928         no warnings;
1929         if (! defined $params{parent}) {
1930                 $params{parent}='::';
1931                 $params{old}=\&{$params{name}};
1932                 $params{name}=~s/.*:://;
1933         }
1934         my $parent=$params{parent};
1935         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1936                 $ns = $params{parent} . $ns;
1937                 inject(%params, parent => $ns) unless $ns eq '::main::';
1938                 *{$ns . $params{name}} = $params{call}
1939                         if exists ${$ns}{$params{name}} &&
1940                            \&{${$ns}{$params{name}}} == $params{old};
1941         }
1942         use strict;
1943         use warnings;
1944 }
1945
1946 sub add_link ($$;$) {
1947         my $page=shift;
1948         my $link=shift;
1949         my $type=shift;
1950
1951         push @{$links{$page}}, $link
1952                 unless grep { $_ eq $link } @{$links{$page}};
1953
1954         if (defined $type) {
1955                 $typedlinks{$page}{$type}{$link} = 1;
1956         }
1957 }
1958
1959 sub sortspec_translate ($$) {
1960         my $spec = shift;
1961         my $reverse = shift;
1962
1963         my $code = "";
1964         my @data;
1965         while ($spec =~ m{
1966                 \s*
1967                 (-?)            # group 1: perhaps negated
1968                 \s*
1969                 (               # group 2: a word
1970                         \w+\([^\)]*\)   # command(params)
1971                         |
1972                         [^\s]+          # or anything else
1973                 )
1974                 \s*
1975         }gx) {
1976                 my $negated = $1;
1977                 my $word = $2;
1978                 my $params = undef;
1979
1980                 if ($word =~ m/^(\w+)\((.*)\)$/) {
1981                         # command with parameters
1982                         $params = $2;
1983                         $word = $1;
1984                 }
1985                 elsif ($word !~ m/^\w+$/) {
1986                         error(sprintf(gettext("invalid sort type %s"), $word));
1987                 }
1988
1989                 if (length $code) {
1990                         $code .= " || ";
1991                 }
1992
1993                 if ($negated) {
1994                         $code .= "-";
1995                 }
1996
1997                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
1998                         if (defined $params) {
1999                                 push @data, $params;
2000                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2001                         }
2002                         else {
2003                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2004                         }
2005                 }
2006                 else {
2007                         error(sprintf(gettext("unknown sort type %s"), $word));
2008                 }
2009         }
2010
2011         if (! length $code) {
2012                 # undefined sorting method... sort arbitrarily
2013                 return sub { 0 };
2014         }
2015
2016         if ($reverse) {
2017                 $code="-($code)";
2018         }
2019
2020         no warnings;
2021         return eval 'sub { '.$code.' }';
2022 }
2023
2024 sub add_autofile ($$) {
2025         my $autofile=shift;
2026         my $plugin=shift;
2027
2028         if (srcfile($autofile, 1)) {
2029                 return 0;
2030         }
2031
2032         my ($file, $page) = verify_src_file("$config{srcdir}/$autofile", $config{srcdir});
2033
2034         if ((!defined $file) ||
2035         (exists $pagestate{$page}{$plugin}{autofile_deleted})) {
2036                 return 0;
2037         }
2038
2039         if (exists $del_hash{$file}) {
2040                 $pagestate{$page}{$plugin}{autofile_deleted}=1;
2041                 return 0;
2042         }
2043
2044         $autofiles{$file}=$plugin;
2045         return 1;
2046 }
2047
2048 sub pagespec_translate ($) {
2049         my $spec=shift;
2050
2051         # Convert spec to perl code.
2052         my $code="";
2053         my @data;
2054         while ($spec=~m{
2055                 \s*             # ignore whitespace
2056                 (               # 1: match a single word
2057                         \!              # !
2058                 |
2059                         \(              # (
2060                 |
2061                         \)              # )
2062                 |
2063                         \w+\([^\)]*\)   # command(params)
2064                 |
2065                         [^\s()]+        # any other text
2066                 )
2067                 \s*             # ignore whitespace
2068         }gx) {
2069                 my $word=$1;
2070                 if (lc $word eq 'and') {
2071                         $code.=' &';
2072                 }
2073                 elsif (lc $word eq 'or') {
2074                         $code.=' |';
2075                 }
2076                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2077                         $code.=' '.$word;
2078                 }
2079                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2080                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2081                                 push @data, $2;
2082                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2083                         }
2084                         else {
2085                                 push @data, qq{unknown function in pagespec "$word"};
2086                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2087                         }
2088                 }
2089                 else {
2090                         push @data, $word;
2091                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2092                 }
2093         }
2094
2095         if (! length $code) {
2096                 $code="IkiWiki::FailReason->new('empty pagespec')";
2097         }
2098
2099         no warnings;
2100         return eval 'sub { my $page=shift; '.$code.' }';
2101 }
2102
2103 sub pagespec_match ($$;@) {
2104         my $page=shift;
2105         my $spec=shift;
2106         my @params=@_;
2107
2108         # Backwards compatability with old calling convention.
2109         if (@params == 1) {
2110                 unshift @params, 'location';
2111         }
2112
2113         my $sub=pagespec_translate($spec);
2114         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2115                 if ! defined $sub;
2116         return $sub->($page, @params);
2117 }
2118
2119 sub pagespec_match_list ($$;@) {
2120         my $page=shift;
2121         my $pagespec=shift;
2122         my %params=@_;
2123
2124         # Backwards compatability with old calling convention.
2125         if (ref $page) {
2126                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2127                 $params{list}=$page;
2128                 $page=$params{location}; # ugh!
2129         }
2130
2131         my $sub=pagespec_translate($pagespec);
2132         error "syntax error in pagespec \"$pagespec\""
2133                 if ! defined $sub;
2134         my $sort=sortspec_translate($params{sort}, $params{reverse})
2135                 if defined $params{sort};
2136
2137         my @candidates;
2138         if (exists $params{list}) {
2139                 @candidates=exists $params{filter}
2140                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2141                         : @{$params{list}};
2142         }
2143         else {
2144                 @candidates=exists $params{filter}
2145                         ? grep { ! $params{filter}->($_) } keys %pagesources
2146                         : keys %pagesources;
2147         }
2148         
2149         # clear params, remainder is passed to pagespec
2150         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2151         my $num=$params{num};
2152         delete @params{qw{num deptype reverse sort filter list}};
2153         
2154         # when only the top matches will be returned, it's efficient to
2155         # sort before matching to pagespec,
2156         if (defined $num && defined $sort) {
2157                 @candidates=IkiWiki::SortSpec::sort_pages(
2158                         $sort, @candidates);
2159         }
2160         
2161         my @matches;
2162         my $firstfail;
2163         my $count=0;
2164         my $accum=IkiWiki::SuccessReason->new();
2165         foreach my $p (@candidates) {
2166                 my $r=$sub->($p, %params, location => $page);
2167                 error(sprintf(gettext("cannot match pages: %s"), $r))
2168                         if $r->isa("IkiWiki::ErrorReason");
2169                 $accum |= $r;
2170                 if ($r) {
2171                         push @matches, $p;
2172                         last if defined $num && ++$count == $num;
2173                 }
2174         }
2175
2176         # Add simple dependencies for accumulated influences.
2177         my $i=$accum->influences;
2178         foreach my $k (keys %$i) {
2179                 $depends_simple{$page}{lc $k} |= $i->{$k};
2180         }
2181
2182         # when all matches will be returned, it's efficient to
2183         # sort after matching
2184         if (! defined $num && defined $sort) {
2185                 return IkiWiki::SortSpec::sort_pages(
2186                         $sort, @matches);
2187         }
2188         else {
2189                 return @matches;
2190         }
2191 }
2192
2193 sub pagespec_valid ($) {
2194         my $spec=shift;
2195
2196         return defined pagespec_translate($spec);
2197 }
2198
2199 sub glob2re ($) {
2200         my $re=quotemeta(shift);
2201         $re=~s/\\\*/.*/g;
2202         $re=~s/\\\?/./g;
2203         return $re;
2204 }
2205
2206 package IkiWiki::FailReason;
2207
2208 use overload (
2209         '""'    => sub { $_[0][0] },
2210         '0+'    => sub { 0 },
2211         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2212         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2213         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2214         fallback => 1,
2215 );
2216
2217 our @ISA = 'IkiWiki::SuccessReason';
2218
2219 package IkiWiki::SuccessReason;
2220
2221 use overload (
2222         '""'    => sub { $_[0][0] },
2223         '0+'    => sub { 1 },
2224         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2225         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2226         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2227         fallback => 1,
2228 );
2229
2230 sub new {
2231         my $class = shift;
2232         my $value = shift;
2233         return bless [$value, {@_}], $class;
2234 }
2235
2236 sub influences {
2237         my $this=shift;
2238         $this->[1]={@_} if @_;
2239         my %i=%{$this->[1]};
2240         delete $i{""};
2241         return \%i;
2242 }
2243
2244 sub influences_static {
2245         return ! $_[0][1]->{""};
2246 }
2247
2248 sub merge_influences {
2249         my $this=shift;
2250         my $other=shift;
2251         my $anded=shift;
2252
2253         if (! $anded || (($this || %{$this->[1]}) &&
2254                         ($other || %{$other->[1]}))) {
2255                 foreach my $influence (keys %{$other->[1]}) {
2256                         $this->[1]{$influence} |= $other->[1]{$influence};
2257                 }
2258         }
2259         else {
2260                 # influence blocker
2261                 $this->[1]={};
2262         }
2263 }
2264
2265 package IkiWiki::ErrorReason;
2266
2267 our @ISA = 'IkiWiki::FailReason';
2268
2269 package IkiWiki::PageSpec;
2270
2271 sub derel ($$) {
2272         my $path=shift;
2273         my $from=shift;
2274
2275         if ($path =~ m!^\./!) {
2276                 $from=~s#/?[^/]+$## if defined $from;
2277                 $path=~s#^\./##;
2278                 $path="$from/$path" if length $from;
2279         }
2280
2281         return $path;
2282 }
2283
2284 sub match_glob ($$;@) {
2285         my $page=shift;
2286         my $glob=shift;
2287         my %params=@_;
2288         
2289         $glob=derel($glob, $params{location});
2290
2291         my $regexp=IkiWiki::glob2re($glob);
2292         if ($page=~/^$regexp$/i) {
2293                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2294                         return IkiWiki::SuccessReason->new("$glob matches $page");
2295                 }
2296                 else {
2297                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2298                 }
2299         }
2300         else {
2301                 return IkiWiki::FailReason->new("$glob does not match $page");
2302         }
2303 }
2304
2305 sub match_internal ($$;@) {
2306         return match_glob($_[0], $_[1], @_, internal => 1)
2307 }
2308
2309 sub match_link ($$;@) {
2310         my $page=shift;
2311         my $link=lc(shift);
2312         my %params=@_;
2313
2314         $link=derel($link, $params{location});
2315         my $from=exists $params{location} ? $params{location} : '';
2316         my $linktype=$params{linktype};
2317         my $qualifier='';
2318         if (defined $linktype) {
2319                 $qualifier=" with type $linktype";
2320         }
2321
2322         my $links = $IkiWiki::links{$page};
2323         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2324                 unless $links && @{$links};
2325         my $bestlink = IkiWiki::bestlink($from, $link);
2326         foreach my $p (@{$links}) {
2327                 if (length $bestlink) {
2328                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && $bestlink eq IkiWiki::bestlink($page, $p)) {
2329                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2330                         }
2331                 }
2332                 else {
2333                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && match_glob($p, $link, %params)) {
2334                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2335                         }
2336                         my ($p_rel)=$p=~/^\/?(.*)/;
2337                         $link=~s/^\///;
2338                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p_rel}) && match_glob($p_rel, $link, %params)) {
2339                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2340                         }
2341                 }
2342         }
2343         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2344 }
2345
2346 sub match_backlink ($$;@) {
2347         my $ret=match_link($_[1], $_[0], @_);
2348         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2349         return $ret;
2350 }
2351
2352 sub match_created_before ($$;@) {
2353         my $page=shift;
2354         my $testpage=shift;
2355         my %params=@_;
2356         
2357         $testpage=derel($testpage, $params{location});
2358
2359         if (exists $IkiWiki::pagectime{$testpage}) {
2360                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2361                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2362                 }
2363                 else {
2364                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2365                 }
2366         }
2367         else {
2368                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2369         }
2370 }
2371
2372 sub match_created_after ($$;@) {
2373         my $page=shift;
2374         my $testpage=shift;
2375         my %params=@_;
2376         
2377         $testpage=derel($testpage, $params{location});
2378
2379         if (exists $IkiWiki::pagectime{$testpage}) {
2380                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2381                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2382                 }
2383                 else {
2384                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2385                 }
2386         }
2387         else {
2388                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2389         }
2390 }
2391
2392 sub match_creation_day ($$;@) {
2393         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2394                 return IkiWiki::SuccessReason->new('creation_day matched');
2395         }
2396         else {
2397                 return IkiWiki::FailReason->new('creation_day did not match');
2398         }
2399 }
2400
2401 sub match_creation_month ($$;@) {
2402         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2403                 return IkiWiki::SuccessReason->new('creation_month matched');
2404         }
2405         else {
2406                 return IkiWiki::FailReason->new('creation_month did not match');
2407         }
2408 }
2409
2410 sub match_creation_year ($$;@) {
2411         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2412                 return IkiWiki::SuccessReason->new('creation_year matched');
2413         }
2414         else {
2415                 return IkiWiki::FailReason->new('creation_year did not match');
2416         }
2417 }
2418
2419 sub match_user ($$;@) {
2420         shift;
2421         my $user=shift;
2422         my %params=@_;
2423         
2424         my $regexp=IkiWiki::glob2re($user);
2425         
2426         if (! exists $params{user}) {
2427                 return IkiWiki::ErrorReason->new("no user specified");
2428         }
2429
2430         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2431                 return IkiWiki::SuccessReason->new("user is $user");
2432         }
2433         elsif (! defined $params{user}) {
2434                 return IkiWiki::FailReason->new("not logged in");
2435         }
2436         else {
2437                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2438         }
2439 }
2440
2441 sub match_admin ($$;@) {
2442         shift;
2443         shift;
2444         my %params=@_;
2445         
2446         if (! exists $params{user}) {
2447                 return IkiWiki::ErrorReason->new("no user specified");
2448         }
2449
2450         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2451                 return IkiWiki::SuccessReason->new("user is an admin");
2452         }
2453         elsif (! defined $params{user}) {
2454                 return IkiWiki::FailReason->new("not logged in");
2455         }
2456         else {
2457                 return IkiWiki::FailReason->new("user is not an admin");
2458         }
2459 }
2460
2461 sub match_ip ($$;@) {
2462         shift;
2463         my $ip=shift;
2464         my %params=@_;
2465         
2466         if (! exists $params{ip}) {
2467                 return IkiWiki::ErrorReason->new("no IP specified");
2468         }
2469
2470         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2471                 return IkiWiki::SuccessReason->new("IP is $ip");
2472         }
2473         else {
2474                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2475         }
2476 }
2477
2478 package IkiWiki::SortSpec;
2479
2480 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2481 # are easily available in this namespace, for cmp functions to use them.
2482 sub sort_pages {
2483         my $f=shift;
2484         sort $f @_
2485 }
2486
2487 sub cmp_title {
2488         IkiWiki::pagetitle(IkiWiki::basename($a))
2489         cmp
2490         IkiWiki::pagetitle(IkiWiki::basename($b))
2491 }
2492
2493 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2494 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
2495
2496 1