s/the the/the/
[ikiwiki] / 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 %delpagesources %destsources %depends %depends_simple
16         @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17         %oldtypedlinks %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         my $force=shift;
598
599         return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
600
601         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
602                          "$installdir/lib/ikiwiki") {
603                 if (defined $dir && -x "$dir/plugins/$plugin") {
604                         eval { require IkiWiki::Plugin::external };
605                         if ($@) {
606                                 my $reason=$@;
607                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
608                         }
609                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
610                         $loaded_plugins{$plugin}=1;
611                         return 1;
612                 }
613         }
614
615         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
616         eval qq{use $mod};
617         if ($@) {
618                 error("Failed to load plugin $mod: $@");
619         }
620         $loaded_plugins{$plugin}=1;
621         return 1;
622 }
623
624 sub error ($;$) {
625         my $message=shift;
626         my $cleaner=shift;
627         log_message('err' => $message) if $config{syslog};
628         if (defined $cleaner) {
629                 $cleaner->();
630         }
631         die $message."\n";
632 }
633
634 sub debug ($) {
635         return unless $config{verbose};
636         return log_message(debug => @_);
637 }
638
639 my $log_open=0;
640 sub log_message ($$) {
641         my $type=shift;
642
643         if ($config{syslog}) {
644                 require Sys::Syslog;
645                 if (! $log_open) {
646                         Sys::Syslog::setlogsock('unix');
647                         Sys::Syslog::openlog('ikiwiki', '', 'user');
648                         $log_open=1;
649                 }
650                 return eval {
651                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
652                 };
653         }
654         elsif (! $config{cgi}) {
655                 return print "@_\n";
656         }
657         else {
658                 return print STDERR "@_\n";
659         }
660 }
661
662 sub possibly_foolish_untaint ($) {
663         my $tainted=shift;
664         my ($untainted)=$tainted=~/(.*)/s;
665         return $untainted;
666 }
667
668 sub basename ($) {
669         my $file=shift;
670
671         $file=~s!.*/+!!;
672         return $file;
673 }
674
675 sub dirname ($) {
676         my $file=shift;
677
678         $file=~s!/*[^/]+$!!;
679         return $file;
680 }
681
682 sub isinternal ($) {
683         my $page=shift;
684         return exists $pagesources{$page} &&
685                 $pagesources{$page} =~ /\._([^.]+)$/;
686 }
687
688 sub pagetype ($) {
689         my $file=shift;
690         
691         if ($file =~ /\.([^.]+)$/) {
692                 return $1 if exists $hooks{htmlize}{$1};
693         }
694         my $base=basename($file);
695         if (exists $hooks{htmlize}{$base} &&
696             $hooks{htmlize}{$base}{noextension}) {
697                 return $base;
698         }
699         return;
700 }
701
702 my %pagename_cache;
703
704 sub pagename ($) {
705         my $file=shift;
706
707         if (exists $pagename_cache{$file}) {
708                 return $pagename_cache{$file};
709         }
710
711         my $type=pagetype($file);
712         my $page=$file;
713         $page=~s/\Q.$type\E*$//
714                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
715                         && !$hooks{htmlize}{$type}{noextension};
716         if ($config{indexpages} && $page=~/(.*)\/index$/) {
717                 $page=$1;
718         }
719
720         $pagename_cache{$file} = $page;
721         return $page;
722 }
723
724 sub newpagefile ($$) {
725         my $page=shift;
726         my $type=shift;
727
728         if (! $config{indexpages} || $page eq 'index') {
729                 return $page.".".$type;
730         }
731         else {
732                 return $page."/index.".$type;
733         }
734 }
735
736 sub targetpage ($$;$) {
737         my $page=shift;
738         my $ext=shift;
739         my $filename=shift;
740         
741         if (defined $filename) {
742                 return $page."/".$filename.".".$ext;
743         }
744         elsif (! $config{usedirs} || $page eq 'index') {
745                 return $page.".".$ext;
746         }
747         else {
748                 return $page."/index.".$ext;
749         }
750 }
751
752 sub htmlpage ($) {
753         my $page=shift;
754         
755         return targetpage($page, $config{htmlext});
756 }
757
758 sub srcfile_stat {
759         my $file=shift;
760         my $nothrow=shift;
761
762         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
763         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
764                 return "$dir/$file", stat(_) if -e "$dir/$file";
765         }
766         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
767         return;
768 }
769
770 sub srcfile ($;$) {
771         return (srcfile_stat(@_))[0];
772 }
773
774 sub add_underlay ($) {
775         my $dir=shift;
776
777         if ($dir !~ /^\//) {
778                 $dir="$config{underlaydirbase}/$dir";
779         }
780
781         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
782                 unshift @{$config{underlaydirs}}, $dir;
783         }
784
785         return 1;
786 }
787
788 sub readfile ($;$$) {
789         my $file=shift;
790         my $binary=shift;
791         my $wantfd=shift;
792
793         if (-l $file) {
794                 error("cannot read a symlink ($file)");
795         }
796         
797         local $/=undef;
798         open (my $in, "<", $file) || error("failed to read $file: $!");
799         binmode($in) if ($binary);
800         return \*$in if $wantfd;
801         my $ret=<$in>;
802         # check for invalid utf-8, and toss it back to avoid crashes
803         if (! utf8::valid($ret)) {
804                 $ret=encode_utf8($ret);
805         }
806         close $in || error("failed to read $file: $!");
807         return $ret;
808 }
809
810 sub prep_writefile ($$) {
811         my $file=shift;
812         my $destdir=shift;
813         
814         my $test=$file;
815         while (length $test) {
816                 if (-l "$destdir/$test") {
817                         error("cannot write to a symlink ($test)");
818                 }
819                 $test=dirname($test);
820         }
821
822         my $dir=dirname("$destdir/$file");
823         if (! -d $dir) {
824                 my $d="";
825                 foreach my $s (split(m!/+!, $dir)) {
826                         $d.="$s/";
827                         if (! -d $d) {
828                                 mkdir($d) || error("failed to create directory $d: $!");
829                         }
830                 }
831         }
832
833         return 1;
834 }
835
836 sub writefile ($$$;$$) {
837         my $file=shift; # can include subdirs
838         my $destdir=shift; # directory to put file in
839         my $content=shift;
840         my $binary=shift;
841         my $writer=shift;
842         
843         prep_writefile($file, $destdir);
844         
845         my $newfile="$destdir/$file.ikiwiki-new";
846         if (-l $newfile) {
847                 error("cannot write to a symlink ($newfile)");
848         }
849         
850         my $cleanup = sub { unlink($newfile) };
851         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
852         binmode($out) if ($binary);
853         if ($writer) {
854                 $writer->(\*$out, $cleanup);
855         }
856         else {
857                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
858         }
859         close $out || error("failed saving $newfile: $!", $cleanup);
860         rename($newfile, "$destdir/$file") || 
861                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
862
863         return 1;
864 }
865
866 my %cleared;
867 sub will_render ($$;$) {
868         my $page=shift;
869         my $dest=shift;
870         my $clear=shift;
871
872         # Important security check.
873         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
874             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
875                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
876         }
877
878         if (! $clear || $cleared{$page}) {
879                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
880         }
881         else {
882                 foreach my $old (@{$renderedfiles{$page}}) {
883                         delete $destsources{$old};
884                 }
885                 $renderedfiles{$page}=[$dest];
886                 $cleared{$page}=1;
887         }
888         $destsources{$dest}=$page;
889
890         return 1;
891 }
892
893 sub bestlink ($$) {
894         my $page=shift;
895         my $link=shift;
896         
897         my $cwd=$page;
898         if ($link=~s/^\/+//) {
899                 # absolute links
900                 $cwd="";
901         }
902         $link=~s/\/$//;
903
904         do {
905                 my $l=$cwd;
906                 $l.="/" if length $l;
907                 $l.=$link;
908
909                 if (exists $pagesources{$l}) {
910                         return $l;
911                 }
912                 elsif (exists $pagecase{lc $l}) {
913                         return $pagecase{lc $l};
914                 }
915         } while $cwd=~s{/?[^/]+$}{};
916
917         if (length $config{userdir}) {
918                 my $l = "$config{userdir}/".lc($link);
919                 if (exists $pagesources{$l}) {
920                         return $l;
921                 }
922                 elsif (exists $pagecase{lc $l}) {
923                         return $pagecase{lc $l};
924                 }
925         }
926
927         #print STDERR "warning: page $page, broken link: $link\n";
928         return "";
929 }
930
931 sub isinlinableimage ($) {
932         my $file=shift;
933         
934         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
935 }
936
937 sub pagetitle ($;$) {
938         my $page=shift;
939         my $unescaped=shift;
940
941         if ($unescaped) {
942                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
943         }
944         else {
945                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
946         }
947
948         return $page;
949 }
950
951 sub titlepage ($) {
952         my $title=shift;
953         # support use w/o %config set
954         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
955         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
956         return $title;
957 }
958
959 sub linkpage ($) {
960         my $link=shift;
961         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
962         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
963         return $link;
964 }
965
966 sub cgiurl (@) {
967         my %params=@_;
968
969         my $cgiurl=$config{cgiurl};
970         if (exists $params{cgiurl}) {
971                 $cgiurl=$params{cgiurl};
972                 delete $params{cgiurl};
973         }
974         return $cgiurl."?".
975                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
976 }
977
978 sub baseurl (;$) {
979         my $page=shift;
980
981         return "$config{url}/" if ! defined $page;
982         
983         $page=htmlpage($page);
984         $page=~s/[^\/]+$//;
985         $page=~s/[^\/]+\//..\//g;
986         return $page;
987 }
988
989 sub abs2rel ($$) {
990         # Work around very innefficient behavior in File::Spec if abs2rel
991         # is passed two relative paths. It's much faster if paths are
992         # absolute! (Debian bug #376658; fixed in debian unstable now)
993         my $path="/".shift;
994         my $base="/".shift;
995
996         require File::Spec;
997         my $ret=File::Spec->abs2rel($path, $base);
998         $ret=~s/^// if defined $ret;
999         return $ret;
1000 }
1001
1002 sub displaytime ($;$$) {
1003         # Plugins can override this function to mark up the time to
1004         # display.
1005         my $time=formattime($_[0], $_[1]);
1006         if ($config{html5}) {
1007                 return '<time datetime="'.date_3339($_[0]).'"'.
1008                         ($_[2] ? ' pubdate="pubdate"' : '').
1009                         '>'.$time.'</time>';
1010         }
1011         else {
1012                 return '<span class="date">'.$time.'</span>';
1013         }
1014 }
1015
1016 sub formattime ($;$) {
1017         # Plugins can override this function to format the time.
1018         my $time=shift;
1019         my $format=shift;
1020         if (! defined $format) {
1021                 $format=$config{timeformat};
1022         }
1023
1024         # strftime doesn't know about encodings, so make sure
1025         # its output is properly treated as utf8
1026         return decode_utf8(POSIX::strftime($format, localtime($time)));
1027 }
1028
1029 sub date_3339 ($) {
1030         my $time=shift;
1031
1032         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1033         POSIX::setlocale(&POSIX::LC_TIME, "C");
1034         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1035         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1036         return $ret;
1037 }
1038
1039 sub beautify_urlpath ($) {
1040         my $url=shift;
1041
1042         # Ensure url is not an empty link, and if necessary,
1043         # add ./ to avoid colon confusion.
1044         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1045                 $url="./$url";
1046         }
1047
1048         if ($config{usedirs}) {
1049                 $url =~ s!/index.$config{htmlext}$!/!;
1050         }
1051
1052         return $url;
1053 }
1054
1055 sub urlto ($$;$) {
1056         my $to=shift;
1057         my $from=shift;
1058         my $absolute=shift;
1059         
1060         if (! length $to) {
1061                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1062         }
1063
1064         if (! $destsources{$to}) {
1065                 $to=htmlpage($to);
1066         }
1067
1068         if ($absolute) {
1069                 return $config{url}.beautify_urlpath("/".$to);
1070         }
1071
1072         my $link = abs2rel($to, dirname(htmlpage($from)));
1073
1074         return beautify_urlpath($link);
1075 }
1076
1077 sub htmllink ($$$;@) {
1078         my $lpage=shift; # the page doing the linking
1079         my $page=shift; # the page that will contain the link (different for inline)
1080         my $link=shift;
1081         my %opts=@_;
1082
1083         $link=~s/\/$//;
1084
1085         my $bestlink;
1086         if (! $opts{forcesubpage}) {
1087                 $bestlink=bestlink($lpage, $link);
1088         }
1089         else {
1090                 $bestlink="$lpage/".lc($link);
1091         }
1092
1093         my $linktext;
1094         if (defined $opts{linktext}) {
1095                 $linktext=$opts{linktext};
1096         }
1097         else {
1098                 $linktext=pagetitle(basename($link));
1099         }
1100         
1101         return "<span class=\"selflink\">$linktext</span>"
1102                 if length $bestlink && $page eq $bestlink &&
1103                    ! defined $opts{anchor};
1104         
1105         if (! $destsources{$bestlink}) {
1106                 $bestlink=htmlpage($bestlink);
1107
1108                 if (! $destsources{$bestlink}) {
1109                         my $cgilink = "";
1110                         if (length $config{cgiurl}) {
1111                                 $cgilink = "<a href=\"".
1112                                         cgiurl(
1113                                                 do => "create",
1114                                                 page => lc($link),
1115                                                 from => $lpage
1116                                         )."\" rel=\"nofollow\">?</a>";
1117                         }
1118                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1119                 }
1120         }
1121         
1122         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1123         $bestlink=beautify_urlpath($bestlink);
1124         
1125         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1126                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1127         }
1128
1129         if (defined $opts{anchor}) {
1130                 $bestlink.="#".$opts{anchor};
1131         }
1132
1133         my @attrs;
1134         foreach my $attr (qw{rel class title}) {
1135                 if (defined $opts{$attr}) {
1136                         push @attrs, " $attr=\"$opts{$attr}\"";
1137                 }
1138         }
1139
1140         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1141 }
1142
1143 sub userpage ($) {
1144         my $user=shift;
1145         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1146 }
1147
1148 sub openiduser ($) {
1149         my $user=shift;
1150
1151         if ($user =~ m!^https?://! &&
1152             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1153                 my $display;
1154
1155                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1156                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1157                 }
1158                 else {
1159                         # backcompat with old version
1160                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1161                         $display=$oid->display;
1162                 }
1163
1164                 # Convert "user.somehost.com" to "user [somehost.com]"
1165                 # (also "user.somehost.co.uk")
1166                 if ($display !~ /\[/) {
1167                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1168                 }
1169                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1170                 # (also "https://somehost.com/user/")
1171                 if ($display !~ /\[/) {
1172                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1173                 }
1174                 $display=~s!^https?://!!; # make sure this is removed
1175                 eval q{use CGI 'escapeHTML'};
1176                 error($@) if $@;
1177                 return escapeHTML($display);
1178         }
1179         return;
1180 }
1181
1182 sub htmlize ($$$$) {
1183         my $page=shift;
1184         my $destpage=shift;
1185         my $type=shift;
1186         my $content=shift;
1187         
1188         my $oneline = $content !~ /\n/;
1189         
1190         if (exists $hooks{htmlize}{$type}) {
1191                 $content=$hooks{htmlize}{$type}{call}->(
1192                         page => $page,
1193                         content => $content,
1194                 );
1195         }
1196         else {
1197                 error("htmlization of $type not supported");
1198         }
1199
1200         run_hooks(sanitize => sub {
1201                 $content=shift->(
1202                         page => $page,
1203                         destpage => $destpage,
1204                         content => $content,
1205                 );
1206         });
1207         
1208         if ($oneline) {
1209                 # hack to get rid of enclosing junk added by markdown
1210                 # and other htmlizers/sanitizers
1211                 $content=~s/^<p>//i;
1212                 $content=~s/<\/p>\n*$//i;
1213         }
1214
1215         return $content;
1216 }
1217
1218 sub linkify ($$$) {
1219         my $page=shift;
1220         my $destpage=shift;
1221         my $content=shift;
1222
1223         run_hooks(linkify => sub {
1224                 $content=shift->(
1225                         page => $page,
1226                         destpage => $destpage,
1227                         content => $content,
1228                 );
1229         });
1230         
1231         return $content;
1232 }
1233
1234 our %preprocessing;
1235 our $preprocess_preview=0;
1236 sub preprocess ($$$;$$) {
1237         my $page=shift; # the page the data comes from
1238         my $destpage=shift; # the page the data will appear in (different for inline)
1239         my $content=shift;
1240         my $scan=shift;
1241         my $preview=shift;
1242
1243         # Using local because it needs to be set within any nested calls
1244         # of this function.
1245         local $preprocess_preview=$preview if defined $preview;
1246
1247         my $handle=sub {
1248                 my $escape=shift;
1249                 my $prefix=shift;
1250                 my $command=shift;
1251                 my $params=shift;
1252                 $params="" if ! defined $params;
1253
1254                 if (length $escape) {
1255                         return "[[$prefix$command $params]]";
1256                 }
1257                 elsif (exists $hooks{preprocess}{$command}) {
1258                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1259                         # Note: preserve order of params, some plugins may
1260                         # consider it significant.
1261                         my @params;
1262                         while ($params =~ m{
1263                                 (?:([-\w]+)=)?          # 1: named parameter key?
1264                                 (?:
1265                                         """(.*?)"""     # 2: triple-quoted value
1266                                 |
1267                                         "([^"]*?)"      # 3: single-quoted value
1268                                 |
1269                                         (\S+)           # 4: unquoted value
1270                                 )
1271                                 (?:\s+|$)               # delimiter to next param
1272                         }sgx) {
1273                                 my $key=$1;
1274                                 my $val;
1275                                 if (defined $2) {
1276                                         $val=$2;
1277                                         $val=~s/\r\n/\n/mg;
1278                                         $val=~s/^\n+//g;
1279                                         $val=~s/\n+$//g;
1280                                 }
1281                                 elsif (defined $3) {
1282                                         $val=$3;
1283                                 }
1284                                 elsif (defined $4) {
1285                                         $val=$4;
1286                                 }
1287
1288                                 if (defined $key) {
1289                                         push @params, $key, $val;
1290                                 }
1291                                 else {
1292                                         push @params, $val, '';
1293                                 }
1294                         }
1295                         if ($preprocessing{$page}++ > 3) {
1296                                 # Avoid loops of preprocessed pages preprocessing
1297                                 # other pages that preprocess them, etc.
1298                                 return "[[!$command <span class=\"error\">".
1299                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1300                                                 $page, $preprocessing{$page}).
1301                                         "</span>]]";
1302                         }
1303                         my $ret;
1304                         if (! $scan) {
1305                                 $ret=eval {
1306                                         $hooks{preprocess}{$command}{call}->(
1307                                                 @params,
1308                                                 page => $page,
1309                                                 destpage => $destpage,
1310                                                 preview => $preprocess_preview,
1311                                         );
1312                                 };
1313                                 if ($@) {
1314                                         my $error=$@;
1315                                         chomp $error;
1316                                         $ret="[[!$command <span class=\"error\">".
1317                                                 gettext("Error").": $error"."</span>]]";
1318                                 }
1319                         }
1320                         else {
1321                                 # use void context during scan pass
1322                                 eval {
1323                                         $hooks{preprocess}{$command}{call}->(
1324                                                 @params,
1325                                                 page => $page,
1326                                                 destpage => $destpage,
1327                                                 preview => $preprocess_preview,
1328                                         );
1329                                 };
1330                                 $ret="";
1331                         }
1332                         $preprocessing{$page}--;
1333                         return $ret;
1334                 }
1335                 else {
1336                         return "[[$prefix$command $params]]";
1337                 }
1338         };
1339         
1340         my $regex;
1341         if ($config{prefix_directives}) {
1342                 $regex = qr{
1343                         (\\?)           # 1: escape?
1344                         \[\[(!)         # directive open; 2: prefix
1345                         ([-\w]+)        # 3: command
1346                         (               # 4: the parameters..
1347                                 \s+     # Must have space if parameters present
1348                                 (?:
1349                                         (?:[-\w]+=)?            # named parameter key?
1350                                         (?:
1351                                                 """.*?"""       # triple-quoted value
1352                                                 |
1353                                                 "[^"]*?"        # single-quoted value
1354                                                 |
1355                                                 [^"\s\]]+       # unquoted value
1356                                         )
1357                                         \s*                     # whitespace or end
1358                                                                 # of directive
1359                                 )
1360                         *)?             # 0 or more parameters
1361                         \]\]            # directive closed
1362                 }sx;
1363         }
1364         else {
1365                 $regex = qr{
1366                         (\\?)           # 1: escape?
1367                         \[\[(!?)        # directive open; 2: optional prefix
1368                         ([-\w]+)        # 3: command
1369                         \s+
1370                         (               # 4: the parameters..
1371                                 (?:
1372                                         (?:[-\w]+=)?            # named parameter key?
1373                                         (?:
1374                                                 """.*?"""       # triple-quoted value
1375                                                 |
1376                                                 "[^"]*?"        # single-quoted value
1377                                                 |
1378                                                 [^"\s\]]+       # unquoted value
1379                                         )
1380                                         \s*                     # whitespace or end
1381                                                                 # of directive
1382                                 )
1383                         *)              # 0 or more parameters
1384                         \]\]            # directive closed
1385                 }sx;
1386         }
1387
1388         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1389         return $content;
1390 }
1391
1392 sub filter ($$$) {
1393         my $page=shift;
1394         my $destpage=shift;
1395         my $content=shift;
1396
1397         run_hooks(filter => sub {
1398                 $content=shift->(page => $page, destpage => $destpage, 
1399                         content => $content);
1400         });
1401
1402         return $content;
1403 }
1404
1405 sub check_canedit ($$$;$) {
1406         my $page=shift;
1407         my $q=shift;
1408         my $session=shift;
1409         my $nonfatal=shift;
1410         
1411         my $canedit;
1412         run_hooks(canedit => sub {
1413                 return if defined $canedit;
1414                 my $ret=shift->($page, $q, $session);
1415                 if (defined $ret) {
1416                         if ($ret eq "") {
1417                                 $canedit=1;
1418                         }
1419                         elsif (ref $ret eq 'CODE') {
1420                                 $ret->() unless $nonfatal;
1421                                 $canedit=0;
1422                         }
1423                         elsif (defined $ret) {
1424                                 error($ret) unless $nonfatal;
1425                                 $canedit=0;
1426                         }
1427                 }
1428         });
1429         return defined $canedit ? $canedit : 1;
1430 }
1431
1432 sub check_content (@) {
1433         my %params=@_;
1434         
1435         return 1 if ! exists $hooks{checkcontent}; # optimisation
1436
1437         if (exists $pagesources{$params{page}}) {
1438                 my @diff;
1439                 my %old=map { $_ => 1 }
1440                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1441                 foreach my $line (split("\n", $params{content})) {
1442                         push @diff, $line if ! exists $old{$line};
1443                 }
1444                 $params{diff}=join("\n", @diff);
1445         }
1446
1447         my $ok;
1448         run_hooks(checkcontent => sub {
1449                 return if defined $ok;
1450                 my $ret=shift->(%params);
1451                 if (defined $ret) {
1452                         if ($ret eq "") {
1453                                 $ok=1;
1454                         }
1455                         elsif (ref $ret eq 'CODE') {
1456                                 $ret->() unless $params{nonfatal};
1457                                 $ok=0;
1458                         }
1459                         elsif (defined $ret) {
1460                                 error($ret) unless $params{nonfatal};
1461                                 $ok=0;
1462                         }
1463                 }
1464
1465         });
1466         return defined $ok ? $ok : 1;
1467 }
1468
1469 my $wikilock;
1470
1471 sub lockwiki () {
1472         # Take an exclusive lock on the wiki to prevent multiple concurrent
1473         # run issues. The lock will be dropped on program exit.
1474         if (! -d $config{wikistatedir}) {
1475                 mkdir($config{wikistatedir});
1476         }
1477         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1478                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1479         if (! flock($wikilock, 2)) { # LOCK_EX
1480                 error("failed to get lock");
1481         }
1482         return 1;
1483 }
1484
1485 sub unlockwiki () {
1486         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1487         return close($wikilock) if $wikilock;
1488         return;
1489 }
1490
1491 my $commitlock;
1492
1493 sub commit_hook_enabled () {
1494         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1495                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1496         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1497                 close($commitlock) || error("failed closing commitlock: $!");
1498                 return 0;
1499         }
1500         close($commitlock) || error("failed closing commitlock: $!");
1501         return 1;
1502 }
1503
1504 sub disable_commit_hook () {
1505         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1506                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1507         if (! flock($commitlock, 2)) { # LOCK_EX
1508                 error("failed to get commit lock");
1509         }
1510         return 1;
1511 }
1512
1513 sub enable_commit_hook () {
1514         return close($commitlock) if $commitlock;
1515         return;
1516 }
1517
1518 sub loadindex () {
1519         %oldrenderedfiles=%pagectime=();
1520         if (! $config{rebuild}) {
1521                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1522                 %destsources=%renderedfiles=%pagecase=%pagestate=
1523                 %depends_simple=%typedlinks=%oldtypedlinks=();
1524         }
1525         my $in;
1526         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1527                 if (-e "$config{wikistatedir}/index") {
1528                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1529                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1530                 }
1531                 else {
1532                         $config{gettime}=1; # first build
1533                         return;
1534                 }
1535         }
1536
1537         my $index=Storable::fd_retrieve($in);
1538         if (! defined $index) {
1539                 return 0;
1540         }
1541
1542         my $pages;
1543         if (exists $index->{version} && ! ref $index->{version}) {
1544                 $pages=$index->{page};
1545                 %wikistate=%{$index->{state}};
1546         }
1547         else {
1548                 $pages=$index;
1549                 %wikistate=();
1550         }
1551
1552         foreach my $src (keys %$pages) {
1553                 my $d=$pages->{$src};
1554                 my $page=pagename($src);
1555                 $pagectime{$page}=$d->{ctime};
1556                 $pagesources{$page}=$src;
1557                 if (! $config{rebuild}) {
1558                         $pagemtime{$page}=$d->{mtime};
1559                         $renderedfiles{$page}=$d->{dest};
1560                         if (exists $d->{links} && ref $d->{links}) {
1561                                 $links{$page}=$d->{links};
1562                                 $oldlinks{$page}=[@{$d->{links}}];
1563                         }
1564                         if (ref $d->{depends_simple} eq 'ARRAY') {
1565                                 # old format
1566                                 $depends_simple{$page}={
1567                                         map { $_ => 1 } @{$d->{depends_simple}}
1568                                 };
1569                         }
1570                         elsif (exists $d->{depends_simple}) {
1571                                 $depends_simple{$page}=$d->{depends_simple};
1572                         }
1573                         if (exists $d->{dependslist}) {
1574                                 # old format
1575                                 $depends{$page}={
1576                                         map { $_ => $DEPEND_CONTENT }
1577                                                 @{$d->{dependslist}}
1578                                 };
1579                         }
1580                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1581                                 # old format
1582                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1583                         }
1584                         elsif (exists $d->{depends}) {
1585                                 $depends{$page}=$d->{depends};
1586                         }
1587                         if (exists $d->{state}) {
1588                                 $pagestate{$page}=$d->{state};
1589                         }
1590                         if (exists $d->{typedlinks}) {
1591                                 $typedlinks{$page}=$d->{typedlinks};
1592
1593                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1594                                         next unless %$links;
1595                                         $oldtypedlinks{$page}{$type} = {%$links};
1596                                 }
1597                         }
1598                 }
1599                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1600         }
1601         foreach my $page (keys %pagesources) {
1602                 $pagecase{lc $page}=$page;
1603         }
1604         foreach my $page (keys %renderedfiles) {
1605                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1606         }
1607         return close($in);
1608 }
1609
1610 sub saveindex () {
1611         run_hooks(savestate => sub { shift->() });
1612
1613         my %hookids;
1614         foreach my $type (keys %hooks) {
1615                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1616         }
1617         my @hookids=keys %hookids;
1618
1619         if (! -d $config{wikistatedir}) {
1620                 mkdir($config{wikistatedir});
1621         }
1622         my $newfile="$config{wikistatedir}/indexdb.new";
1623         my $cleanup = sub { unlink($newfile) };
1624         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1625
1626         my %index;
1627         foreach my $page (keys %pagemtime) {
1628                 next unless $pagemtime{$page};
1629                 my $src=$pagesources{$page};
1630
1631                 $index{page}{$src}={
1632                         ctime => $pagectime{$page},
1633                         mtime => $pagemtime{$page},
1634                         dest => $renderedfiles{$page},
1635                         links => $links{$page},
1636                 };
1637
1638                 if (exists $depends{$page}) {
1639                         $index{page}{$src}{depends} = $depends{$page};
1640                 }
1641
1642                 if (exists $depends_simple{$page}) {
1643                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1644                 }
1645
1646                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1647                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1648                 }
1649
1650                 if (exists $pagestate{$page}) {
1651                         foreach my $id (@hookids) {
1652                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1653                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1654                                 }
1655                         }
1656                 }
1657         }
1658
1659         $index{state}={};
1660         foreach my $id (@hookids) {
1661                 foreach my $key (keys %{$wikistate{$id}}) {
1662                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1663                 }
1664         }
1665         
1666         $index{version}="3";
1667         my $ret=Storable::nstore_fd(\%index, $out);
1668         return if ! defined $ret || ! $ret;
1669         close $out || error("failed saving to $newfile: $!", $cleanup);
1670         rename($newfile, "$config{wikistatedir}/indexdb") ||
1671                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1672         
1673         return 1;
1674 }
1675
1676 sub template_file ($) {
1677         my $name=shift;
1678         
1679         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1680         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1681                 $tpage=$pagesources{$tpage};
1682                 $name.=".tmpl";
1683         }
1684
1685         my $template=srcfile($tpage, 1);
1686         if (defined $template) {
1687                 return $template, $tpage, 1 if wantarray;
1688                 return $template;
1689         }
1690         else {
1691                 $name=~s:/::; # avoid path traversal
1692                 foreach my $dir ($config{templatedir},
1693                                  "$installdir/share/ikiwiki/templates") {
1694                         if (-e "$dir/$name") {
1695                                 $template="$dir/$name";
1696                                 last;
1697                         }
1698                 }
1699                 if (defined $template) {        
1700                         return $template, $tpage if wantarray;
1701                         return $template;
1702                 }
1703         }
1704
1705         return;
1706 }
1707
1708 sub template_depends ($$;@) {
1709         my $name=shift;
1710         my $page=shift;
1711         
1712         my ($filename, $tpage, $untrusted)=template_file($name);
1713         if (defined $page && defined $tpage) {
1714                 add_depends($page, $tpage);
1715         }
1716
1717         return unless defined $filename;
1718
1719         my @opts=(
1720                 filter => sub {
1721                         my $text_ref = shift;
1722                         ${$text_ref} = decode_utf8(${$text_ref});
1723                 },
1724                 loop_context_vars => 1,
1725                 die_on_bad_params => 0,
1726                 filename => $filename,
1727                 @_,
1728                 ($untrusted ? (no_includes => 1) : ()),
1729         );
1730         return @opts if wantarray;
1731
1732         require HTML::Template;
1733         return HTML::Template->new(@opts);
1734 }
1735
1736 sub template ($;@) {
1737         template_depends(shift, undef, @_);
1738 }
1739
1740 sub misctemplate ($$;@) {
1741         my $title=shift;
1742         my $content=shift;
1743         my %params=@_;
1744         
1745         my $template=template("page.tmpl");
1746
1747         my $page="";
1748         if (exists $params{page}) {
1749                 $page=delete $params{page};
1750         }
1751         run_hooks(pagetemplate => sub {
1752                 shift->(
1753                         page => $page,
1754                         destpage => $page,
1755                         template => $template,
1756                 );
1757         });
1758         templateactions($template, "");
1759
1760         $template->param(
1761                 dynamic => 1,
1762                 title => $title,
1763                 wikiname => $config{wikiname},
1764                 content => $content,
1765                 baseurl => baseurl(),
1766                 html5 => $config{html5},
1767                 %params,
1768         );
1769         
1770         return $template->output;
1771 }
1772
1773 sub templateactions ($$) {
1774         my $template=shift;
1775         my $page=shift;
1776
1777         my $have_actions=0;
1778         my @actions;
1779         run_hooks(pageactions => sub {
1780                 push @actions, map { { action => $_ } } 
1781                         grep { defined } shift->(page => $page);
1782         });
1783         $template->param(actions => \@actions);
1784
1785         if ($config{cgiurl} && exists $hooks{auth}) {
1786                 $template->param(prefsurl => cgiurl(do => "prefs"));
1787                 $have_actions=1;
1788         }
1789
1790         if ($have_actions || @actions) {
1791                 $template->param(have_actions => 1);
1792         }
1793 }
1794
1795 sub hook (@) {
1796         my %param=@_;
1797         
1798         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1799                 error 'hook requires type, call, and id parameters';
1800         }
1801
1802         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1803         
1804         $hooks{$param{type}}{$param{id}}=\%param;
1805         return 1;
1806 }
1807
1808 sub run_hooks ($$) {
1809         # Calls the given sub for each hook of the given type,
1810         # passing it the hook function to call.
1811         my $type=shift;
1812         my $sub=shift;
1813
1814         if (exists $hooks{$type}) {
1815                 my (@first, @middle, @last);
1816                 foreach my $id (keys %{$hooks{$type}}) {
1817                         if ($hooks{$type}{$id}{first}) {
1818                                 push @first, $id;
1819                         }
1820                         elsif ($hooks{$type}{$id}{last}) {
1821                                 push @last, $id;
1822                         }
1823                         else {
1824                                 push @middle, $id;
1825                         }
1826                 }
1827                 foreach my $id (@first, @middle, @last) {
1828                         $sub->($hooks{$type}{$id}{call});
1829                 }
1830         }
1831
1832         return 1;
1833 }
1834
1835 sub rcs_update () {
1836         $hooks{rcs}{rcs_update}{call}->(@_);
1837 }
1838
1839 sub rcs_prepedit ($) {
1840         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1841 }
1842
1843 sub rcs_commit (@) {
1844         $hooks{rcs}{rcs_commit}{call}->(@_);
1845 }
1846
1847 sub rcs_commit_staged (@) {
1848         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1849 }
1850
1851 sub rcs_add ($) {
1852         $hooks{rcs}{rcs_add}{call}->(@_);
1853 }
1854
1855 sub rcs_remove ($) {
1856         $hooks{rcs}{rcs_remove}{call}->(@_);
1857 }
1858
1859 sub rcs_rename ($$) {
1860         $hooks{rcs}{rcs_rename}{call}->(@_);
1861 }
1862
1863 sub rcs_recentchanges ($) {
1864         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1865 }
1866
1867 sub rcs_diff ($) {
1868         $hooks{rcs}{rcs_diff}{call}->(@_);
1869 }
1870
1871 sub rcs_getctime ($) {
1872         $hooks{rcs}{rcs_getctime}{call}->(@_);
1873 }
1874
1875 sub rcs_getmtime ($) {
1876         $hooks{rcs}{rcs_getmtime}{call}->(@_);
1877 }
1878
1879 sub rcs_receive () {
1880         $hooks{rcs}{rcs_receive}{call}->();
1881 }
1882
1883 sub add_depends ($$;$) {
1884         my $page=shift;
1885         my $pagespec=shift;
1886         my $deptype=shift || $DEPEND_CONTENT;
1887
1888         # Is the pagespec a simple page name?
1889         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1890             $pagespec !~ /[\s*?()!]/) {
1891                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1892                 return 1;
1893         }
1894
1895         # Add explicit dependencies for influences.
1896         my $sub=pagespec_translate($pagespec);
1897         return unless defined $sub;
1898         foreach my $p (keys %pagesources) {
1899                 my $r=$sub->($p, location => $page);
1900                 my $i=$r->influences;
1901                 my $static=$r->influences_static;
1902                 foreach my $k (keys %$i) {
1903                         next unless $r || $static || $k eq $page;
1904                         $depends_simple{$page}{lc $k} |= $i->{$k};
1905                 }
1906                 last if $static;
1907         }
1908
1909         $depends{$page}{$pagespec} |= $deptype;
1910         return 1;
1911 }
1912
1913 sub deptype (@) {
1914         my $deptype=0;
1915         foreach my $type (@_) {
1916                 if ($type eq 'presence') {
1917                         $deptype |= $DEPEND_PRESENCE;
1918                 }
1919                 elsif ($type eq 'links') { 
1920                         $deptype |= $DEPEND_LINKS;
1921                 }
1922                 elsif ($type eq 'content') {
1923                         $deptype |= $DEPEND_CONTENT;
1924                 }
1925         }
1926         return $deptype;
1927 }
1928
1929 my $file_prune_regexp;
1930 sub file_pruned ($) {
1931         my $file=shift;
1932
1933         if (defined $config{include} && length $config{include}) {
1934                 return 0 if $file =~ m/$config{include}/;
1935         }
1936
1937         if (! defined $file_prune_regexp) {
1938                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1939                 $file_prune_regexp=qr/$file_prune_regexp/;
1940         }
1941         return $file =~ m/$file_prune_regexp/;
1942 }
1943
1944 sub define_gettext () {
1945         # If translation is needed, redefine the gettext function to do it.
1946         # Otherwise, it becomes a quick no-op.
1947         my $gettext_obj;
1948         my $getobj;
1949         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1950             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1951             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1952                 $getobj=sub {
1953                         $gettext_obj=eval q{
1954                                 use Locale::gettext q{textdomain};
1955                                 Locale::gettext->domain('ikiwiki')
1956                         };
1957                 };
1958         }
1959
1960         no warnings 'redefine';
1961         *gettext=sub {
1962                 $getobj->() if $getobj;
1963                 if ($gettext_obj) {
1964                         $gettext_obj->get(shift);
1965                 }
1966                 else {
1967                         return shift;
1968                 }
1969         };
1970         *ngettext=sub {
1971                 $getobj->() if $getobj;
1972                 if ($gettext_obj) {
1973                         $gettext_obj->nget(@_);
1974                 }
1975                 else {
1976                         return ($_[2] == 1 ? $_[0] : $_[1])
1977                 }
1978         };
1979 }
1980
1981 sub gettext {
1982         define_gettext();
1983         gettext(@_);
1984 }
1985
1986 sub ngettext {
1987         define_gettext();
1988         ngettext(@_);
1989 }
1990
1991 sub yesno ($) {
1992         my $val=shift;
1993
1994         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1995 }
1996
1997 sub inject {
1998         # Injects a new function into the symbol table to replace an
1999         # exported function.
2000         my %params=@_;
2001
2002         # This is deep ugly perl foo, beware.
2003         no strict;
2004         no warnings;
2005         if (! defined $params{parent}) {
2006                 $params{parent}='::';
2007                 $params{old}=\&{$params{name}};
2008                 $params{name}=~s/.*:://;
2009         }
2010         my $parent=$params{parent};
2011         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2012                 $ns = $params{parent} . $ns;
2013                 inject(%params, parent => $ns) unless $ns eq '::main::';
2014                 *{$ns . $params{name}} = $params{call}
2015                         if exists ${$ns}{$params{name}} &&
2016                            \&{${$ns}{$params{name}}} == $params{old};
2017         }
2018         use strict;
2019         use warnings;
2020 }
2021
2022 sub add_link ($$;$) {
2023         my $page=shift;
2024         my $link=shift;
2025         my $type=shift;
2026
2027         push @{$links{$page}}, $link
2028                 unless grep { $_ eq $link } @{$links{$page}};
2029
2030         if (defined $type) {
2031                 $typedlinks{$page}{$type}{$link} = 1;
2032         }
2033 }
2034
2035 sub add_autofile ($$$) {
2036         my $file=shift;
2037         my $plugin=shift;
2038         my $generator=shift;
2039         
2040         $autofiles{$file}{plugin}=$plugin;
2041         $autofiles{$file}{generator}=$generator;
2042 }
2043
2044 sub sortspec_translate ($$) {
2045         my $spec = shift;
2046         my $reverse = shift;
2047
2048         my $code = "";
2049         my @data;
2050         while ($spec =~ m{
2051                 \s*
2052                 (-?)            # group 1: perhaps negated
2053                 \s*
2054                 (               # group 2: a word
2055                         \w+\([^\)]*\)   # command(params)
2056                         |
2057                         [^\s]+          # or anything else
2058                 )
2059                 \s*
2060         }gx) {
2061                 my $negated = $1;
2062                 my $word = $2;
2063                 my $params = undef;
2064
2065                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2066                         # command with parameters
2067                         $params = $2;
2068                         $word = $1;
2069                 }
2070                 elsif ($word !~ m/^\w+$/) {
2071                         error(sprintf(gettext("invalid sort type %s"), $word));
2072                 }
2073
2074                 if (length $code) {
2075                         $code .= " || ";
2076                 }
2077
2078                 if ($negated) {
2079                         $code .= "-";
2080                 }
2081
2082                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2083                         if (defined $params) {
2084                                 push @data, $params;
2085                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2086                         }
2087                         else {
2088                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2089                         }
2090                 }
2091                 else {
2092                         error(sprintf(gettext("unknown sort type %s"), $word));
2093                 }
2094         }
2095
2096         if (! length $code) {
2097                 # undefined sorting method... sort arbitrarily
2098                 return sub { 0 };
2099         }
2100
2101         if ($reverse) {
2102                 $code="-($code)";
2103         }
2104
2105         no warnings;
2106         return eval 'sub { '.$code.' }';
2107 }
2108
2109 sub pagespec_translate ($) {
2110         my $spec=shift;
2111
2112         # Convert spec to perl code.
2113         my $code="";
2114         my @data;
2115         while ($spec=~m{
2116                 \s*             # ignore whitespace
2117                 (               # 1: match a single word
2118                         \!              # !
2119                 |
2120                         \(              # (
2121                 |
2122                         \)              # )
2123                 |
2124                         \w+\([^\)]*\)   # command(params)
2125                 |
2126                         [^\s()]+        # any other text
2127                 )
2128                 \s*             # ignore whitespace
2129         }gx) {
2130                 my $word=$1;
2131                 if (lc $word eq 'and') {
2132                         $code.=' &';
2133                 }
2134                 elsif (lc $word eq 'or') {
2135                         $code.=' |';
2136                 }
2137                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2138                         $code.=' '.$word;
2139                 }
2140                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2141                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2142                                 push @data, $2;
2143                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2144                         }
2145                         else {
2146                                 push @data, qq{unknown function in pagespec "$word"};
2147                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2148                         }
2149                 }
2150                 else {
2151                         push @data, $word;
2152                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2153                 }
2154         }
2155
2156         if (! length $code) {
2157                 $code="IkiWiki::FailReason->new('empty pagespec')";
2158         }
2159
2160         no warnings;
2161         return eval 'sub { my $page=shift; '.$code.' }';
2162 }
2163
2164 sub pagespec_match ($$;@) {
2165         my $page=shift;
2166         my $spec=shift;
2167         my @params=@_;
2168
2169         # Backwards compatability with old calling convention.
2170         if (@params == 1) {
2171                 unshift @params, 'location';
2172         }
2173
2174         my $sub=pagespec_translate($spec);
2175         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2176                 if ! defined $sub;
2177         return $sub->($page, @params);
2178 }
2179
2180 sub pagespec_match_list ($$;@) {
2181         my $page=shift;
2182         my $pagespec=shift;
2183         my %params=@_;
2184
2185         # Backwards compatability with old calling convention.
2186         if (ref $page) {
2187                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2188                 $params{list}=$page;
2189                 $page=$params{location}; # ugh!
2190         }
2191
2192         my $sub=pagespec_translate($pagespec);
2193         error "syntax error in pagespec \"$pagespec\""
2194                 if ! defined $sub;
2195         my $sort=sortspec_translate($params{sort}, $params{reverse})
2196                 if defined $params{sort};
2197
2198         my @candidates;
2199         if (exists $params{list}) {
2200                 @candidates=exists $params{filter}
2201                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2202                         : @{$params{list}};
2203         }
2204         else {
2205                 @candidates=exists $params{filter}
2206                         ? grep { ! $params{filter}->($_) } keys %pagesources
2207                         : keys %pagesources;
2208         }
2209         
2210         # clear params, remainder is passed to pagespec
2211         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2212         my $num=$params{num};
2213         delete @params{qw{num deptype reverse sort filter list}};
2214         
2215         # when only the top matches will be returned, it's efficient to
2216         # sort before matching to pagespec,
2217         if (defined $num && defined $sort) {
2218                 @candidates=IkiWiki::SortSpec::sort_pages(
2219                         $sort, @candidates);
2220         }
2221         
2222         my @matches;
2223         my $firstfail;
2224         my $count=0;
2225         my $accum=IkiWiki::SuccessReason->new();
2226         foreach my $p (@candidates) {
2227                 my $r=$sub->($p, %params, location => $page);
2228                 error(sprintf(gettext("cannot match pages: %s"), $r))
2229                         if $r->isa("IkiWiki::ErrorReason");
2230                 unless ($r || $r->influences_static) {
2231                         $r->remove_influence($p);
2232                 }
2233                 $accum |= $r;
2234                 if ($r) {
2235                         push @matches, $p;
2236                         last if defined $num && ++$count == $num;
2237                 }
2238         }
2239
2240         # Add simple dependencies for accumulated influences.
2241         my $i=$accum->influences;
2242         foreach my $k (keys %$i) {
2243                 $depends_simple{$page}{lc $k} |= $i->{$k};
2244         }
2245
2246         # when all matches will be returned, it's efficient to
2247         # sort after matching
2248         if (! defined $num && defined $sort) {
2249                 return IkiWiki::SortSpec::sort_pages(
2250                         $sort, @matches);
2251         }
2252         else {
2253                 return @matches;
2254         }
2255 }
2256
2257 sub pagespec_valid ($) {
2258         my $spec=shift;
2259
2260         return defined pagespec_translate($spec);
2261 }
2262
2263 sub glob2re ($) {
2264         my $re=quotemeta(shift);
2265         $re=~s/\\\*/.*/g;
2266         $re=~s/\\\?/./g;
2267         return $re;
2268 }
2269
2270 package IkiWiki::FailReason;
2271
2272 use overload (
2273         '""'    => sub { $_[0][0] },
2274         '0+'    => sub { 0 },
2275         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2276         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2277         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2278         fallback => 1,
2279 );
2280
2281 our @ISA = 'IkiWiki::SuccessReason';
2282
2283 package IkiWiki::SuccessReason;
2284
2285 use overload (
2286         '""'    => sub { $_[0][0] },
2287         '0+'    => sub { 1 },
2288         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2289         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2290         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2291         fallback => 1,
2292 );
2293
2294 sub new {
2295         my $class = shift;
2296         my $value = shift;
2297         return bless [$value, {@_}], $class;
2298 }
2299
2300 sub influences {
2301         my $this=shift;
2302         $this->[1]={@_} if @_;
2303         my %i=%{$this->[1]};
2304         delete $i{""};
2305         return \%i;
2306 }
2307
2308 sub influences_static {
2309         return ! $_[0][1]->{""};
2310 }
2311
2312 sub merge_influences {
2313         my $this=shift;
2314         my $other=shift;
2315         my $anded=shift;
2316
2317         if (! $anded || (($this || %{$this->[1]}) &&
2318                          ($other || %{$other->[1]}))) {
2319                 foreach my $influence (keys %{$other->[1]}) {
2320                         $this->[1]{$influence} |= $other->[1]{$influence};
2321                 }
2322         }
2323         else {
2324                 # influence blocker
2325                 $this->[1]={};
2326         }
2327 }
2328
2329 sub remove_influence {
2330         my $this=shift;
2331         my $torm=shift;
2332
2333         delete $this->[1]{$torm};
2334 }
2335
2336 package IkiWiki::ErrorReason;
2337
2338 our @ISA = 'IkiWiki::FailReason';
2339
2340 package IkiWiki::PageSpec;
2341
2342 sub derel ($$) {
2343         my $path=shift;
2344         my $from=shift;
2345
2346         if ($path =~ m!^\./!) {
2347                 $from=~s#/?[^/]+$## if defined $from;
2348                 $path=~s#^\./##;
2349                 $path="$from/$path" if defined $from && length $from;
2350         }
2351
2352         return $path;
2353 }
2354
2355 sub match_glob ($$;@) {
2356         my $page=shift;
2357         my $glob=shift;
2358         my %params=@_;
2359         
2360         $glob=derel($glob, $params{location});
2361
2362         my $regexp=IkiWiki::glob2re($glob);
2363         if ($page=~/^$regexp$/i) {
2364                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2365                         return IkiWiki::SuccessReason->new("$glob matches $page");
2366                 }
2367                 else {
2368                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2369                 }
2370         }
2371         else {
2372                 return IkiWiki::FailReason->new("$glob does not match $page");
2373         }
2374 }
2375
2376 sub match_internal ($$;@) {
2377         return match_glob(shift, shift, @_, internal => 1)
2378 }
2379
2380 sub match_page ($$;@) {
2381         my $page=shift;
2382         my $match=match_glob($page, shift, @_);
2383         if ($match && ! (exists $IkiWiki::pagesources{$page}
2384             && defined IkiWiki::pagetype($IkiWiki::pagesources{$page}))) {
2385                 return IkiWiki::FailReason->new("$page is not a page");
2386         }
2387         else {
2388                 return $match;
2389         }
2390 }
2391
2392 sub match_link ($$;@) {
2393         my $page=shift;
2394         my $link=lc(shift);
2395         my %params=@_;
2396
2397         $link=derel($link, $params{location});
2398         my $from=exists $params{location} ? $params{location} : '';
2399         my $linktype=$params{linktype};
2400         my $qualifier='';
2401         if (defined $linktype) {
2402                 $qualifier=" with type $linktype";
2403         }
2404
2405         my $links = $IkiWiki::links{$page};
2406         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2407                 unless $links && @{$links};
2408         my $bestlink = IkiWiki::bestlink($from, $link);
2409         foreach my $p (@{$links}) {
2410                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2411
2412                 if (length $bestlink) {
2413                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2414                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2415                         }
2416                 }
2417                 else {
2418                         if (match_glob($p, $link, %params)) {
2419                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2420                         }
2421                         my ($p_rel)=$p=~/^\/?(.*)/;
2422                         $link=~s/^\///;
2423                         if (match_glob($p_rel, $link, %params)) {
2424                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2425                         }
2426                 }
2427         }
2428         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2429 }
2430
2431 sub match_backlink ($$;@) {
2432         my $ret=match_link($_[1], $_[0], @_);
2433         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2434         return $ret;
2435 }
2436
2437 sub match_created_before ($$;@) {
2438         my $page=shift;
2439         my $testpage=shift;
2440         my %params=@_;
2441         
2442         $testpage=derel($testpage, $params{location});
2443
2444         if (exists $IkiWiki::pagectime{$testpage}) {
2445                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2446                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2447                 }
2448                 else {
2449                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2450                 }
2451         }
2452         else {
2453                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2454         }
2455 }
2456
2457 sub match_created_after ($$;@) {
2458         my $page=shift;
2459         my $testpage=shift;
2460         my %params=@_;
2461         
2462         $testpage=derel($testpage, $params{location});
2463
2464         if (exists $IkiWiki::pagectime{$testpage}) {
2465                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2466                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2467                 }
2468                 else {
2469                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2470                 }
2471         }
2472         else {
2473                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2474         }
2475 }
2476
2477 sub match_creation_day ($$;@) {
2478         if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2479                 return IkiWiki::SuccessReason->new('creation_day matched');
2480         }
2481         else {
2482                 return IkiWiki::FailReason->new('creation_day did not match');
2483         }
2484 }
2485
2486 sub match_creation_month ($$;@) {
2487         if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2488                 return IkiWiki::SuccessReason->new('creation_month matched');
2489         }
2490         else {
2491                 return IkiWiki::FailReason->new('creation_month did not match');
2492         }
2493 }
2494
2495 sub match_creation_year ($$;@) {
2496         if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2497                 return IkiWiki::SuccessReason->new('creation_year matched');
2498         }
2499         else {
2500                 return IkiWiki::FailReason->new('creation_year did not match');
2501         }
2502 }
2503
2504 sub match_user ($$;@) {
2505         shift;
2506         my $user=shift;
2507         my %params=@_;
2508         
2509         my $regexp=IkiWiki::glob2re($user);
2510         
2511         if (! exists $params{user}) {
2512                 return IkiWiki::ErrorReason->new("no user specified");
2513         }
2514
2515         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2516                 return IkiWiki::SuccessReason->new("user is $user");
2517         }
2518         elsif (! defined $params{user}) {
2519                 return IkiWiki::FailReason->new("not logged in");
2520         }
2521         else {
2522                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2523         }
2524 }
2525
2526 sub match_admin ($$;@) {
2527         shift;
2528         shift;
2529         my %params=@_;
2530         
2531         if (! exists $params{user}) {
2532                 return IkiWiki::ErrorReason->new("no user specified");
2533         }
2534
2535         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2536                 return IkiWiki::SuccessReason->new("user is an admin");
2537         }
2538         elsif (! defined $params{user}) {
2539                 return IkiWiki::FailReason->new("not logged in");
2540         }
2541         else {
2542                 return IkiWiki::FailReason->new("user is not an admin");
2543         }
2544 }
2545
2546 sub match_ip ($$;@) {
2547         shift;
2548         my $ip=shift;
2549         my %params=@_;
2550         
2551         if (! exists $params{ip}) {
2552                 return IkiWiki::ErrorReason->new("no IP specified");
2553         }
2554
2555         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2556                 return IkiWiki::SuccessReason->new("IP is $ip");
2557         }
2558         else {
2559                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2560         }
2561 }
2562
2563 package IkiWiki::SortSpec;
2564
2565 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2566 # are easily available in this namespace, for cmp functions to use them.
2567 sub sort_pages {
2568         my $f=shift;
2569         sort $f @_
2570 }
2571
2572 sub cmp_title {
2573         IkiWiki::pagetitle(IkiWiki::basename($a))
2574         cmp
2575         IkiWiki::pagetitle(IkiWiki::basename($b))
2576 }
2577
2578 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2579 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
2580
2581 1