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