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