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