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