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