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