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