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