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