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