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