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