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