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