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