add missing setup options, tweak others' display
[ikiwiki] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use Encode;
8 use HTML::Entities;
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 %renderedfiles %oldrenderedfiles %pagesources
16             %destsources %depends %hooks %forcerebuild $gettext_obj};
17
18 use Exporter q{import};
19 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
20                  bestlink htmllink readfile writefile pagetype srcfile pagename
21                  displaytime will_render gettext urlto targetpage
22                  add_underlay
23                  %config %links %pagestate %renderedfiles
24                  %pagesources %destsources);
25 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
26 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
27 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
28
29 # Optimisation.
30 use Memoize;
31 memoize("abs2rel");
32 memoize("pagespec_translate");
33 memoize("file_pruned");
34
35 sub getsetup () { #{{{
36         wikiname => {
37                 type => "string",
38                 default => "wiki",
39                 description => "name of the wiki",
40                 safe => 1,
41                 rebuild => 1,
42         },
43         srcdir => {
44                 type => "string",
45                 default => undef,
46                 example => "$ENV{HOME}/wiki",
47                 description => "where the source of the wiki is located",
48                 safe => 0, # path
49                 rebuild => 1,
50         },
51         destdir => {
52                 type => "string",
53                 default => undef,
54                 example => "/var/www/wiki",
55                 description => "where to build the wiki",
56                 safe => 0, # path
57                 rebuild => 1,
58         },
59         adminuser => {
60                 type => "string",
61                 default => [],
62                 description => "user names of wiki admins",
63                 safe => 1,
64                 rebuild => 0,
65         },
66         adminemail => {
67                 type => "string",
68                 default => undef,
69                 example => 'me@example.com',
70                 description => "contact email for wiki",
71                 safe => 1,
72                 rebuild => 0,
73         },
74         url => {
75                 type => "string",
76                 default => '',
77                 example => "http://example.com/wiki",
78                 description => "base url to the wiki",
79                 safe => 1,
80                 rebuild => 1,
81         },
82         cgiurl => {
83                 type => "string",
84                 default => '',
85                 examples => "http://example.com/wiki/ikiwiki.cgi",
86                 description => "url to the ikiwiki.cgi",
87                 safe => 1,
88                 rebuild => 1,
89         },
90         rcs => {
91                 type => "string",
92                 default => '',
93                 description => "rcs backend to use",
94                 safe => 0, # don't allow overriding
95                 rebuild => 0,
96         },
97         default_plugins => {
98                 type => "internal",
99                 default => [qw{mdwn link inline htmlscrubber passwordauth
100                                 openid signinedit lockedit conditional
101                                 recentchanges parentlinks}],
102                 description => "plugins to enable by default",
103                 safe => 1,
104                 rebuild => 1,
105         },
106         add_plugins => {
107                 type => "string",
108                 default => [],
109                 description => "plugins to add to the default configuration",
110                 safe => 1,
111                 rebuild => 1,
112         },
113         disable_plugins => {
114                 type => "string",
115                 default => [],
116                 description => "plugins to disable",
117                 safe => 1,
118                 rebuild => 1,
119         },
120         wrappers => {
121                 type => "string",
122                 default => undef,
123                 description => "definitions of wrappers to generate",
124                 safe => 0,
125                 rebuild => 0,
126         },
127         wrapper => {
128                 type => "internal",
129                 default => undef,
130                 description => "wrapper filename",
131                 safe => 0,
132                 rebuild => 0,
133         },
134         wrappermode => {
135                 type => "internal",
136                 default => undef,
137                 description => "mode of wrapper file",
138                 safe => 0,
139                 rebuild => 0,
140         },
141         templatedir => {
142                 type => "string",
143                 default => "$installdir/share/ikiwiki/templates",
144                 description => "location of template files",
145                 safe => 0, # path
146                 rebuild => 1,
147         },
148         underlaydir => {
149                 type => "string",
150                 default => "$installdir/share/ikiwiki/basewiki",
151                 description => "base wiki source location",
152                 safe => 0, # path
153                 rebuild => 0,
154         },
155         underlaydirs => {
156                 type => "internal",
157                 default => [],
158                 description => "additional underlays to use",
159                 safe => 0,
160                 rebuild => 0,
161         },
162         verbose => {
163                 type => "boolean",
164                 default => 0,
165                 description => "display verbose messages when building?",
166                 safe => 1,
167                 rebuild => 0,
168         },
169         syslog => {
170                 type => "boolean",
171                 default => 0,
172                 description => "log to syslog?",
173                 safe => 1,
174                 rebuild => 0,
175         },
176         usedirs => {
177                 type => "boolean",
178                 default => 1,
179                 description => "create output files named page/index.html?",
180                 safe => 0, # changing requires manual transition
181                 rebuild => 1,
182         },
183         prefix_directives => {
184                 type => "boolean",
185                 default => 0,
186                 description => "use '!'-prefixed preprocessor directives?",
187                 safe => 0, # changing requires manual transition
188                 rebuild => 1,
189         },
190         discussion => {
191                 type => "boolean",
192                 default => 1,
193                 description => "enable Discussion pages?",
194                 safe => 1,
195                 rebuild => 1,
196         },
197         default_pageext => {
198                 type => "string",
199                 default => "mdwn",
200                 description => "extension to use for new pages",
201                 safe => 0, # not sanitized
202                 rebuild => 0,
203         },
204         htmlext => {
205                 type => "string",
206                 default => "html",
207                 description => "extension to use for html files",
208                 safe => 0, # not sanitized
209                 rebuild => 1,
210         },
211         timeformat => {
212                 type => "string",
213                 default => '%c',
214                 description => "strftime format string to display date",
215                 safe => 1,
216                 rebuild => 1,
217         },
218         locale => {
219                 type => "string",
220                 default => undef,
221                 example => "en_US.UTF-8",
222                 description => "UTF-8 locale to use",
223                 safe => 0,
224                 rebuild => 1,
225         },
226         sslcookie => {
227                 type => "boolean",
228                 default => 0,
229                 description => "only send cookies over SSL connections?",
230                 safe => 1,
231                 rebuild => 0,
232         },
233         userdir => {
234                 type => "string",
235                 default => "",
236                 example => "users",
237                 description => "put user pages below specified page",
238                 safe => 1,
239                 rebuild => 1,
240         },
241         numbacklinks => {
242                 type => "integer",
243                 default => 10,
244                 description => "how many backlinks to show before hiding excess (0 to show all)",
245                 safe => 1,
246                 rebuild => 1,
247         },
248         hardlink => {
249                 type => "boolean",
250                 default => 0,
251                 description => "attempt to hardlink source files? (optimisation for large files)",
252                 safe => 0, # paranoia
253                 rebuild => 0,
254         },
255         umask => {
256                 type => "integer",
257                 description => "",
258                 example => "022",
259                 description => "force ikiwiki to use a particular umask",
260                 safe => 0, # paranoia
261                 rebuild => 0,
262         },
263         libdir => {
264                 type => "string",
265                 default => "",
266                 example => "$ENV{HOME}/.ikiwiki/",
267                 description => "extra library and plugin directory",
268                 safe => 0, # directory
269                 rebuild => 0,
270         },
271         ENV => {
272                 type => "string", 
273                 default => {},
274                 description => "environment variables",
275                 safe => 0, # paranoia
276                 rebuild => 0,
277         },
278         exclude => {
279                 type => "string",
280                 default => undef,
281                 example => '\.wav$',
282                 description => "regexp of source files to ignore",
283                 safe => 0, # regexp
284                 rebuild => 1,
285         },
286         wiki_file_prune_regexps => {
287                 type => "internal",
288                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
289                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
290                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
291                         qr/(^|\/)_MTN\//,
292                         qr/\.dpkg-tmp$/],
293                 description => "regexps of source files to ignore",
294                 safe => 0,
295                 rebuild => 1,
296         },
297         wiki_file_regexp => {
298                 type => "internal",
299                 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
300                 description => "regexp of legal source files",
301                 safe => 0,
302                 rebuild => 1,
303         },
304         web_commit_regexp => {
305                 type => "internal",
306                 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
307                 description => "regexp to parse web commits from logs",
308                 safe => 0,
309                 rebuild => 0,
310         },
311         cgi => {
312                 type => "internal",
313                 default => 0,
314                 description => "run as a cgi",
315                 safe => 0,
316                 rebuild => 0,
317         },
318         cgi_disable_uploads => {
319                 type => "internal",
320                 default => 1,
321                 description => "whether CGI should accept file uploads",
322                 safe => 0,
323                 rebuild => 0,
324         },
325         post_commit => {
326                 type => "internal",
327                 default => 0,
328                 description => "run as a post-commit hook",
329                 safe => 0,
330                 rebuild => 0,
331         },
332         rebuild => {
333                 type => "internal",
334                 default => 0,
335                 description => "running in rebuild mode",
336                 safe => 0,
337                 rebuild => 0,
338         },
339         refresh => {
340                 type => "internal",
341                 default => 0,
342                 description => "running in refresh mode",
343                 safe => 0,
344                 rebuild => 0,
345         },
346         getctime => {
347                 type => "internal",
348                 default => 0,
349                 description => "running in getctime mode",
350                 safe => 0,
351                 rebuild => 0,
352         },
353         w3mmode => {
354                 type => "internal",
355                 default => 0,
356                 description => "running in w3mmode",
357                 safe => 0,
358                 rebuild => 0,
359         },
360         setup => {
361                 type => "internal",
362                 default => undef,
363                 description => "setup file to read",
364                 safe => 0,
365                 rebuild => 0,
366         },
367 } #}}}
368
369 sub defaultconfig () { #{{{
370         my %s=getsetup();
371         my @ret;
372         foreach my $key (keys %s) {
373                 push @ret, $key, $s{$key}->{default};
374         }
375         use Data::Dumper;
376         return @ret;
377 } #}}}
378
379 sub checkconfig () { #{{{
380         # locale stuff; avoid LC_ALL since it overrides everything
381         if (defined $ENV{LC_ALL}) {
382                 $ENV{LANG} = $ENV{LC_ALL};
383                 delete $ENV{LC_ALL};
384         }
385         if (defined $config{locale}) {
386                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
387                         $ENV{LANG}=$config{locale};
388                         $gettext_obj=undef;
389                 }
390         }
391
392         if (ref $config{ENV} eq 'HASH') {
393                 foreach my $val (keys %{$config{ENV}}) {
394                         $ENV{$val}=$config{ENV}{$val};
395                 }
396         }
397
398         if ($config{w3mmode}) {
399                 eval q{use Cwd q{abs_path}};
400                 error($@) if $@;
401                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
402                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
403                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
404                         unless $config{cgiurl} =~ m!file:///!;
405                 $config{url}="file://".$config{destdir};
406         }
407
408         if ($config{cgi} && ! length $config{url}) {
409                 error(gettext("Must specify url to wiki with --url when using --cgi"));
410         }
411         
412         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
413                 unless exists $config{wikistatedir};
414         
415         if ($config{rcs}) {
416                 eval qq{use IkiWiki::Rcs::$config{rcs}};
417                 if ($@) {
418                         error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
419                 }
420         }
421         else {
422                 require IkiWiki::Rcs::Stub;
423         }
424
425         if (defined $config{umask}) {
426                 umask(possibly_foolish_untaint($config{umask}));
427         }
428
429         run_hooks(checkconfig => sub { shift->() });
430
431         return 1;
432 } #}}}
433
434 sub listplugins () { #{{{
435         my %ret;
436
437         foreach my $dir (@INC, $config{libdir}) {
438                 next unless defined $dir;
439                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
440                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
441                         $ret{$plugin}=1;
442                 }
443         }
444         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
445                 next unless defined $dir;
446                 foreach my $file (glob("$dir/plugins/*")) {
447                         $ret{basename($file)}=1 if -x $file;
448                 }
449         }
450
451         return keys %ret;
452 } #}}}
453
454 sub loadplugins () { #{{{
455         if (defined $config{libdir}) {
456                 unshift @INC, possibly_foolish_untaint($config{libdir});
457         }
458
459         loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
460
461         run_hooks(getopt => sub { shift->() });
462         if (grep /^-/, @ARGV) {
463                 print STDERR "Unknown option: $_\n"
464                         foreach grep /^-/, @ARGV;
465                 usage();
466         }
467
468         return 1;
469 } #}}}
470
471 sub loadplugin ($) { #{{{
472         my $plugin=shift;
473
474         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
475
476         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
477                          "$installdir/lib/ikiwiki") {
478                 if (defined $dir && -x "$dir/plugins/$plugin") {
479                         require IkiWiki::Plugin::external;
480                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
481                         return 1;
482                 }
483         }
484
485         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
486         eval qq{use $mod};
487         if ($@) {
488                 error("Failed to load plugin $mod: $@");
489         }
490         return 1;
491 } #}}}
492
493 sub error ($;$) { #{{{
494         my $message=shift;
495         my $cleaner=shift;
496         log_message('err' => $message) if $config{syslog};
497         if (defined $cleaner) {
498                 $cleaner->();
499         }
500         die $message."\n";
501 } #}}}
502
503 sub debug ($) { #{{{
504         return unless $config{verbose};
505         return log_message(debug => @_);
506 } #}}}
507
508 my $log_open=0;
509 sub log_message ($$) { #{{{
510         my $type=shift;
511
512         if ($config{syslog}) {
513                 require Sys::Syslog;
514                 if (! $log_open) {
515                         Sys::Syslog::setlogsock('unix');
516                         Sys::Syslog::openlog('ikiwiki', '', 'user');
517                         $log_open=1;
518                 }
519                 return eval {
520                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
521                 };
522         }
523         elsif (! $config{cgi}) {
524                 return print "@_\n";
525         }
526         else {
527                 return print STDERR "@_\n";
528         }
529 } #}}}
530
531 sub possibly_foolish_untaint ($) { #{{{
532         my $tainted=shift;
533         my ($untainted)=$tainted=~/(.*)/s;
534         return $untainted;
535 } #}}}
536
537 sub basename ($) { #{{{
538         my $file=shift;
539
540         $file=~s!.*/+!!;
541         return $file;
542 } #}}}
543
544 sub dirname ($) { #{{{
545         my $file=shift;
546
547         $file=~s!/*[^/]+$!!;
548         return $file;
549 } #}}}
550
551 sub pagetype ($) { #{{{
552         my $page=shift;
553         
554         if ($page =~ /\.([^.]+)$/) {
555                 return $1 if exists $hooks{htmlize}{$1};
556         }
557         return;
558 } #}}}
559
560 sub isinternal ($) { #{{{
561         my $page=shift;
562         return exists $pagesources{$page} &&
563                 $pagesources{$page} =~ /\._([^.]+)$/;
564 } #}}}
565
566 sub pagename ($) { #{{{
567         my $file=shift;
568
569         my $type=pagetype($file);
570         my $page=$file;
571         $page=~s/\Q.$type\E*$// if defined $type;
572         return $page;
573 } #}}}
574
575 sub targetpage ($$) { #{{{
576         my $page=shift;
577         my $ext=shift;
578         
579         if (! $config{usedirs} || $page =~ /^index$/ ) {
580                 return $page.".".$ext;
581         } else {
582                 return $page."/index.".$ext;
583         }
584 } #}}}
585
586 sub htmlpage ($) { #{{{
587         my $page=shift;
588         
589         return targetpage($page, $config{htmlext});
590 } #}}}
591
592 sub srcfile_stat { #{{{
593         my $file=shift;
594         my $nothrow=shift;
595
596         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
597         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
598                 return "$dir/$file", stat(_) if -e "$dir/$file";
599         }
600         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
601         return;
602 } #}}}
603
604 sub srcfile ($;$) { #{{{
605         return (srcfile_stat(@_))[0];
606 } #}}}
607
608 sub add_underlay ($) { #{{{
609         my $dir=shift;
610
611         if ($dir=~/^\//) {
612                 unshift @{$config{underlaydirs}}, $dir;
613         }
614         else {
615                 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
616         }
617
618         return 1;
619 } #}}}
620
621 sub readfile ($;$$) { #{{{
622         my $file=shift;
623         my $binary=shift;
624         my $wantfd=shift;
625
626         if (-l $file) {
627                 error("cannot read a symlink ($file)");
628         }
629         
630         local $/=undef;
631         open (my $in, "<", $file) || error("failed to read $file: $!");
632         binmode($in) if ($binary);
633         return \*$in if $wantfd;
634         my $ret=<$in>;
635         close $in || error("failed to read $file: $!");
636         return $ret;
637 } #}}}
638
639 sub prep_writefile ($$) { #{{{
640         my $file=shift;
641         my $destdir=shift;
642         
643         my $test=$file;
644         while (length $test) {
645                 if (-l "$destdir/$test") {
646                         error("cannot write to a symlink ($test)");
647                 }
648                 $test=dirname($test);
649         }
650
651         my $dir=dirname("$destdir/$file");
652         if (! -d $dir) {
653                 my $d="";
654                 foreach my $s (split(m!/+!, $dir)) {
655                         $d.="$s/";
656                         if (! -d $d) {
657                                 mkdir($d) || error("failed to create directory $d: $!");
658                         }
659                 }
660         }
661
662         return 1;
663 } #}}}
664
665 sub writefile ($$$;$$) { #{{{
666         my $file=shift; # can include subdirs
667         my $destdir=shift; # directory to put file in
668         my $content=shift;
669         my $binary=shift;
670         my $writer=shift;
671         
672         prep_writefile($file, $destdir);
673         
674         my $newfile="$destdir/$file.ikiwiki-new";
675         if (-l $newfile) {
676                 error("cannot write to a symlink ($newfile)");
677         }
678         
679         my $cleanup = sub { unlink($newfile) };
680         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
681         binmode($out) if ($binary);
682         if ($writer) {
683                 $writer->(\*$out, $cleanup);
684         }
685         else {
686                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
687         }
688         close $out || error("failed saving $newfile: $!", $cleanup);
689         rename($newfile, "$destdir/$file") || 
690                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
691
692         return 1;
693 } #}}}
694
695 my %cleared;
696 sub will_render ($$;$) { #{{{
697         my $page=shift;
698         my $dest=shift;
699         my $clear=shift;
700
701         # Important security check.
702         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
703             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
704                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
705         }
706
707         if (! $clear || $cleared{$page}) {
708                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
709         }
710         else {
711                 foreach my $old (@{$renderedfiles{$page}}) {
712                         delete $destsources{$old};
713                 }
714                 $renderedfiles{$page}=[$dest];
715                 $cleared{$page}=1;
716         }
717         $destsources{$dest}=$page;
718
719         return 1;
720 } #}}}
721
722 sub bestlink ($$) { #{{{
723         my $page=shift;
724         my $link=shift;
725         
726         my $cwd=$page;
727         if ($link=~s/^\/+//) {
728                 # absolute links
729                 $cwd="";
730         }
731         $link=~s/\/$//;
732
733         do {
734                 my $l=$cwd;
735                 $l.="/" if length $l;
736                 $l.=$link;
737
738                 if (exists $links{$l}) {
739                         return $l;
740                 }
741                 elsif (exists $pagecase{lc $l}) {
742                         return $pagecase{lc $l};
743                 }
744         } while $cwd=~s!/?[^/]+$!!;
745
746         if (length $config{userdir}) {
747                 my $l = "$config{userdir}/".lc($link);
748                 if (exists $links{$l}) {
749                         return $l;
750                 }
751                 elsif (exists $pagecase{lc $l}) {
752                         return $pagecase{lc $l};
753                 }
754         }
755
756         #print STDERR "warning: page $page, broken link: $link\n";
757         return "";
758 } #}}}
759
760 sub isinlinableimage ($) { #{{{
761         my $file=shift;
762         
763         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
764 } #}}}
765
766 sub pagetitle ($;$) { #{{{
767         my $page=shift;
768         my $unescaped=shift;
769
770         if ($unescaped) {
771                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
772         }
773         else {
774                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
775         }
776
777         return $page;
778 } #}}}
779
780 sub titlepage ($) { #{{{
781         my $title=shift;
782         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
783         return $title;
784 } #}}}
785
786 sub linkpage ($) { #{{{
787         my $link=shift;
788         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
789         return $link;
790 } #}}}
791
792 sub cgiurl (@) { #{{{
793         my %params=@_;
794
795         return $config{cgiurl}."?".
796                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
797 } #}}}
798
799 sub baseurl (;$) { #{{{
800         my $page=shift;
801
802         return "$config{url}/" if ! defined $page;
803         
804         $page=htmlpage($page);
805         $page=~s/[^\/]+$//;
806         $page=~s/[^\/]+\//..\//g;
807         return $page;
808 } #}}}
809
810 sub abs2rel ($$) { #{{{
811         # Work around very innefficient behavior in File::Spec if abs2rel
812         # is passed two relative paths. It's much faster if paths are
813         # absolute! (Debian bug #376658; fixed in debian unstable now)
814         my $path="/".shift;
815         my $base="/".shift;
816
817         require File::Spec;
818         my $ret=File::Spec->abs2rel($path, $base);
819         $ret=~s/^// if defined $ret;
820         return $ret;
821 } #}}}
822
823 sub displaytime ($;$) { #{{{
824         my $time=shift;
825         my $format=shift;
826         if (! defined $format) {
827                 $format=$config{timeformat};
828         }
829
830         # strftime doesn't know about encodings, so make sure
831         # its output is properly treated as utf8
832         return decode_utf8(POSIX::strftime($format, localtime($time)));
833 } #}}}
834
835 sub beautify_urlpath ($) { #{{{
836         my $url=shift;
837
838         if ($config{usedirs}) {
839                 $url =~ s!/index.$config{htmlext}$!/!;
840         }
841
842         # Ensure url is not an empty link, and
843         # if it's relative, make that explicit to avoid colon confusion.
844         if ($url !~ /^\//) {
845                 $url="./$url";
846         }
847
848         return $url;
849 } #}}}
850
851 sub urlto ($$;$) { #{{{
852         my $to=shift;
853         my $from=shift;
854         my $absolute=shift;
855         
856         if (! length $to) {
857                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
858         }
859
860         if (! $destsources{$to}) {
861                 $to=htmlpage($to);
862         }
863
864         if ($absolute) {
865                 return $config{url}.beautify_urlpath("/".$to);
866         }
867
868         my $link = abs2rel($to, dirname(htmlpage($from)));
869
870         return beautify_urlpath($link);
871 } #}}}
872
873 sub htmllink ($$$;@) { #{{{
874         my $lpage=shift; # the page doing the linking
875         my $page=shift; # the page that will contain the link (different for inline)
876         my $link=shift;
877         my %opts=@_;
878
879         $link=~s/\/$//;
880
881         my $bestlink;
882         if (! $opts{forcesubpage}) {
883                 $bestlink=bestlink($lpage, $link);
884         }
885         else {
886                 $bestlink="$lpage/".lc($link);
887         }
888
889         my $linktext;
890         if (defined $opts{linktext}) {
891                 $linktext=$opts{linktext};
892         }
893         else {
894                 $linktext=pagetitle(basename($link));
895         }
896         
897         return "<span class=\"selflink\">$linktext</span>"
898                 if length $bestlink && $page eq $bestlink &&
899                    ! defined $opts{anchor};
900         
901         if (! $destsources{$bestlink}) {
902                 $bestlink=htmlpage($bestlink);
903
904                 if (! $destsources{$bestlink}) {
905                         return $linktext unless length $config{cgiurl};
906                         return "<span class=\"createlink\"><a href=\"".
907                                 cgiurl(
908                                         do => "create",
909                                         page => lc($link),
910                                         from => $lpage
911                                 ).
912                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
913                 }
914         }
915         
916         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
917         $bestlink=beautify_urlpath($bestlink);
918         
919         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
920                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
921         }
922
923         if (defined $opts{anchor}) {
924                 $bestlink.="#".$opts{anchor};
925         }
926
927         my @attrs;
928         if (defined $opts{rel}) {
929                 push @attrs, ' rel="'.$opts{rel}.'"';
930         }
931         if (defined $opts{class}) {
932                 push @attrs, ' class="'.$opts{class}.'"';
933         }
934
935         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
936 } #}}}
937
938 sub userlink ($) { #{{{
939         my $user=shift;
940
941         my $oiduser=eval { openiduser($user) };
942         if (defined $oiduser) {
943                 return "<a href=\"$user\">$oiduser</a>";
944         }
945         else {
946                 eval q{use CGI 'escapeHTML'};
947                 error($@) if $@;
948
949                 return htmllink("", "", escapeHTML(
950                         length $config{userdir} ? $config{userdir}."/".$user : $user
951                 ), noimageinline => 1);
952         }
953 } #}}}
954
955 sub htmlize ($$$$) { #{{{
956         my $page=shift;
957         my $destpage=shift;
958         my $type=shift;
959         my $content=shift;
960         
961         my $oneline = $content !~ /\n/;
962
963         if (exists $hooks{htmlize}{$type}) {
964                 $content=$hooks{htmlize}{$type}{call}->(
965                         page => $page,
966                         content => $content,
967                 );
968         }
969         else {
970                 error("htmlization of $type not supported");
971         }
972
973         run_hooks(sanitize => sub {
974                 $content=shift->(
975                         page => $page,
976                         destpage => $destpage,
977                         content => $content,
978                 );
979         });
980         
981         if ($oneline) {
982                 # hack to get rid of enclosing junk added by markdown
983                 # and other htmlizers
984                 $content=~s/^<p>//i;
985                 $content=~s/<\/p>$//i;
986                 chomp $content;
987         }
988
989         return $content;
990 } #}}}
991
992 sub linkify ($$$) { #{{{
993         my $page=shift;
994         my $destpage=shift;
995         my $content=shift;
996
997         run_hooks(linkify => sub {
998                 $content=shift->(
999                         page => $page,
1000                         destpage => $destpage,
1001                         content => $content,
1002                 );
1003         });
1004         
1005         return $content;
1006 } #}}}
1007
1008 our %preprocessing;
1009 our $preprocess_preview=0;
1010 sub preprocess ($$$;$$) { #{{{
1011         my $page=shift; # the page the data comes from
1012         my $destpage=shift; # the page the data will appear in (different for inline)
1013         my $content=shift;
1014         my $scan=shift;
1015         my $preview=shift;
1016
1017         # Using local because it needs to be set within any nested calls
1018         # of this function.
1019         local $preprocess_preview=$preview if defined $preview;
1020
1021         my $handle=sub {
1022                 my $escape=shift;
1023                 my $prefix=shift;
1024                 my $command=shift;
1025                 my $params=shift;
1026                 if (length $escape) {
1027                         return "[[$prefix$command $params]]";
1028                 }
1029                 elsif (exists $hooks{preprocess}{$command}) {
1030                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1031                         # Note: preserve order of params, some plugins may
1032                         # consider it significant.
1033                         my @params;
1034                         while ($params =~ m{
1035                                 (?:([-\w]+)=)?          # 1: named parameter key?
1036                                 (?:
1037                                         """(.*?)"""     # 2: triple-quoted value
1038                                 |
1039                                         "([^"]+)"       # 3: single-quoted value
1040                                 |
1041                                         (\S+)           # 4: unquoted value
1042                                 )
1043                                 (?:\s+|$)               # delimiter to next param
1044                         }sgx) {
1045                                 my $key=$1;
1046                                 my $val;
1047                                 if (defined $2) {
1048                                         $val=$2;
1049                                         $val=~s/\r\n/\n/mg;
1050                                         $val=~s/^\n+//g;
1051                                         $val=~s/\n+$//g;
1052                                 }
1053                                 elsif (defined $3) {
1054                                         $val=$3;
1055                                 }
1056                                 elsif (defined $4) {
1057                                         $val=$4;
1058                                 }
1059
1060                                 if (defined $key) {
1061                                         push @params, $key, $val;
1062                                 }
1063                                 else {
1064                                         push @params, $val, '';
1065                                 }
1066                         }
1067                         if ($preprocessing{$page}++ > 3) {
1068                                 # Avoid loops of preprocessed pages preprocessing
1069                                 # other pages that preprocess them, etc.
1070                                 #translators: The first parameter is a
1071                                 #translators: preprocessor directive name,
1072                                 #translators: the second a page name, the
1073                                 #translators: third a number.
1074                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
1075                                         $command, $page, $preprocessing{$page}).
1076                                 "]]";
1077                         }
1078                         my $ret;
1079                         if (! $scan) {
1080                                 $ret=eval {
1081                                         $hooks{preprocess}{$command}{call}->(
1082                                                 @params,
1083                                                 page => $page,
1084                                                 destpage => $destpage,
1085                                                 preview => $preprocess_preview,
1086                                         );
1087                                 };
1088                                 if ($@) {
1089                                         chomp $@;
1090                                         $ret="[[!$command <span class=\"error\">".
1091                                                 gettext("Error").": $@"."</span>]]";
1092                                 }
1093                         }
1094                         else {
1095                                 # use void context during scan pass
1096                                 eval {
1097                                         $hooks{preprocess}{$command}{call}->(
1098                                                 @params,
1099                                                 page => $page,
1100                                                 destpage => $destpage,
1101                                                 preview => $preprocess_preview,
1102                                         );
1103                                 };
1104                                 $ret="";
1105                         }
1106                         $preprocessing{$page}--;
1107                         return $ret;
1108                 }
1109                 else {
1110                         return "[[$prefix$command $params]]";
1111                 }
1112         };
1113         
1114         my $regex;
1115         if ($config{prefix_directives}) {
1116                 $regex = qr{
1117                         (\\?)           # 1: escape?
1118                         \[\[(!)         # directive open; 2: prefix
1119                         ([-\w]+)        # 3: command
1120                         (               # 4: the parameters..
1121                                 \s+     # Must have space if parameters present
1122                                 (?:
1123                                         (?:[-\w]+=)?            # named parameter key?
1124                                         (?:
1125                                                 """.*?"""       # triple-quoted value
1126                                                 |
1127                                                 "[^"]+"         # single-quoted value
1128                                                 |
1129                                                 [^\s\]]+        # unquoted value
1130                                         )
1131                                         \s*                     # whitespace or end
1132                                                                 # of directive
1133                                 )
1134                         *)?             # 0 or more parameters
1135                         \]\]            # directive closed
1136                 }sx;
1137         }
1138         else {
1139                 $regex = qr{
1140                         (\\?)           # 1: escape?
1141                         \[\[(!?)        # directive open; 2: optional prefix
1142                         ([-\w]+)        # 3: command
1143                         \s+
1144                         (               # 4: the parameters..
1145                                 (?:
1146                                         (?:[-\w]+=)?            # named parameter key?
1147                                         (?:
1148                                                 """.*?"""       # triple-quoted value
1149                                                 |
1150                                                 "[^"]+"         # single-quoted value
1151                                                 |
1152                                                 [^\s\]]+        # unquoted value
1153                                         )
1154                                         \s*                     # whitespace or end
1155                                                                 # of directive
1156                                 )
1157                         *)              # 0 or more parameters
1158                         \]\]            # directive closed
1159                 }sx;
1160         }
1161
1162         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1163         return $content;
1164 } #}}}
1165
1166 sub filter ($$$) { #{{{
1167         my $page=shift;
1168         my $destpage=shift;
1169         my $content=shift;
1170
1171         run_hooks(filter => sub {
1172                 $content=shift->(page => $page, destpage => $destpage, 
1173                         content => $content);
1174         });
1175
1176         return $content;
1177 } #}}}
1178
1179 sub indexlink () { #{{{
1180         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1181 } #}}}
1182
1183 my $wikilock;
1184
1185 sub lockwiki (;$) { #{{{
1186         my $wait=@_ ? shift : 1;
1187         # Take an exclusive lock on the wiki to prevent multiple concurrent
1188         # run issues. The lock will be dropped on program exit.
1189         if (! -d $config{wikistatedir}) {
1190                 mkdir($config{wikistatedir});
1191         }
1192         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1193                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1194         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1195                 if ($wait) {
1196                         debug("wiki seems to be locked, waiting for lock");
1197                         my $wait=600; # arbitrary, but don't hang forever to 
1198                                       # prevent process pileup
1199                         for (1..$wait) {
1200                                 return if flock($wikilock, 2 | 4);
1201                                 sleep 1;
1202                         }
1203                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1204                 }
1205                 else {
1206                         return 0;
1207                 }
1208         }
1209         return 1;
1210 } #}}}
1211
1212 sub unlockwiki () { #{{{
1213         return close($wikilock) if $wikilock;
1214         return;
1215 } #}}}
1216
1217 my $commitlock;
1218
1219 sub commit_hook_enabled () { #{{{
1220         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1221                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1222         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1223                 close($commitlock) || error("failed closing commitlock: $!");
1224                 return 0;
1225         }
1226         close($commitlock) || error("failed closing commitlock: $!");
1227         return 1;
1228 } #}}}
1229
1230 sub disable_commit_hook () { #{{{
1231         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1232                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1233         if (! flock($commitlock, 2)) { # LOCK_EX
1234                 error("failed to get commit lock");
1235         }
1236         return 1;
1237 } #}}}
1238
1239 sub enable_commit_hook () { #{{{
1240         return close($commitlock) if $commitlock;
1241         return;
1242 } #}}}
1243
1244 sub loadindex () { #{{{
1245         %oldrenderedfiles=%pagectime=();
1246         if (! $config{rebuild}) {
1247                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1248                 %destsources=%renderedfiles=%pagecase=%pagestate=();
1249         }
1250         my $in;
1251         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1252                 if (-e "$config{wikistatedir}/index") {
1253                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1254                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1255                 }
1256                 else {
1257                         return;
1258                 }
1259         }
1260         my $ret=Storable::fd_retrieve($in);
1261         if (! defined $ret) {
1262                 return 0;
1263         }
1264         my %index=%$ret;
1265         foreach my $src (keys %index) {
1266                 my %d=%{$index{$src}};
1267                 my $page=pagename($src);
1268                 $pagectime{$page}=$d{ctime};
1269                 if (! $config{rebuild}) {
1270                         $pagesources{$page}=$src;
1271                         $pagemtime{$page}=$d{mtime};
1272                         $renderedfiles{$page}=$d{dest};
1273                         if (exists $d{links} && ref $d{links}) {
1274                                 $links{$page}=$d{links};
1275                                 $oldlinks{$page}=[@{$d{links}}];
1276                         }
1277                         if (exists $d{depends}) {
1278                                 $depends{$page}=$d{depends};
1279                         }
1280                         if (exists $d{state}) {
1281                                 $pagestate{$page}=$d{state};
1282                         }
1283                 }
1284                 $oldrenderedfiles{$page}=[@{$d{dest}}];
1285         }
1286         foreach my $page (keys %pagesources) {
1287                 $pagecase{lc $page}=$page;
1288         }
1289         foreach my $page (keys %renderedfiles) {
1290                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1291         }
1292         return close($in);
1293 } #}}}
1294
1295 sub saveindex () { #{{{
1296         run_hooks(savestate => sub { shift->() });
1297
1298         my %hookids;
1299         foreach my $type (keys %hooks) {
1300                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1301         }
1302         my @hookids=keys %hookids;
1303
1304         if (! -d $config{wikistatedir}) {
1305                 mkdir($config{wikistatedir});
1306         }
1307         my $newfile="$config{wikistatedir}/indexdb.new";
1308         my $cleanup = sub { unlink($newfile) };
1309         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1310         my %index;
1311         foreach my $page (keys %pagemtime) {
1312                 next unless $pagemtime{$page};
1313                 my $src=$pagesources{$page};
1314
1315                 $index{$src}={
1316                         ctime => $pagectime{$page},
1317                         mtime => $pagemtime{$page},
1318                         dest => $renderedfiles{$page},
1319                         links => $links{$page},
1320                 };
1321
1322                 if (exists $depends{$page}) {
1323                         $index{$src}{depends} = $depends{$page};
1324                 }
1325
1326                 if (exists $pagestate{$page}) {
1327                         foreach my $id (@hookids) {
1328                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1329                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1330                                 }
1331                         }
1332                 }
1333         }
1334         my $ret=Storable::nstore_fd(\%index, $out);
1335         return if ! defined $ret || ! $ret;
1336         close $out || error("failed saving to $newfile: $!", $cleanup);
1337         rename($newfile, "$config{wikistatedir}/indexdb") ||
1338                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1339         
1340         return 1;
1341 } #}}}
1342
1343 sub template_file ($) { #{{{
1344         my $template=shift;
1345
1346         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1347                 return "$dir/$template" if -e "$dir/$template";
1348         }
1349         return;
1350 } #}}}
1351
1352 sub template_params (@) { #{{{
1353         my $filename=template_file(shift);
1354
1355         if (! defined $filename) {
1356                 return if wantarray;
1357                 return "";
1358         }
1359
1360         my @ret=(
1361                 filter => sub {
1362                         my $text_ref = shift;
1363                         ${$text_ref} = decode_utf8(${$text_ref});
1364                 },
1365                 filename => $filename,
1366                 loop_context_vars => 1,
1367                 die_on_bad_params => 0,
1368                 @_
1369         );
1370         return wantarray ? @ret : {@ret};
1371 } #}}}
1372
1373 sub template ($;@) { #{{{
1374         require HTML::Template;
1375         return HTML::Template->new(template_params(@_));
1376 } #}}}
1377
1378 sub misctemplate ($$;@) { #{{{
1379         my $title=shift;
1380         my $pagebody=shift;
1381         
1382         my $template=template("misc.tmpl");
1383         $template->param(
1384                 title => $title,
1385                 indexlink => indexlink(),
1386                 wikiname => $config{wikiname},
1387                 pagebody => $pagebody,
1388                 baseurl => baseurl(),
1389                 @_,
1390         );
1391         run_hooks(pagetemplate => sub {
1392                 shift->(page => "", destpage => "", template => $template);
1393         });
1394         return $template->output;
1395 }#}}}
1396
1397 sub hook (@) { # {{{
1398         my %param=@_;
1399         
1400         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1401                 error 'hook requires type, call, and id parameters';
1402         }
1403
1404         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1405         
1406         $hooks{$param{type}}{$param{id}}=\%param;
1407         return 1;
1408 } # }}}
1409
1410 sub run_hooks ($$) { # {{{
1411         # Calls the given sub for each hook of the given type,
1412         # passing it the hook function to call.
1413         my $type=shift;
1414         my $sub=shift;
1415
1416         if (exists $hooks{$type}) {
1417                 my @deferred;
1418                 foreach my $id (keys %{$hooks{$type}}) {
1419                         if ($hooks{$type}{$id}{last}) {
1420                                 push @deferred, $id;
1421                                 next;
1422                         }
1423                         $sub->($hooks{$type}{$id}{call});
1424                 }
1425                 foreach my $id (@deferred) {
1426                         $sub->($hooks{$type}{$id}{call});
1427                 }
1428         }
1429
1430         return 1;
1431 } #}}}
1432
1433 sub globlist_to_pagespec ($) { #{{{
1434         my @globlist=split(' ', shift);
1435
1436         my (@spec, @skip);
1437         foreach my $glob (@globlist) {
1438                 if ($glob=~/^!(.*)/) {
1439                         push @skip, $glob;
1440                 }
1441                 else {
1442                         push @spec, $glob;
1443                 }
1444         }
1445
1446         my $spec=join(' or ', @spec);
1447         if (@skip) {
1448                 my $skip=join(' and ', @skip);
1449                 if (length $spec) {
1450                         $spec="$skip and ($spec)";
1451                 }
1452                 else {
1453                         $spec=$skip;
1454                 }
1455         }
1456         return $spec;
1457 } #}}}
1458
1459 sub is_globlist ($) { #{{{
1460         my $s=shift;
1461         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1462 } #}}}
1463
1464 sub safequote ($) { #{{{
1465         my $s=shift;
1466         $s=~s/[{}]//g;
1467         return "q{$s}";
1468 } #}}}
1469
1470 sub add_depends ($$) { #{{{
1471         my $page=shift;
1472         my $pagespec=shift;
1473         
1474         return unless pagespec_valid($pagespec);
1475
1476         if (! exists $depends{$page}) {
1477                 $depends{$page}=$pagespec;
1478         }
1479         else {
1480                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1481         }
1482
1483         return 1;
1484 } # }}}
1485
1486 sub file_pruned ($$) { #{{{
1487         require File::Spec;
1488         my $file=File::Spec->canonpath(shift);
1489         my $base=File::Spec->canonpath(shift);
1490         $file =~ s#^\Q$base\E/+##;
1491
1492         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1493         return $file =~ m/$regexp/ && $file ne $base;
1494 } #}}}
1495
1496 sub gettext { #{{{
1497         # Only use gettext in the rare cases it's needed.
1498         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1499             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1500             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1501                 if (! $gettext_obj) {
1502                         $gettext_obj=eval q{
1503                                 use Locale::gettext q{textdomain};
1504                                 Locale::gettext->domain('ikiwiki')
1505                         };
1506                         if ($@) {
1507                                 print STDERR "$@";
1508                                 $gettext_obj=undef;
1509                                 return shift;
1510                         }
1511                 }
1512                 return $gettext_obj->get(shift);
1513         }
1514         else {
1515                 return shift;
1516         }
1517 } #}}}
1518
1519 sub yesno ($) { #{{{
1520         my $val=shift;
1521
1522         return (defined $val && lc($val) eq gettext("yes"));
1523 } #}}}
1524
1525 sub pagespec_merge ($$) { #{{{
1526         my $a=shift;
1527         my $b=shift;
1528
1529         return $a if $a eq $b;
1530
1531         # Support for old-style GlobLists.
1532         if (is_globlist($a)) {
1533                 $a=globlist_to_pagespec($a);
1534         }
1535         if (is_globlist($b)) {
1536                 $b=globlist_to_pagespec($b);
1537         }
1538
1539         return "($a) or ($b)";
1540 } #}}}
1541
1542 sub pagespec_translate ($) { #{{{
1543         my $spec=shift;
1544
1545         # Support for old-style GlobLists.
1546         if (is_globlist($spec)) {
1547                 $spec=globlist_to_pagespec($spec);
1548         }
1549
1550         # Convert spec to perl code.
1551         my $code="";
1552         while ($spec=~m{
1553                 \s*             # ignore whitespace
1554                 (               # 1: match a single word
1555                         \!              # !
1556                 |
1557                         \(              # (
1558                 |
1559                         \)              # )
1560                 |
1561                         \w+\([^\)]*\)   # command(params)
1562                 |
1563                         [^\s()]+        # any other text
1564                 )
1565                 \s*             # ignore whitespace
1566         }igx) {
1567                 my $word=$1;
1568                 if (lc $word eq 'and') {
1569                         $code.=' &&';
1570                 }
1571                 elsif (lc $word eq 'or') {
1572                         $code.=' ||';
1573                 }
1574                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1575                         $code.=' '.$word;
1576                 }
1577                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1578                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1579                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1580                         }
1581                         else {
1582                                 $code.=' 0';
1583                         }
1584                 }
1585                 else {
1586                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1587                 }
1588         }
1589
1590         if (! length $code) {
1591                 $code=0;
1592         }
1593
1594         no warnings;
1595         return eval 'sub { my $page=shift; '.$code.' }';
1596 } #}}}
1597
1598 sub pagespec_match ($$;@) { #{{{
1599         my $page=shift;
1600         my $spec=shift;
1601         my @params=@_;
1602
1603         # Backwards compatability with old calling convention.
1604         if (@params == 1) {
1605                 unshift @params, 'location';
1606         }
1607
1608         my $sub=pagespec_translate($spec);
1609         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1610         return $sub->($page, @params);
1611 } #}}}
1612
1613 sub pagespec_valid ($) { #{{{
1614         my $spec=shift;
1615
1616         my $sub=pagespec_translate($spec);
1617         return ! $@;
1618 } #}}}
1619         
1620 sub glob2re ($) { #{{{
1621         my $re=quotemeta(shift);
1622         $re=~s/\\\*/.*/g;
1623         $re=~s/\\\?/./g;
1624         return $re;
1625 } #}}}
1626
1627 package IkiWiki::FailReason;
1628
1629 use overload ( #{{{
1630         '""'    => sub { ${$_[0]} },
1631         '0+'    => sub { 0 },
1632         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1633         fallback => 1,
1634 ); #}}}
1635
1636 sub new { #{{{
1637         my $class = shift;
1638         my $value = shift;
1639         return bless \$value, $class;
1640 } #}}}
1641
1642 package IkiWiki::SuccessReason;
1643
1644 use overload ( #{{{
1645         '""'    => sub { ${$_[0]} },
1646         '0+'    => sub { 1 },
1647         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1648         fallback => 1,
1649 ); #}}}
1650
1651 sub new { #{{{
1652         my $class = shift;
1653         my $value = shift;
1654         return bless \$value, $class;
1655 }; #}}}
1656
1657 package IkiWiki::PageSpec;
1658
1659 sub match_glob ($$;@) { #{{{
1660         my $page=shift;
1661         my $glob=shift;
1662         my %params=@_;
1663         
1664         my $from=exists $params{location} ? $params{location} : '';
1665         
1666         # relative matching
1667         if ($glob =~ m!^\./!) {
1668                 $from=~s#/?[^/]+$##;
1669                 $glob=~s#^\./##;
1670                 $glob="$from/$glob" if length $from;
1671         }
1672
1673         my $regexp=IkiWiki::glob2re($glob);
1674         if ($page=~/^$regexp$/i) {
1675                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1676                         return IkiWiki::SuccessReason->new("$glob matches $page");
1677                 }
1678                 else {
1679                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1680                 }
1681         }
1682         else {
1683                 return IkiWiki::FailReason->new("$glob does not match $page");
1684         }
1685 } #}}}
1686
1687 sub match_internal ($$;@) { #{{{
1688         return match_glob($_[0], $_[1], @_, internal => 1)
1689 } #}}}
1690
1691 sub match_link ($$;@) { #{{{
1692         my $page=shift;
1693         my $link=lc(shift);
1694         my %params=@_;
1695
1696         my $from=exists $params{location} ? $params{location} : '';
1697
1698         # relative matching
1699         if ($link =~ m!^\.! && defined $from) {
1700                 $from=~s#/?[^/]+$##;
1701                 $link=~s#^\./##;
1702                 $link="$from/$link" if length $from;
1703         }
1704
1705         my $links = $IkiWiki::links{$page};
1706         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1707         my $bestlink = IkiWiki::bestlink($from, $link);
1708         foreach my $p (@{$links}) {
1709                 if (length $bestlink) {
1710                         return IkiWiki::SuccessReason->new("$page links to $link")
1711                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1712                 }
1713                 else {
1714                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1715                                 if match_glob($p, $link, %params);
1716                 }
1717         }
1718         return IkiWiki::FailReason->new("$page does not link to $link");
1719 } #}}}
1720
1721 sub match_backlink ($$;@) { #{{{
1722         return match_link($_[1], $_[0], @_);
1723 } #}}}
1724
1725 sub match_created_before ($$;@) { #{{{
1726         my $page=shift;
1727         my $testpage=shift;
1728
1729         if (exists $IkiWiki::pagectime{$testpage}) {
1730                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1731                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1732                 }
1733                 else {
1734                         return IkiWiki::FailReason->new("$page not created before $testpage");
1735                 }
1736         }
1737         else {
1738                 return IkiWiki::FailReason->new("$testpage has no ctime");
1739         }
1740 } #}}}
1741
1742 sub match_created_after ($$;@) { #{{{
1743         my $page=shift;
1744         my $testpage=shift;
1745
1746         if (exists $IkiWiki::pagectime{$testpage}) {
1747                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1748                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1749                 }
1750                 else {
1751                         return IkiWiki::FailReason->new("$page not created after $testpage");
1752                 }
1753         }
1754         else {
1755                 return IkiWiki::FailReason->new("$testpage has no ctime");
1756         }
1757 } #}}}
1758
1759 sub match_creation_day ($$;@) { #{{{
1760         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1761                 return IkiWiki::SuccessReason->new('creation_day matched');
1762         }
1763         else {
1764                 return IkiWiki::FailReason->new('creation_day did not match');
1765         }
1766 } #}}}
1767
1768 sub match_creation_month ($$;@) { #{{{
1769         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1770                 return IkiWiki::SuccessReason->new('creation_month matched');
1771         }
1772         else {
1773                 return IkiWiki::FailReason->new('creation_month did not match');
1774         }
1775 } #}}}
1776
1777 sub match_creation_year ($$;@) { #{{{
1778         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1779                 return IkiWiki::SuccessReason->new('creation_year matched');
1780         }
1781         else {
1782                 return IkiWiki::FailReason->new('creation_year did not match');
1783         }
1784 } #}}}
1785
1786 1