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