set html5 option as advanced for now
[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         html5 => {
238                 type => "boolean",
239                 default => 0,
240                 description => "generate HTML5? (experimental)",
241                 advanced => 1,
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                 $pagesources{$page}=$src;
1542                 if (! $config{rebuild}) {
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 $name=shift;
1663         
1664         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1665         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1666                 $tpage=$pagesources{$tpage};
1667                 $name.=".tmpl";
1668         }
1669
1670         my $template=srcfile($tpage, 1);
1671         if (defined $template) {
1672                 return $template, $tpage, 1 if wantarray;
1673                 return $template;
1674         }
1675         else {
1676                 $name=~s:/::; # avoid path traversal
1677                 foreach my $dir ($config{templatedir},
1678                                  "$installdir/share/ikiwiki/templates") {
1679                         if (-e "$dir/$name") {
1680                                 $template="$dir/$name";
1681                                 last;
1682                         }
1683                 }
1684                 if (defined $template) {        
1685                         return $template, $tpage if wantarray;
1686                         return $template;
1687                 }
1688         }
1689
1690         return;
1691 }
1692
1693 sub template_depends ($$;@) {
1694         my $name=shift;
1695         my $page=shift;
1696         
1697         my ($filename, $tpage, $untrusted)=template_file($name);
1698         if (defined $page && defined $tpage) {
1699                 add_depends($page, $tpage);
1700         }
1701
1702         return unless defined $filename;
1703
1704         my @opts=(
1705                 filter => sub {
1706                         my $text_ref = shift;
1707                         ${$text_ref} = decode_utf8(${$text_ref});
1708                 },
1709                 loop_context_vars => 1,
1710                 die_on_bad_params => 0,
1711                 filename => $filename,
1712                 @_,
1713                 ($untrusted ? (no_includes => 1) : ()),
1714         );
1715         return @opts if wantarray;
1716
1717         require HTML::Template;
1718         return HTML::Template->new(@opts);
1719 }
1720
1721 sub template ($;@) {
1722         template_depends(shift, undef, @_);
1723 }
1724
1725 sub misctemplate ($$;@) {
1726         my $title=shift;
1727         my $pagebody=shift;
1728         
1729         my $template=template("misc.tmpl");
1730         $template->param(
1731                 title => $title,
1732                 indexlink => indexlink(),
1733                 wikiname => $config{wikiname},
1734                 pagebody => $pagebody,
1735                 baseurl => baseurl(),
1736                 html5 => $config{html5},
1737                 @_,
1738         );
1739         run_hooks(pagetemplate => sub {
1740                 shift->(page => "", destpage => "", template => $template);
1741         });
1742         return $template->output;
1743 }
1744
1745 sub hook (@) {
1746         my %param=@_;
1747         
1748         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1749                 error 'hook requires type, call, and id parameters';
1750         }
1751
1752         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1753         
1754         $hooks{$param{type}}{$param{id}}=\%param;
1755         return 1;
1756 }
1757
1758 sub run_hooks ($$) {
1759         # Calls the given sub for each hook of the given type,
1760         # passing it the hook function to call.
1761         my $type=shift;
1762         my $sub=shift;
1763
1764         if (exists $hooks{$type}) {
1765                 my (@first, @middle, @last);
1766                 foreach my $id (keys %{$hooks{$type}}) {
1767                         if ($hooks{$type}{$id}{first}) {
1768                                 push @first, $id;
1769                         }
1770                         elsif ($hooks{$type}{$id}{last}) {
1771                                 push @last, $id;
1772                         }
1773                         else {
1774                                 push @middle, $id;
1775                         }
1776                 }
1777                 foreach my $id (@first, @middle, @last) {
1778                         $sub->($hooks{$type}{$id}{call});
1779                 }
1780         }
1781
1782         return 1;
1783 }
1784
1785 sub rcs_update () {
1786         $hooks{rcs}{rcs_update}{call}->(@_);
1787 }
1788
1789 sub rcs_prepedit ($) {
1790         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1791 }
1792
1793 sub rcs_commit ($$$;$$) {
1794         $hooks{rcs}{rcs_commit}{call}->(@_);
1795 }
1796
1797 sub rcs_commit_staged ($$$) {
1798         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1799 }
1800
1801 sub rcs_add ($) {
1802         $hooks{rcs}{rcs_add}{call}->(@_);
1803 }
1804
1805 sub rcs_remove ($) {
1806         $hooks{rcs}{rcs_remove}{call}->(@_);
1807 }
1808
1809 sub rcs_rename ($$) {
1810         $hooks{rcs}{rcs_rename}{call}->(@_);
1811 }
1812
1813 sub rcs_recentchanges ($) {
1814         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1815 }
1816
1817 sub rcs_diff ($) {
1818         $hooks{rcs}{rcs_diff}{call}->(@_);
1819 }
1820
1821 sub rcs_getctime ($) {
1822         $hooks{rcs}{rcs_getctime}{call}->(@_);
1823 }
1824
1825 sub rcs_getmtime ($) {
1826         $hooks{rcs}{rcs_getmtime}{call}->(@_);
1827 }
1828
1829 sub rcs_receive () {
1830         $hooks{rcs}{rcs_receive}{call}->();
1831 }
1832
1833 sub add_depends ($$;$) {
1834         my $page=shift;
1835         my $pagespec=shift;
1836         my $deptype=shift || $DEPEND_CONTENT;
1837
1838         # Is the pagespec a simple page name?
1839         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1840             $pagespec !~ /[\s*?()!]/) {
1841                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1842                 return 1;
1843         }
1844
1845         # Add explicit dependencies for influences.
1846         my $sub=pagespec_translate($pagespec);
1847         return unless defined $sub;
1848         foreach my $p (keys %pagesources) {
1849                 my $r=$sub->($p, location => $page);
1850                 my $i=$r->influences;
1851                 my $static=$r->influences_static;
1852                 foreach my $k (keys %$i) {
1853                         next unless $r || $static || $k eq $page;
1854                         $depends_simple{$page}{lc $k} |= $i->{$k};
1855                 }
1856                 last if $static;
1857         }
1858
1859         $depends{$page}{$pagespec} |= $deptype;
1860         return 1;
1861 }
1862
1863 sub deptype (@) {
1864         my $deptype=0;
1865         foreach my $type (@_) {
1866                 if ($type eq 'presence') {
1867                         $deptype |= $DEPEND_PRESENCE;
1868                 }
1869                 elsif ($type eq 'links') { 
1870                         $deptype |= $DEPEND_LINKS;
1871                 }
1872                 elsif ($type eq 'content') {
1873                         $deptype |= $DEPEND_CONTENT;
1874                 }
1875         }
1876         return $deptype;
1877 }
1878
1879 my $file_prune_regexp;
1880 sub file_pruned ($) {
1881         my $file=shift;
1882
1883         if (defined $config{include} && length $config{include}) {
1884                 return 0 if $file =~ m/$config{include}/;
1885         }
1886
1887         if (! defined $file_prune_regexp) {
1888                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1889                 $file_prune_regexp=qr/$file_prune_regexp/;
1890         }
1891         return $file =~ m/$file_prune_regexp/;
1892 }
1893
1894 sub define_gettext () {
1895         # If translation is needed, redefine the gettext function to do it.
1896         # Otherwise, it becomes a quick no-op.
1897         my $gettext_obj;
1898         my $getobj;
1899         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1900             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1901             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1902                 $getobj=sub {
1903                         $gettext_obj=eval q{
1904                                 use Locale::gettext q{textdomain};
1905                                 Locale::gettext->domain('ikiwiki')
1906                         };
1907                 };
1908         }
1909
1910         no warnings 'redefine';
1911         *gettext=sub {
1912                 $getobj->() if $getobj;
1913                 if ($gettext_obj) {
1914                         $gettext_obj->get(shift);
1915                 }
1916                 else {
1917                         return shift;
1918                 }
1919         };
1920         *ngettext=sub {
1921                 $getobj->() if $getobj;
1922                 if ($gettext_obj) {
1923                         $gettext_obj->nget(@_);
1924                 }
1925                 else {
1926                         return ($_[2] == 1 ? $_[0] : $_[1])
1927                 }
1928         };
1929 }
1930
1931 sub gettext {
1932         define_gettext();
1933         gettext(@_);
1934 }
1935
1936 sub ngettext {
1937         define_gettext();
1938         ngettext(@_);
1939 }
1940
1941 sub yesno ($) {
1942         my $val=shift;
1943
1944         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1945 }
1946
1947 sub inject {
1948         # Injects a new function into the symbol table to replace an
1949         # exported function.
1950         my %params=@_;
1951
1952         # This is deep ugly perl foo, beware.
1953         no strict;
1954         no warnings;
1955         if (! defined $params{parent}) {
1956                 $params{parent}='::';
1957                 $params{old}=\&{$params{name}};
1958                 $params{name}=~s/.*:://;
1959         }
1960         my $parent=$params{parent};
1961         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1962                 $ns = $params{parent} . $ns;
1963                 inject(%params, parent => $ns) unless $ns eq '::main::';
1964                 *{$ns . $params{name}} = $params{call}
1965                         if exists ${$ns}{$params{name}} &&
1966                            \&{${$ns}{$params{name}}} == $params{old};
1967         }
1968         use strict;
1969         use warnings;
1970 }
1971
1972 sub add_link ($$;$) {
1973         my $page=shift;
1974         my $link=shift;
1975         my $type=shift;
1976
1977         push @{$links{$page}}, $link
1978                 unless grep { $_ eq $link } @{$links{$page}};
1979
1980         if (defined $type) {
1981                 $typedlinks{$page}{$type}{$link} = 1;
1982         }
1983 }
1984
1985 sub add_autofile ($$$) {
1986         my $file=shift;
1987         my $plugin=shift;
1988         my $generator=shift;
1989         
1990         $autofiles{$file}{plugin}=$plugin;
1991         $autofiles{$file}{generator}=$generator;
1992 }
1993
1994 sub sortspec_translate ($$) {
1995         my $spec = shift;
1996         my $reverse = shift;
1997
1998         my $code = "";
1999         my @data;
2000         while ($spec =~ m{
2001                 \s*
2002                 (-?)            # group 1: perhaps negated
2003                 \s*
2004                 (               # group 2: a word
2005                         \w+\([^\)]*\)   # command(params)
2006                         |
2007                         [^\s]+          # or anything else
2008                 )
2009                 \s*
2010         }gx) {
2011                 my $negated = $1;
2012                 my $word = $2;
2013                 my $params = undef;
2014
2015                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2016                         # command with parameters
2017                         $params = $2;
2018                         $word = $1;
2019                 }
2020                 elsif ($word !~ m/^\w+$/) {
2021                         error(sprintf(gettext("invalid sort type %s"), $word));
2022                 }
2023
2024                 if (length $code) {
2025                         $code .= " || ";
2026                 }
2027
2028                 if ($negated) {
2029                         $code .= "-";
2030                 }
2031
2032                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2033                         if (defined $params) {
2034                                 push @data, $params;
2035                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2036                         }
2037                         else {
2038                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2039                         }
2040                 }
2041                 else {
2042                         error(sprintf(gettext("unknown sort type %s"), $word));
2043                 }
2044         }
2045
2046         if (! length $code) {
2047                 # undefined sorting method... sort arbitrarily
2048                 return sub { 0 };
2049         }
2050
2051         if ($reverse) {
2052                 $code="-($code)";
2053         }
2054
2055         no warnings;
2056         return eval 'sub { '.$code.' }';
2057 }
2058
2059 sub pagespec_translate ($) {
2060         my $spec=shift;
2061
2062         # Convert spec to perl code.
2063         my $code="";
2064         my @data;
2065         while ($spec=~m{
2066                 \s*             # ignore whitespace
2067                 (               # 1: match a single word
2068                         \!              # !
2069                 |
2070                         \(              # (
2071                 |
2072                         \)              # )
2073                 |
2074                         \w+\([^\)]*\)   # command(params)
2075                 |
2076                         [^\s()]+        # any other text
2077                 )
2078                 \s*             # ignore whitespace
2079         }gx) {
2080                 my $word=$1;
2081                 if (lc $word eq 'and') {
2082                         $code.=' &';
2083                 }
2084                 elsif (lc $word eq 'or') {
2085                         $code.=' |';
2086                 }
2087                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2088                         $code.=' '.$word;
2089                 }
2090                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2091                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2092                                 push @data, $2;
2093                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2094                         }
2095                         else {
2096                                 push @data, qq{unknown function in pagespec "$word"};
2097                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2098                         }
2099                 }
2100                 else {
2101                         push @data, $word;
2102                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2103                 }
2104         }
2105
2106         if (! length $code) {
2107                 $code="IkiWiki::FailReason->new('empty pagespec')";
2108         }
2109
2110         no warnings;
2111         return eval 'sub { my $page=shift; '.$code.' }';
2112 }
2113
2114 sub pagespec_match ($$;@) {
2115         my $page=shift;
2116         my $spec=shift;
2117         my @params=@_;
2118
2119         # Backwards compatability with old calling convention.
2120         if (@params == 1) {
2121                 unshift @params, 'location';
2122         }
2123
2124         my $sub=pagespec_translate($spec);
2125         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2126                 if ! defined $sub;
2127         return $sub->($page, @params);
2128 }
2129
2130 sub pagespec_match_list ($$;@) {
2131         my $page=shift;
2132         my $pagespec=shift;
2133         my %params=@_;
2134
2135         # Backwards compatability with old calling convention.
2136         if (ref $page) {
2137                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2138                 $params{list}=$page;
2139                 $page=$params{location}; # ugh!
2140         }
2141
2142         my $sub=pagespec_translate($pagespec);
2143         error "syntax error in pagespec \"$pagespec\""
2144                 if ! defined $sub;
2145         my $sort=sortspec_translate($params{sort}, $params{reverse})
2146                 if defined $params{sort};
2147
2148         my @candidates;
2149         if (exists $params{list}) {
2150                 @candidates=exists $params{filter}
2151                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2152                         : @{$params{list}};
2153         }
2154         else {
2155                 @candidates=exists $params{filter}
2156                         ? grep { ! $params{filter}->($_) } keys %pagesources
2157                         : keys %pagesources;
2158         }
2159         
2160         # clear params, remainder is passed to pagespec
2161         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2162         my $num=$params{num};
2163         delete @params{qw{num deptype reverse sort filter list}};
2164         
2165         # when only the top matches will be returned, it's efficient to
2166         # sort before matching to pagespec,
2167         if (defined $num && defined $sort) {
2168                 @candidates=IkiWiki::SortSpec::sort_pages(
2169                         $sort, @candidates);
2170         }
2171         
2172         my @matches;
2173         my $firstfail;
2174         my $count=0;
2175         my $accum=IkiWiki::SuccessReason->new();
2176         foreach my $p (@candidates) {
2177                 my $r=$sub->($p, %params, location => $page);
2178                 error(sprintf(gettext("cannot match pages: %s"), $r))
2179                         if $r->isa("IkiWiki::ErrorReason");
2180                 unless ($r || $r->influences_static) {
2181                         $r->remove_influence($p);
2182                 }
2183                 $accum |= $r;
2184                 if ($r) {
2185                         push @matches, $p;
2186                         last if defined $num && ++$count == $num;
2187                 }
2188         }
2189
2190         # Add simple dependencies for accumulated influences.
2191         my $i=$accum->influences;
2192         foreach my $k (keys %$i) {
2193                 $depends_simple{$page}{lc $k} |= $i->{$k};
2194         }
2195
2196         # when all matches will be returned, it's efficient to
2197         # sort after matching
2198         if (! defined $num && defined $sort) {
2199                 return IkiWiki::SortSpec::sort_pages(
2200                         $sort, @matches);
2201         }
2202         else {
2203                 return @matches;
2204         }
2205 }
2206
2207 sub pagespec_valid ($) {
2208         my $spec=shift;
2209
2210         return defined pagespec_translate($spec);
2211 }
2212
2213 sub glob2re ($) {
2214         my $re=quotemeta(shift);
2215         $re=~s/\\\*/.*/g;
2216         $re=~s/\\\?/./g;
2217         return $re;
2218 }
2219
2220 package IkiWiki::FailReason;
2221
2222 use overload (
2223         '""'    => sub { $_[0][0] },
2224         '0+'    => sub { 0 },
2225         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2226         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2227         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2228         fallback => 1,
2229 );
2230
2231 our @ISA = 'IkiWiki::SuccessReason';
2232
2233 package IkiWiki::SuccessReason;
2234
2235 use overload (
2236         '""'    => sub { $_[0][0] },
2237         '0+'    => sub { 1 },
2238         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2239         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2240         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2241         fallback => 1,
2242 );
2243
2244 sub new {
2245         my $class = shift;
2246         my $value = shift;
2247         return bless [$value, {@_}], $class;
2248 }
2249
2250 sub influences {
2251         my $this=shift;
2252         $this->[1]={@_} if @_;
2253         my %i=%{$this->[1]};
2254         delete $i{""};
2255         return \%i;
2256 }
2257
2258 sub influences_static {
2259         return ! $_[0][1]->{""};
2260 }
2261
2262 sub merge_influences {
2263         my $this=shift;
2264         my $other=shift;
2265         my $anded=shift;
2266
2267         if (! $anded || (($this || %{$this->[1]}) &&
2268                          ($other || %{$other->[1]}))) {
2269                 foreach my $influence (keys %{$other->[1]}) {
2270                         $this->[1]{$influence} |= $other->[1]{$influence};
2271                 }
2272         }
2273         else {
2274                 # influence blocker
2275                 $this->[1]={};
2276         }
2277 }
2278
2279 sub remove_influence {
2280         my $this=shift;
2281         my $torm=shift;
2282
2283         delete $this->[1]{$torm};
2284 }
2285
2286 package IkiWiki::ErrorReason;
2287
2288 our @ISA = 'IkiWiki::FailReason';
2289
2290 package IkiWiki::PageSpec;
2291
2292 sub derel ($$) {
2293         my $path=shift;
2294         my $from=shift;
2295
2296         if ($path =~ m!^\./!) {
2297                 $from=~s#/?[^/]+$## if defined $from;
2298                 $path=~s#^\./##;
2299                 $path="$from/$path" if defined $from && length $from;
2300         }
2301
2302         return $path;
2303 }
2304
2305 sub match_glob ($$;@) {
2306         my $page=shift;
2307         my $glob=shift;
2308         my %params=@_;
2309         
2310         $glob=derel($glob, $params{location});
2311
2312         my $regexp=IkiWiki::glob2re($glob);
2313         if ($page=~/^$regexp$/i) {
2314                 if ($params{onlypage} &&
2315                     ! defined IkiWiki::pagetype($IkiWiki::pagesources{$page})) {
2316                         return IkiWiki::FailReason->new("$page is not a page");
2317                 }
2318                 elsif (! IkiWiki::isinternal($page) || $params{internal}) {
2319                         return IkiWiki::SuccessReason->new("$glob matches $page");
2320                 }
2321                 else {
2322                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2323                 }
2324         }
2325         else {
2326                 return IkiWiki::FailReason->new("$glob does not match $page");
2327         }
2328 }
2329
2330 sub match_internal ($$;@) {
2331         return match_glob($_[0], $_[1], @_, internal => 1)
2332 }
2333
2334 sub match_page ($$;@) {
2335         return match_glob($_[0], $_[1], @_, onlypage => 1)
2336 }
2337
2338 sub match_link ($$;@) {
2339         my $page=shift;
2340         my $link=lc(shift);
2341         my %params=@_;
2342
2343         $link=derel($link, $params{location});
2344         my $from=exists $params{location} ? $params{location} : '';
2345         my $linktype=$params{linktype};
2346         my $qualifier='';
2347         if (defined $linktype) {
2348                 $qualifier=" with type $linktype";
2349         }
2350
2351         my $links = $IkiWiki::links{$page};
2352         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2353                 unless $links && @{$links};
2354         my $bestlink = IkiWiki::bestlink($from, $link);
2355         foreach my $p (@{$links}) {
2356                 if (length $bestlink) {
2357                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && $bestlink eq IkiWiki::bestlink($page, $p)) {
2358                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2359                         }
2360                 }
2361                 else {
2362                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && match_glob($p, $link, %params)) {
2363                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2364                         }
2365                         my ($p_rel)=$p=~/^\/?(.*)/;
2366                         $link=~s/^\///;
2367                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p_rel}) && match_glob($p_rel, $link, %params)) {
2368                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2369                         }
2370                 }
2371         }
2372         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2373 }
2374
2375 sub match_backlink ($$;@) {
2376         my $ret=match_link($_[1], $_[0], @_);
2377         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2378         return $ret;
2379 }
2380
2381 sub match_created_before ($$;@) {
2382         my $page=shift;
2383         my $testpage=shift;
2384         my %params=@_;
2385         
2386         $testpage=derel($testpage, $params{location});
2387
2388         if (exists $IkiWiki::pagectime{$testpage}) {
2389                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2390                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2391                 }
2392                 else {
2393                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2394                 }
2395         }
2396         else {
2397                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2398         }
2399 }
2400
2401 sub match_created_after ($$;@) {
2402         my $page=shift;
2403         my $testpage=shift;
2404         my %params=@_;
2405         
2406         $testpage=derel($testpage, $params{location});
2407
2408         if (exists $IkiWiki::pagectime{$testpage}) {
2409                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2410                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2411                 }
2412                 else {
2413                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2414                 }
2415         }
2416         else {
2417                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2418         }
2419 }
2420
2421 sub match_creation_day ($$;@) {
2422         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2423                 return IkiWiki::SuccessReason->new('creation_day matched');
2424         }
2425         else {
2426                 return IkiWiki::FailReason->new('creation_day did not match');
2427         }
2428 }
2429
2430 sub match_creation_month ($$;@) {
2431         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2432                 return IkiWiki::SuccessReason->new('creation_month matched');
2433         }
2434         else {
2435                 return IkiWiki::FailReason->new('creation_month did not match');
2436         }
2437 }
2438
2439 sub match_creation_year ($$;@) {
2440         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2441                 return IkiWiki::SuccessReason->new('creation_year matched');
2442         }
2443         else {
2444                 return IkiWiki::FailReason->new('creation_year did not match');
2445         }
2446 }
2447
2448 sub match_user ($$;@) {
2449         shift;
2450         my $user=shift;
2451         my %params=@_;
2452         
2453         my $regexp=IkiWiki::glob2re($user);
2454         
2455         if (! exists $params{user}) {
2456                 return IkiWiki::ErrorReason->new("no user specified");
2457         }
2458
2459         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2460                 return IkiWiki::SuccessReason->new("user is $user");
2461         }
2462         elsif (! defined $params{user}) {
2463                 return IkiWiki::FailReason->new("not logged in");
2464         }
2465         else {
2466                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2467         }
2468 }
2469
2470 sub match_admin ($$;@) {
2471         shift;
2472         shift;
2473         my %params=@_;
2474         
2475         if (! exists $params{user}) {
2476                 return IkiWiki::ErrorReason->new("no user specified");
2477         }
2478
2479         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2480                 return IkiWiki::SuccessReason->new("user is an admin");
2481         }
2482         elsif (! defined $params{user}) {
2483                 return IkiWiki::FailReason->new("not logged in");
2484         }
2485         else {
2486                 return IkiWiki::FailReason->new("user is not an admin");
2487         }
2488 }
2489
2490 sub match_ip ($$;@) {
2491         shift;
2492         my $ip=shift;
2493         my %params=@_;
2494         
2495         if (! exists $params{ip}) {
2496                 return IkiWiki::ErrorReason->new("no IP specified");
2497         }
2498
2499         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2500                 return IkiWiki::SuccessReason->new("IP is $ip");
2501         }
2502         else {
2503                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2504         }
2505 }
2506
2507 package IkiWiki::SortSpec;
2508
2509 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2510 # are easily available in this namespace, for cmp functions to use them.
2511 sub sort_pages {
2512         my $f=shift;
2513         sort $f @_
2514 }
2515
2516 sub cmp_title {
2517         IkiWiki::pagetitle(IkiWiki::basename($a))
2518         cmp
2519         IkiWiki::pagetitle(IkiWiki::basename($b))
2520 }
2521
2522 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2523 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
2524
2525 1