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