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