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