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