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