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