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