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