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