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