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