]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
Updated French translation. Closes: #532654
[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             %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21                  pagespec_match_list bestlink htmllink readfile writefile
22                  pagetype srcfile pagename displaytime will_render gettext urlto
23                  targetpage add_underlay pagetitle titlepage linkpage
24                  newpagefile inject add_link
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='/usr'; # 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         underlaydirbase => {
161                 type => "internal",
162                 default => "$installdir/share/ikiwiki",
163                 description => "parent directory containing additional underlays",
164                 safe => 0,
165                 rebuild => 0,
166         },
167         wrappers => {
168                 type => "internal",
169                 default => [],
170                 description => "wrappers to generate",
171                 safe => 0,
172                 rebuild => 0,
173         },
174         underlaydirs => {
175                 type => "internal",
176                 default => [],
177                 description => "additional underlays to use",
178                 safe => 0,
179                 rebuild => 0,
180         },
181         verbose => {
182                 type => "boolean",
183                 example => 1,
184                 description => "display verbose messages?",
185                 safe => 1,
186                 rebuild => 0,
187         },
188         syslog => {
189                 type => "boolean",
190                 example => 1,
191                 description => "log to syslog?",
192                 safe => 1,
193                 rebuild => 0,
194         },
195         usedirs => {
196                 type => "boolean",
197                 default => 1,
198                 description => "create output files named page/index.html?",
199                 safe => 0, # changing requires manual transition
200                 rebuild => 1,
201         },
202         prefix_directives => {
203                 type => "boolean",
204                 default => 1,
205                 description => "use '!'-prefixed preprocessor directives?",
206                 safe => 0, # changing requires manual transition
207                 rebuild => 1,
208         },
209         indexpages => {
210                 type => "boolean",
211                 default => 0,
212                 description => "use page/index.mdwn source files",
213                 safe => 1,
214                 rebuild => 1,
215         },
216         discussion => {
217                 type => "boolean",
218                 default => 1,
219                 description => "enable Discussion pages?",
220                 safe => 1,
221                 rebuild => 1,
222         },
223         sslcookie => {
224                 type => "boolean",
225                 default => 0,
226                 description => "only send cookies over SSL connections?",
227                 advanced => 1,
228                 safe => 1,
229                 rebuild => 0,
230         },
231         default_pageext => {
232                 type => "string",
233                 default => "mdwn",
234                 description => "extension to use for new pages",
235                 safe => 0, # not sanitized
236                 rebuild => 0,
237         },
238         htmlext => {
239                 type => "string",
240                 default => "html",
241                 description => "extension to use for html files",
242                 safe => 0, # not sanitized
243                 rebuild => 1,
244         },
245         timeformat => {
246                 type => "string",
247                 default => '%c',
248                 description => "strftime format string to display date",
249                 advanced => 1,
250                 safe => 1,
251                 rebuild => 1,
252         },
253         locale => {
254                 type => "string",
255                 default => undef,
256                 example => "en_US.UTF-8",
257                 description => "UTF-8 locale to use",
258                 advanced => 1,
259                 safe => 0,
260                 rebuild => 1,
261         },
262         userdir => {
263                 type => "string",
264                 default => "",
265                 example => "users",
266                 description => "put user pages below specified page",
267                 safe => 1,
268                 rebuild => 1,
269         },
270         numbacklinks => {
271                 type => "integer",
272                 default => 10,
273                 description => "how many backlinks to show before hiding excess (0 to show all)",
274                 safe => 1,
275                 rebuild => 1,
276         },
277         hardlink => {
278                 type => "boolean",
279                 default => 0,
280                 description => "attempt to hardlink source files? (optimisation for large files)",
281                 advanced => 1,
282                 safe => 0, # paranoia
283                 rebuild => 0,
284         },
285         umask => {
286                 type => "integer",
287                 example => "022",
288                 description => "force ikiwiki to use a particular umask",
289                 advanced => 1,
290                 safe => 0, # paranoia
291                 rebuild => 0,
292         },
293         wrappergroup => {
294                 type => "string",
295                 example => "ikiwiki",
296                 description => "group for wrappers to run in",
297                 advanced => 1,
298                 safe => 0, # paranoia
299                 rebuild => 0,
300         },
301         libdir => {
302                 type => "string",
303                 default => "",
304                 example => "$ENV{HOME}/.ikiwiki/",
305                 description => "extra library and plugin directory",
306                 advanced => 1,
307                 safe => 0, # directory
308                 rebuild => 0,
309         },
310         ENV => {
311                 type => "string", 
312                 default => {},
313                 description => "environment variables",
314                 safe => 0, # paranoia
315                 rebuild => 0,
316         },
317         exclude => {
318                 type => "string",
319                 default => undef,
320                 example => '\.wav$',
321                 description => "regexp of source files to ignore",
322                 advanced => 1,
323                 safe => 0, # regexp
324                 rebuild => 1,
325         },
326         wiki_file_prune_regexps => {
327                 type => "internal",
328                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
329                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
330                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
331                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
332                         qr/\.dpkg-tmp$/],
333                 description => "regexps of source files to ignore",
334                 safe => 0,
335                 rebuild => 1,
336         },
337         wiki_file_chars => {
338                 type => "string",
339                 description => "specifies the characters that are allowed in source filenames",
340                 default => "-[:alnum:]+/.:_",
341                 safe => 0,
342                 rebuild => 1,
343         },
344         wiki_file_regexp => {
345                 type => "internal",
346                 description => "regexp of legal source files",
347                 safe => 0,
348                 rebuild => 1,
349         },
350         web_commit_regexp => {
351                 type => "internal",
352                 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
353                 description => "regexp to parse web commits from logs",
354                 safe => 0,
355                 rebuild => 0,
356         },
357         cgi => {
358                 type => "internal",
359                 default => 0,
360                 description => "run as a cgi",
361                 safe => 0,
362                 rebuild => 0,
363         },
364         cgi_disable_uploads => {
365                 type => "internal",
366                 default => 1,
367                 description => "whether CGI should accept file uploads",
368                 safe => 0,
369                 rebuild => 0,
370         },
371         post_commit => {
372                 type => "internal",
373                 default => 0,
374                 description => "run as a post-commit hook",
375                 safe => 0,
376                 rebuild => 0,
377         },
378         rebuild => {
379                 type => "internal",
380                 default => 0,
381                 description => "running in rebuild mode",
382                 safe => 0,
383                 rebuild => 0,
384         },
385         setup => {
386                 type => "internal",
387                 default => undef,
388                 description => "running in setup mode",
389                 safe => 0,
390                 rebuild => 0,
391         },
392         refresh => {
393                 type => "internal",
394                 default => 0,
395                 description => "running in refresh mode",
396                 safe => 0,
397                 rebuild => 0,
398         },
399         test_receive => {
400                 type => "internal",
401                 default => 0,
402                 description => "running in receive test mode",
403                 safe => 0,
404                 rebuild => 0,
405         },
406         getctime => {
407                 type => "internal",
408                 default => 0,
409                 description => "running in getctime mode",
410                 safe => 0,
411                 rebuild => 0,
412         },
413         w3mmode => {
414                 type => "internal",
415                 default => 0,
416                 description => "running in w3mmode",
417                 safe => 0,
418                 rebuild => 0,
419         },
420         wikistatedir => {
421                 type => "internal",
422                 default => undef,
423                 description => "path to the .ikiwiki directory holding ikiwiki state",
424                 safe => 0,
425                 rebuild => 0,
426         },
427         setupfile => {
428                 type => "internal",
429                 default => undef,
430                 description => "path to setup file",
431                 safe => 0,
432                 rebuild => 0,
433         },
434         allow_symlinks_before_srcdir => {
435                 type => "boolean",
436                 default => 0,
437                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
438                 safe => 0,
439                 rebuild => 0,
440         },
443 sub defaultconfig () {
444         my %s=getsetup();
445         my @ret;
446         foreach my $key (keys %s) {
447                 push @ret, $key, $s{$key}->{default};
448         }
449         use Data::Dumper;
450         return @ret;
453 sub checkconfig () {
454         # locale stuff; avoid LC_ALL since it overrides everything
455         if (defined $ENV{LC_ALL}) {
456                 $ENV{LANG} = $ENV{LC_ALL};
457                 delete $ENV{LC_ALL};
458         }
459         if (defined $config{locale}) {
460                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
461                         $ENV{LANG}=$config{locale};
462                         define_gettext();
463                 }
464         }
465                 
466         if (! defined $config{wiki_file_regexp}) {
467                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
468         }
470         if (ref $config{ENV} eq 'HASH') {
471                 foreach my $val (keys %{$config{ENV}}) {
472                         $ENV{$val}=$config{ENV}{$val};
473                 }
474         }
476         if ($config{w3mmode}) {
477                 eval q{use Cwd q{abs_path}};
478                 error($@) if $@;
479                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
480                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
481                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
482                         unless $config{cgiurl} =~ m!file:///!;
483                 $config{url}="file://".$config{destdir};
484         }
486         if ($config{cgi} && ! length $config{url}) {
487                 error(gettext("Must specify url to wiki with --url when using --cgi"));
488         }
489         
490         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
491                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
493         if (defined $config{umask}) {
494                 umask(possibly_foolish_untaint($config{umask}));
495         }
497         run_hooks(checkconfig => sub { shift->() });
499         return 1;
502 sub listplugins () {
503         my %ret;
505         foreach my $dir (@INC, $config{libdir}) {
506                 next unless defined $dir && length $dir;
507                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
508                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
509                         $ret{$plugin}=1;
510                 }
511         }
512         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
513                 next unless defined $dir && length $dir;
514                 foreach my $file (glob("$dir/plugins/*")) {
515                         $ret{basename($file)}=1 if -x $file;
516                 }
517         }
519         return keys %ret;
522 sub loadplugins () {
523         if (defined $config{libdir} && length $config{libdir}) {
524                 unshift @INC, possibly_foolish_untaint($config{libdir});
525         }
527         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
528                 loadplugin($plugin);
529         }
530         
531         if ($config{rcs}) {
532                 if (exists $IkiWiki::hooks{rcs}) {
533                         error(gettext("cannot use multiple rcs plugins"));
534                 }
535                 loadplugin($config{rcs});
536         }
537         if (! exists $IkiWiki::hooks{rcs}) {
538                 loadplugin("norcs");
539         }
541         run_hooks(getopt => sub { shift->() });
542         if (grep /^-/, @ARGV) {
543                 print STDERR "Unknown option (or missing parameter): $_\n"
544                         foreach grep /^-/, @ARGV;
545                 usage();
546         }
548         return 1;
551 sub loadplugin ($) {
552         my $plugin=shift;
554         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
556         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
557                          "$installdir/lib/ikiwiki") {
558                 if (defined $dir && -x "$dir/plugins/$plugin") {
559                         eval { require IkiWiki::Plugin::external };
560                         if ($@) {
561                                 my $reason=$@;
562                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
563                         }
564                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
565                         $loaded_plugins{$plugin}=1;
566                         return 1;
567                 }
568         }
570         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
571         eval qq{use $mod};
572         if ($@) {
573                 error("Failed to load plugin $mod: $@");
574         }
575         $loaded_plugins{$plugin}=1;
576         return 1;
579 sub error ($;$) {
580         my $message=shift;
581         my $cleaner=shift;
582         log_message('err' => $message) if $config{syslog};
583         if (defined $cleaner) {
584                 $cleaner->();
585         }
586         die $message."\n";
589 sub debug ($) {
590         return unless $config{verbose};
591         return log_message(debug => @_);
594 my $log_open=0;
595 sub log_message ($$) {
596         my $type=shift;
598         if ($config{syslog}) {
599                 require Sys::Syslog;
600                 if (! $log_open) {
601                         Sys::Syslog::setlogsock('unix');
602                         Sys::Syslog::openlog('ikiwiki', '', 'user');
603                         $log_open=1;
604                 }
605                 return eval {
606                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
607                 };
608         }
609         elsif (! $config{cgi}) {
610                 return print "@_\n";
611         }
612         else {
613                 return print STDERR "@_\n";
614         }
617 sub possibly_foolish_untaint ($) {
618         my $tainted=shift;
619         my ($untainted)=$tainted=~/(.*)/s;
620         return $untainted;
623 sub basename ($) {
624         my $file=shift;
626         $file=~s!.*/+!!;
627         return $file;
630 sub dirname ($) {
631         my $file=shift;
633         $file=~s!/*[^/]+$!!;
634         return $file;
637 sub isinternal ($) {
638         my $page=shift;
639         return exists $pagesources{$page} &&
640                 $pagesources{$page} =~ /\._([^.]+)$/;
643 sub pagetype ($) {
644         my $file=shift;
645         
646         if ($file =~ /\.([^.]+)$/) {
647                 return $1 if exists $hooks{htmlize}{$1};
648         }
649         my $base=basename($file);
650         if (exists $hooks{htmlize}{$base} &&
651             $hooks{htmlize}{$base}{noextension}) {
652                 return $base;
653         }
654         return;
657 sub pagename ($) {
658         my $file=shift;
660         my $type=pagetype($file);
661         my $page=$file;
662         $page=~s/\Q.$type\E*$//
663                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
664                         && !$hooks{htmlize}{$type}{noextension};
665         if ($config{indexpages} && $page=~/(.*)\/index$/) {
666                 $page=$1;
667         }
668         return $page;
671 sub newpagefile ($$) {
672         my $page=shift;
673         my $type=shift;
675         if (! $config{indexpages} || $page eq 'index') {
676                 return $page.".".$type;
677         }
678         else {
679                 return $page."/index.".$type;
680         }
683 sub targetpage ($$;$) {
684         my $page=shift;
685         my $ext=shift;
686         my $filename=shift;
687         
688         if (defined $filename) {
689                 return $page."/".$filename.".".$ext;
690         }
691         elsif (! $config{usedirs} || $page eq 'index') {
692                 return $page.".".$ext;
693         }
694         else {
695                 return $page."/index.".$ext;
696         }
699 sub htmlpage ($) {
700         my $page=shift;
701         
702         return targetpage($page, $config{htmlext});
705 sub srcfile_stat {
706         my $file=shift;
707         my $nothrow=shift;
709         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
710         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
711                 return "$dir/$file", stat(_) if -e "$dir/$file";
712         }
713         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
714         return;
717 sub srcfile ($;$) {
718         return (srcfile_stat(@_))[0];
721 sub add_underlay ($) {
722         my $dir=shift;
724         if ($dir !~ /^\//) {
725                 $dir="$config{underlaydirbase}/$dir";
726         }
728         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
729                 unshift @{$config{underlaydirs}}, $dir;
730         }
732         return 1;
735 sub readfile ($;$$) {
736         my $file=shift;
737         my $binary=shift;
738         my $wantfd=shift;
740         if (-l $file) {
741                 error("cannot read a symlink ($file)");
742         }
743         
744         local $/=undef;
745         open (my $in, "<", $file) || error("failed to read $file: $!");
746         binmode($in) if ($binary);
747         return \*$in if $wantfd;
748         my $ret=<$in>;
749         # check for invalid utf-8, and toss it back to avoid crashes
750         if (! utf8::valid($ret)) {
751                 $ret=encode_utf8($ret);
752         }
753         close $in || error("failed to read $file: $!");
754         return $ret;
757 sub prep_writefile ($$) {
758         my $file=shift;
759         my $destdir=shift;
760         
761         my $test=$file;
762         while (length $test) {
763                 if (-l "$destdir/$test") {
764                         error("cannot write to a symlink ($test)");
765                 }
766                 $test=dirname($test);
767         }
769         my $dir=dirname("$destdir/$file");
770         if (! -d $dir) {
771                 my $d="";
772                 foreach my $s (split(m!/+!, $dir)) {
773                         $d.="$s/";
774                         if (! -d $d) {
775                                 mkdir($d) || error("failed to create directory $d: $!");
776                         }
777                 }
778         }
780         return 1;
783 sub writefile ($$$;$$) {
784         my $file=shift; # can include subdirs
785         my $destdir=shift; # directory to put file in
786         my $content=shift;
787         my $binary=shift;
788         my $writer=shift;
789         
790         prep_writefile($file, $destdir);
791         
792         my $newfile="$destdir/$file.ikiwiki-new";
793         if (-l $newfile) {
794                 error("cannot write to a symlink ($newfile)");
795         }
796         
797         my $cleanup = sub { unlink($newfile) };
798         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
799         binmode($out) if ($binary);
800         if ($writer) {
801                 $writer->(\*$out, $cleanup);
802         }
803         else {
804                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
805         }
806         close $out || error("failed saving $newfile: $!", $cleanup);
807         rename($newfile, "$destdir/$file") || 
808                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
810         return 1;
813 my %cleared;
814 sub will_render ($$;$) {
815         my $page=shift;
816         my $dest=shift;
817         my $clear=shift;
819         # Important security check.
820         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
821             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
822                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
823         }
825         if (! $clear || $cleared{$page}) {
826                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
827         }
828         else {
829                 foreach my $old (@{$renderedfiles{$page}}) {
830                         delete $destsources{$old};
831                 }
832                 $renderedfiles{$page}=[$dest];
833                 $cleared{$page}=1;
834         }
835         $destsources{$dest}=$page;
837         return 1;
840 sub bestlink ($$) {
841         my $page=shift;
842         my $link=shift;
843         
844         my $cwd=$page;
845         if ($link=~s/^\/+//) {
846                 # absolute links
847                 $cwd="";
848         }
849         $link=~s/\/$//;
851         do {
852                 my $l=$cwd;
853                 $l.="/" if length $l;
854                 $l.=$link;
856                 if (exists $links{$l}) {
857                         return $l;
858                 }
859                 elsif (exists $pagecase{lc $l}) {
860                         return $pagecase{lc $l};
861                 }
862         } while $cwd=~s{/?[^/]+$}{};
864         if (length $config{userdir}) {
865                 my $l = "$config{userdir}/".lc($link);
866                 if (exists $links{$l}) {
867                         return $l;
868                 }
869                 elsif (exists $pagecase{lc $l}) {
870                         return $pagecase{lc $l};
871                 }
872         }
874         #print STDERR "warning: page $page, broken link: $link\n";
875         return "";
878 sub isinlinableimage ($) {
879         my $file=shift;
880         
881         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
884 sub pagetitle ($;$) {
885         my $page=shift;
886         my $unescaped=shift;
888         if ($unescaped) {
889                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
890         }
891         else {
892                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
893         }
895         return $page;
898 sub titlepage ($) {
899         my $title=shift;
900         # support use w/o %config set
901         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
902         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
903         return $title;
906 sub linkpage ($) {
907         my $link=shift;
908         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
909         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
910         return $link;
913 sub cgiurl (@) {
914         my %params=@_;
916         return $config{cgiurl}."?".
917                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
920 sub baseurl (;$) {
921         my $page=shift;
923         return "$config{url}/" if ! defined $page;
924         
925         $page=htmlpage($page);
926         $page=~s/[^\/]+$//;
927         $page=~s/[^\/]+\//..\//g;
928         return $page;
931 sub abs2rel ($$) {
932         # Work around very innefficient behavior in File::Spec if abs2rel
933         # is passed two relative paths. It's much faster if paths are
934         # absolute! (Debian bug #376658; fixed in debian unstable now)
935         my $path="/".shift;
936         my $base="/".shift;
938         require File::Spec;
939         my $ret=File::Spec->abs2rel($path, $base);
940         $ret=~s/^// if defined $ret;
941         return $ret;
944 sub displaytime ($;$) {
945         # Plugins can override this function to mark up the time to
946         # display.
947         return '<span class="date">'.formattime(@_).'</span>';
950 sub formattime ($;$) {
951         # Plugins can override this function to format the time.
952         my $time=shift;
953         my $format=shift;
954         if (! defined $format) {
955                 $format=$config{timeformat};
956         }
958         # strftime doesn't know about encodings, so make sure
959         # its output is properly treated as utf8
960         return decode_utf8(POSIX::strftime($format, localtime($time)));
963 sub beautify_urlpath ($) {
964         my $url=shift;
966         # Ensure url is not an empty link, and if necessary,
967         # add ./ to avoid colon confusion.
968         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
969                 $url="./$url";
970         }
972         if ($config{usedirs}) {
973                 $url =~ s!/index.$config{htmlext}$!/!;
974         }
976         return $url;
979 sub urlto ($$;$) {
980         my $to=shift;
981         my $from=shift;
982         my $absolute=shift;
983         
984         if (! length $to) {
985                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
986         }
988         if (! $destsources{$to}) {
989                 $to=htmlpage($to);
990         }
992         if ($absolute) {
993                 return $config{url}.beautify_urlpath("/".$to);
994         }
996         my $link = abs2rel($to, dirname(htmlpage($from)));
998         return beautify_urlpath($link);
1001 sub htmllink ($$$;@) {
1002         my $lpage=shift; # the page doing the linking
1003         my $page=shift; # the page that will contain the link (different for inline)
1004         my $link=shift;
1005         my %opts=@_;
1007         $link=~s/\/$//;
1009         my $bestlink;
1010         if (! $opts{forcesubpage}) {
1011                 $bestlink=bestlink($lpage, $link);
1012         }
1013         else {
1014                 $bestlink="$lpage/".lc($link);
1015         }
1017         my $linktext;
1018         if (defined $opts{linktext}) {
1019                 $linktext=$opts{linktext};
1020         }
1021         else {
1022                 $linktext=pagetitle(basename($link));
1023         }
1024         
1025         return "<span class=\"selflink\">$linktext</span>"
1026                 if length $bestlink && $page eq $bestlink &&
1027                    ! defined $opts{anchor};
1028         
1029         if (! $destsources{$bestlink}) {
1030                 $bestlink=htmlpage($bestlink);
1032                 if (! $destsources{$bestlink}) {
1033                         return $linktext unless length $config{cgiurl};
1034                         return "<span class=\"createlink\"><a href=\"".
1035                                 cgiurl(
1036                                         do => "create",
1037                                         page => lc($link),
1038                                         from => $lpage
1039                                 ).
1040                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
1041                 }
1042         }
1043         
1044         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1045         $bestlink=beautify_urlpath($bestlink);
1046         
1047         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1048                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1049         }
1051         if (defined $opts{anchor}) {
1052                 $bestlink.="#".$opts{anchor};
1053         }
1055         my @attrs;
1056         if (defined $opts{rel}) {
1057                 push @attrs, ' rel="'.$opts{rel}.'"';
1058         }
1059         if (defined $opts{class}) {
1060                 push @attrs, ' class="'.$opts{class}.'"';
1061         }
1063         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1066 sub userlink ($) {
1067         my $user=shift;
1069         my $oiduser=eval { openiduser($user) };
1070         if (defined $oiduser) {
1071                 return "<a href=\"$user\">$oiduser</a>";
1072         }
1073         else {
1074                 eval q{use CGI 'escapeHTML'};
1075                 error($@) if $@;
1077                 return htmllink("", "", escapeHTML(
1078                         length $config{userdir} ? $config{userdir}."/".$user : $user
1079                 ), noimageinline => 1);
1080         }
1083 sub htmlize ($$$$) {
1084         my $page=shift;
1085         my $destpage=shift;
1086         my $type=shift;
1087         my $content=shift;
1088         
1089         my $oneline = $content !~ /\n/;
1091         if (exists $hooks{htmlize}{$type}) {
1092                 $content=$hooks{htmlize}{$type}{call}->(
1093                         page => $page,
1094                         content => $content,
1095                 );
1096         }
1097         else {
1098                 error("htmlization of $type not supported");
1099         }
1101         run_hooks(sanitize => sub {
1102                 $content=shift->(
1103                         page => $page,
1104                         destpage => $destpage,
1105                         content => $content,
1106                 );
1107         });
1108         
1109         if ($oneline) {
1110                 # hack to get rid of enclosing junk added by markdown
1111                 # and other htmlizers
1112                 $content=~s/^<p>//i;
1113                 $content=~s/<\/p>$//i;
1114                 chomp $content;
1115         }
1117         return $content;
1120 sub linkify ($$$) {
1121         my $page=shift;
1122         my $destpage=shift;
1123         my $content=shift;
1125         run_hooks(linkify => sub {
1126                 $content=shift->(
1127                         page => $page,
1128                         destpage => $destpage,
1129                         content => $content,
1130                 );
1131         });
1132         
1133         return $content;
1136 our %preprocessing;
1137 our $preprocess_preview=0;
1138 sub preprocess ($$$;$$) {
1139         my $page=shift; # the page the data comes from
1140         my $destpage=shift; # the page the data will appear in (different for inline)
1141         my $content=shift;
1142         my $scan=shift;
1143         my $preview=shift;
1145         # Using local because it needs to be set within any nested calls
1146         # of this function.
1147         local $preprocess_preview=$preview if defined $preview;
1149         my $handle=sub {
1150                 my $escape=shift;
1151                 my $prefix=shift;
1152                 my $command=shift;
1153                 my $params=shift;
1154                 $params="" if ! defined $params;
1156                 if (length $escape) {
1157                         return "[[$prefix$command $params]]";
1158                 }
1159                 elsif (exists $hooks{preprocess}{$command}) {
1160                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1161                         # Note: preserve order of params, some plugins may
1162                         # consider it significant.
1163                         my @params;
1164                         while ($params =~ m{
1165                                 (?:([-\w]+)=)?          # 1: named parameter key?
1166                                 (?:
1167                                         """(.*?)"""     # 2: triple-quoted value
1168                                 |
1169                                         "([^"]+)"       # 3: single-quoted value
1170                                 |
1171                                         (\S+)           # 4: unquoted value
1172                                 )
1173                                 (?:\s+|$)               # delimiter to next param
1174                         }sgx) {
1175                                 my $key=$1;
1176                                 my $val;
1177                                 if (defined $2) {
1178                                         $val=$2;
1179                                         $val=~s/\r\n/\n/mg;
1180                                         $val=~s/^\n+//g;
1181                                         $val=~s/\n+$//g;
1182                                 }
1183                                 elsif (defined $3) {
1184                                         $val=$3;
1185                                 }
1186                                 elsif (defined $4) {
1187                                         $val=$4;
1188                                 }
1190                                 if (defined $key) {
1191                                         push @params, $key, $val;
1192                                 }
1193                                 else {
1194                                         push @params, $val, '';
1195                                 }
1196                         }
1197                         if ($preprocessing{$page}++ > 3) {
1198                                 # Avoid loops of preprocessed pages preprocessing
1199                                 # other pages that preprocess them, etc.
1200                                 return "[[!$command <span class=\"error\">".
1201                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1202                                                 $page, $preprocessing{$page}).
1203                                         "</span>]]";
1204                         }
1205                         my $ret;
1206                         if (! $scan) {
1207                                 $ret=eval {
1208                                         $hooks{preprocess}{$command}{call}->(
1209                                                 @params,
1210                                                 page => $page,
1211                                                 destpage => $destpage,
1212                                                 preview => $preprocess_preview,
1213                                         );
1214                                 };
1215                                 if ($@) {
1216                                         chomp $@;
1217                                         $ret="[[!$command <span class=\"error\">".
1218                                                 gettext("Error").": $@"."</span>]]";
1219                                 }
1220                         }
1221                         else {
1222                                 # use void context during scan pass
1223                                 eval {
1224                                         $hooks{preprocess}{$command}{call}->(
1225                                                 @params,
1226                                                 page => $page,
1227                                                 destpage => $destpage,
1228                                                 preview => $preprocess_preview,
1229                                         );
1230                                 };
1231                                 $ret="";
1232                         }
1233                         $preprocessing{$page}--;
1234                         return $ret;
1235                 }
1236                 else {
1237                         return "[[$prefix$command $params]]";
1238                 }
1239         };
1240         
1241         my $regex;
1242         if ($config{prefix_directives}) {
1243                 $regex = qr{
1244                         (\\?)           # 1: escape?
1245                         \[\[(!)         # directive open; 2: prefix
1246                         ([-\w]+)        # 3: command
1247                         (               # 4: the parameters..
1248                                 \s+     # Must have space if parameters present
1249                                 (?:
1250                                         (?:[-\w]+=)?            # named parameter key?
1251                                         (?:
1252                                                 """.*?"""       # triple-quoted value
1253                                                 |
1254                                                 "[^"]+"         # single-quoted value
1255                                                 |
1256                                                 [^"\s\]]+       # unquoted value
1257                                         )
1258                                         \s*                     # whitespace or end
1259                                                                 # of directive
1260                                 )
1261                         *)?             # 0 or more parameters
1262                         \]\]            # directive closed
1263                 }sx;
1264         }
1265         else {
1266                 $regex = qr{
1267                         (\\?)           # 1: escape?
1268                         \[\[(!?)        # directive open; 2: optional prefix
1269                         ([-\w]+)        # 3: command
1270                         \s+
1271                         (               # 4: the parameters..
1272                                 (?:
1273                                         (?:[-\w]+=)?            # named parameter key?
1274                                         (?:
1275                                                 """.*?"""       # triple-quoted value
1276                                                 |
1277                                                 "[^"]+"         # single-quoted value
1278                                                 |
1279                                                 [^"\s\]]+       # unquoted value
1280                                         )
1281                                         \s*                     # whitespace or end
1282                                                                 # of directive
1283                                 )
1284                         *)              # 0 or more parameters
1285                         \]\]            # directive closed
1286                 }sx;
1287         }
1289         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1290         return $content;
1293 sub filter ($$$) {
1294         my $page=shift;
1295         my $destpage=shift;
1296         my $content=shift;
1298         run_hooks(filter => sub {
1299                 $content=shift->(page => $page, destpage => $destpage, 
1300                         content => $content);
1301         });
1303         return $content;
1306 sub indexlink () {
1307         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1310 sub check_canedit ($$$;$) {
1311         my $page=shift;
1312         my $q=shift;
1313         my $session=shift;
1314         my $nonfatal=shift;
1315         
1316         my $canedit;
1317         run_hooks(canedit => sub {
1318                 return if defined $canedit;
1319                 my $ret=shift->($page, $q, $session);
1320                 if (defined $ret) {
1321                         if ($ret eq "") {
1322                                 $canedit=1;
1323                         }
1324                         elsif (ref $ret eq 'CODE') {
1325                                 $ret->() unless $nonfatal;
1326                                 $canedit=0;
1327                         }
1328                         elsif (defined $ret) {
1329                                 error($ret) unless $nonfatal;
1330                                 $canedit=0;
1331                         }
1332                 }
1333         });
1334         return defined $canedit ? $canedit : 1;
1337 sub check_content (@) {
1338         my %params=@_;
1339         
1340         return 1 if ! exists $hooks{checkcontent}; # optimisation
1342         if (exists $pagesources{$params{page}}) {
1343                 my @diff;
1344                 my %old=map { $_ => 1 }
1345                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1346                 foreach my $line (split("\n", $params{content})) {
1347                         push @diff, $line if ! exists $old{$_};
1348                 }
1349                 $params{content}=join("\n", @diff);
1350         }
1352         my $ok;
1353         run_hooks(checkcontent => sub {
1354                 return if defined $ok;
1355                 my $ret=shift->(%params);
1356                 if (defined $ret) {
1357                         if ($ret eq "") {
1358                                 $ok=1;
1359                         }
1360                         elsif (ref $ret eq 'CODE') {
1361                                 $ret->() unless $params{nonfatal};
1362                                 $ok=0;
1363                         }
1364                         elsif (defined $ret) {
1365                                 error($ret) unless $params{nonfatal};
1366                                 $ok=0;
1367                         }
1368                 }
1370         });
1371         return defined $ok ? $ok : 1;
1374 my $wikilock;
1376 sub lockwiki () {
1377         # Take an exclusive lock on the wiki to prevent multiple concurrent
1378         # run issues. The lock will be dropped on program exit.
1379         if (! -d $config{wikistatedir}) {
1380                 mkdir($config{wikistatedir});
1381         }
1382         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1383                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1384         if (! flock($wikilock, 2)) { # LOCK_EX
1385                 error("failed to get lock");
1386         }
1387         return 1;
1390 sub unlockwiki () {
1391         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1392         return close($wikilock) if $wikilock;
1393         return;
1396 my $commitlock;
1398 sub commit_hook_enabled () {
1399         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1400                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1401         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1402                 close($commitlock) || error("failed closing commitlock: $!");
1403                 return 0;
1404         }
1405         close($commitlock) || error("failed closing commitlock: $!");
1406         return 1;
1409 sub disable_commit_hook () {
1410         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1411                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1412         if (! flock($commitlock, 2)) { # LOCK_EX
1413                 error("failed to get commit lock");
1414         }
1415         return 1;
1418 sub enable_commit_hook () {
1419         return close($commitlock) if $commitlock;
1420         return;
1423 sub loadindex () {
1424         %oldrenderedfiles=%pagectime=();
1425         if (! $config{rebuild}) {
1426                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1427                 %destsources=%renderedfiles=%pagecase=%pagestate=();
1428         }
1429         my $in;
1430         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1431                 if (-e "$config{wikistatedir}/index") {
1432                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1433                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1434                 }
1435                 else {
1436                         return;
1437                 }
1438         }
1440         my $index=Storable::fd_retrieve($in);
1441         if (! defined $index) {
1442                 return 0;
1443         }
1445         my $pages;
1446         if (exists $index->{version} && ! ref $index->{version}) {
1447                 $pages=$index->{page};
1448                 %wikistate=%{$index->{state}};
1449         }
1450         else {
1451                 $pages=$index;
1452                 %wikistate=();
1453         }
1455         foreach my $src (keys %$pages) {
1456                 my $d=$pages->{$src};
1457                 my $page=pagename($src);
1458                 $pagectime{$page}=$d->{ctime};
1459                 if (! $config{rebuild}) {
1460                         $pagesources{$page}=$src;
1461                         $pagemtime{$page}=$d->{mtime};
1462                         $renderedfiles{$page}=$d->{dest};
1463                         if (exists $d->{links} && ref $d->{links}) {
1464                                 $links{$page}=$d->{links};
1465                                 $oldlinks{$page}=[@{$d->{links}}];
1466                         }
1467                         if (exists $d->{depends}) {
1468                                 $depends{$page}=$d->{depends};
1469                         }
1470                         if (exists $d->{state}) {
1471                                 $pagestate{$page}=$d->{state};
1472                         }
1473                 }
1474                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1475         }
1476         foreach my $page (keys %pagesources) {
1477                 $pagecase{lc $page}=$page;
1478         }
1479         foreach my $page (keys %renderedfiles) {
1480                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1481         }
1482         return close($in);
1485 sub saveindex () {
1486         run_hooks(savestate => sub { shift->() });
1488         my %hookids;
1489         foreach my $type (keys %hooks) {
1490                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1491         }
1492         my @hookids=keys %hookids;
1494         if (! -d $config{wikistatedir}) {
1495                 mkdir($config{wikistatedir});
1496         }
1497         my $newfile="$config{wikistatedir}/indexdb.new";
1498         my $cleanup = sub { unlink($newfile) };
1499         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1501         my %index;
1502         foreach my $page (keys %pagemtime) {
1503                 next unless $pagemtime{$page};
1504                 my $src=$pagesources{$page};
1506                 $index{page}{$src}={
1507                         ctime => $pagectime{$page},
1508                         mtime => $pagemtime{$page},
1509                         dest => $renderedfiles{$page},
1510                         links => $links{$page},
1511                 };
1513                 if (exists $depends{$page}) {
1514                         $index{page}{$src}{depends} = $depends{$page};
1515                 }
1517                 if (exists $pagestate{$page}) {
1518                         foreach my $id (@hookids) {
1519                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1520                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1521                                 }
1522                         }
1523                 }
1524         }
1526         $index{state}={};
1527         foreach my $id (@hookids) {
1528                 foreach my $key (keys %{$wikistate{$id}}) {
1529                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1530                 }
1531         }
1532         
1533         $index{version}="3";
1534         my $ret=Storable::nstore_fd(\%index, $out);
1535         return if ! defined $ret || ! $ret;
1536         close $out || error("failed saving to $newfile: $!", $cleanup);
1537         rename($newfile, "$config{wikistatedir}/indexdb") ||
1538                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1539         
1540         return 1;
1543 sub template_file ($) {
1544         my $template=shift;
1546         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1547                 return "$dir/$template" if -e "$dir/$template";
1548         }
1549         return;
1552 sub template_params (@) {
1553         my $filename=template_file(shift);
1555         if (! defined $filename) {
1556                 return if wantarray;
1557                 return "";
1558         }
1560         my @ret=(
1561                 filter => sub {
1562                         my $text_ref = shift;
1563                         ${$text_ref} = decode_utf8(${$text_ref});
1564                 },
1565                 filename => $filename,
1566                 loop_context_vars => 1,
1567                 die_on_bad_params => 0,
1568                 @_
1569         );
1570         return wantarray ? @ret : {@ret};
1573 sub template ($;@) {
1574         require HTML::Template;
1575         return HTML::Template->new(template_params(@_));
1578 sub misctemplate ($$;@) {
1579         my $title=shift;
1580         my $pagebody=shift;
1581         
1582         my $template=template("misc.tmpl");
1583         $template->param(
1584                 title => $title,
1585                 indexlink => indexlink(),
1586                 wikiname => $config{wikiname},
1587                 pagebody => $pagebody,
1588                 baseurl => baseurl(),
1589                 @_,
1590         );
1591         run_hooks(pagetemplate => sub {
1592                 shift->(page => "", destpage => "", template => $template);
1593         });
1594         return $template->output;
1597 sub hook (@) {
1598         my %param=@_;
1599         
1600         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1601                 error 'hook requires type, call, and id parameters';
1602         }
1604         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1605         
1606         $hooks{$param{type}}{$param{id}}=\%param;
1607         return 1;
1610 sub run_hooks ($$) {
1611         # Calls the given sub for each hook of the given type,
1612         # passing it the hook function to call.
1613         my $type=shift;
1614         my $sub=shift;
1616         if (exists $hooks{$type}) {
1617                 my (@first, @middle, @last);
1618                 foreach my $id (keys %{$hooks{$type}}) {
1619                         if ($hooks{$type}{$id}{first}) {
1620                                 push @first, $id;
1621                         }
1622                         elsif ($hooks{$type}{$id}{last}) {
1623                                 push @last, $id;
1624                         }
1625                         else {
1626                                 push @middle, $id;
1627                         }
1628                 }
1629                 foreach my $id (@first, @middle, @last) {
1630                         $sub->($hooks{$type}{$id}{call});
1631                 }
1632         }
1634         return 1;
1637 sub rcs_update () {
1638         $hooks{rcs}{rcs_update}{call}->(@_);
1641 sub rcs_prepedit ($) {
1642         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1645 sub rcs_commit ($$$;$$) {
1646         $hooks{rcs}{rcs_commit}{call}->(@_);
1649 sub rcs_commit_staged ($$$) {
1650         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1653 sub rcs_add ($) {
1654         $hooks{rcs}{rcs_add}{call}->(@_);
1657 sub rcs_remove ($) {
1658         $hooks{rcs}{rcs_remove}{call}->(@_);
1661 sub rcs_rename ($$) {
1662         $hooks{rcs}{rcs_rename}{call}->(@_);
1665 sub rcs_recentchanges ($) {
1666         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1669 sub rcs_diff ($) {
1670         $hooks{rcs}{rcs_diff}{call}->(@_);
1673 sub rcs_getctime ($) {
1674         $hooks{rcs}{rcs_getctime}{call}->(@_);
1677 sub rcs_receive () {
1678         $hooks{rcs}{rcs_receive}{call}->();
1681 sub add_depends ($$) {
1682         my $page=shift;
1683         my $pagespec=shift;
1684         
1685         return unless pagespec_valid($pagespec);
1687         if (! exists $depends{$page}) {
1688                 $depends{$page}=$pagespec;
1689         }
1690         else {
1691                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1692         }
1694         return 1;
1697 sub file_pruned ($$) {
1698         require File::Spec;
1699         my $file=File::Spec->canonpath(shift);
1700         my $base=File::Spec->canonpath(shift);
1701         $file =~ s#^\Q$base\E/+##;
1703         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1704         return $file =~ m/$regexp/ && $file ne $base;
1707 sub define_gettext () {
1708         # If translation is needed, redefine the gettext function to do it.
1709         # Otherwise, it becomes a quick no-op.
1710         no warnings 'redefine';
1711         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1712             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1713             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1714                 *gettext=sub {
1715                         my $gettext_obj=eval q{
1716                                 use Locale::gettext q{textdomain};
1717                                 Locale::gettext->domain('ikiwiki')
1718                         };
1720                         if ($gettext_obj) {
1721                                 $gettext_obj->get(shift);
1722                         }
1723                         else {
1724                                 return shift;
1725                         }
1726                 };
1727         }
1728         else {
1729                 *gettext=sub { return shift };
1730         }
1733 sub gettext {
1734         define_gettext();
1735         gettext(@_);
1738 sub yesno ($) {
1739         my $val=shift;
1741         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1744 sub inject {
1745         # Injects a new function into the symbol table to replace an
1746         # exported function.
1747         my %params=@_;
1749         # This is deep ugly perl foo, beware.
1750         no strict;
1751         no warnings;
1752         if (! defined $params{parent}) {
1753                 $params{parent}='::';
1754                 $params{old}=\&{$params{name}};
1755                 $params{name}=~s/.*:://;
1756         }
1757         my $parent=$params{parent};
1758         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1759                 $ns = $params{parent} . $ns;
1760                 inject(%params, parent => $ns) unless $ns eq '::main::';
1761                 *{$ns . $params{name}} = $params{call}
1762                         if exists ${$ns}{$params{name}} &&
1763                            \&{${$ns}{$params{name}}} == $params{old};
1764         }
1765         use strict;
1766         use warnings;
1769 sub add_link ($$) {
1770         my $page=shift;
1771         my $link=shift;
1773         push @{$links{$page}}, $link
1774                 unless grep { $_ eq $link } @{$links{$page}};
1777 sub pagespec_merge ($$) {
1778         my $a=shift;
1779         my $b=shift;
1781         return $a if $a eq $b;
1782         return "($a) or ($b)";
1785 sub pagespec_translate ($) {
1786         my $spec=shift;
1788         # Convert spec to perl code.
1789         my $code="";
1790         my @data;
1791         while ($spec=~m{
1792                 \s*             # ignore whitespace
1793                 (               # 1: match a single word
1794                         \!              # !
1795                 |
1796                         \(              # (
1797                 |
1798                         \)              # )
1799                 |
1800                         \w+\([^\)]*\)   # command(params)
1801                 |
1802                         [^\s()]+        # any other text
1803                 )
1804                 \s*             # ignore whitespace
1805         }igx) {
1806                 my $word=$1;
1807                 if (lc $word eq 'and') {
1808                         $code.=' &&';
1809                 }
1810                 elsif (lc $word eq 'or') {
1811                         $code.=' ||';
1812                 }
1813                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1814                         $code.=' '.$word;
1815                 }
1816                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1817                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1818                                 push @data, $2;
1819                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1820                         }
1821                         else {
1822                                 push @data, qq{unknown function in pagespec "$word"};
1823                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1824                         }
1825                 }
1826                 else {
1827                         push @data, $word;
1828                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1829                 }
1830         }
1832         if (! length $code) {
1833                 $code="IkiWiki::FailReason->new('empty pagespec')";
1834         }
1836         no warnings;
1837         return eval 'sub { my $page=shift; '.$code.' }';
1840 sub pagespec_match ($$;@) {
1841         my $page=shift;
1842         my $spec=shift;
1843         my @params=@_;
1845         # Backwards compatability with old calling convention.
1846         if (@params == 1) {
1847                 unshift @params, 'location';
1848         }
1850         my $sub=pagespec_translate($spec);
1851         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1852                 if $@ || ! defined $sub;
1853         return $sub->($page, @params);
1856 sub pagespec_match_list ($$;@) {
1857         my $pages=shift;
1858         my $spec=shift;
1859         my @params=@_;
1861         my $sub=pagespec_translate($spec);
1862         error "syntax error in pagespec \"$spec\""
1863                 if $@ || ! defined $sub;
1864         
1865         my @ret;
1866         my $r;
1867         foreach my $page (@$pages) {
1868                 $r=$sub->($page, @params);
1869                 push @ret, $page if $r;
1870         }
1872         if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1873                 error(sprintf(gettext("cannot match pages: %s"), $r));
1874         }
1875         else {
1876                 return @ret;
1877         }
1880 sub pagespec_valid ($) {
1881         my $spec=shift;
1883         my $sub=pagespec_translate($spec);
1884         return ! $@;
1887 sub glob2re ($) {
1888         my $re=quotemeta(shift);
1889         $re=~s/\\\*/.*/g;
1890         $re=~s/\\\?/./g;
1891         return $re;
1894 package IkiWiki::FailReason;
1896 use overload (
1897         '""'    => sub { ${$_[0]} },
1898         '0+'    => sub { 0 },
1899         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1900         fallback => 1,
1901 );
1903 sub new {
1904         my $class = shift;
1905         my $value = shift;
1906         return bless \$value, $class;
1909 package IkiWiki::ErrorReason;
1911 our @ISA = 'IkiWiki::FailReason';
1913 package IkiWiki::SuccessReason;
1915 use overload (
1916         '""'    => sub { ${$_[0]} },
1917         '0+'    => sub { 1 },
1918         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1919         fallback => 1,
1920 );
1922 sub new {
1923         my $class = shift;
1924         my $value = shift;
1925         return bless \$value, $class;
1926 };
1928 package IkiWiki::PageSpec;
1930 sub derel ($$) {
1931         my $path=shift;
1932         my $from=shift;
1934         if ($path =~ m!^\./!) {
1935                 $from=~s#/?[^/]+$## if defined $from;
1936                 $path=~s#^\./##;
1937                 $path="$from/$path" if length $from;
1938         }
1940         return $path;
1943 sub match_glob ($$;@) {
1944         my $page=shift;
1945         my $glob=shift;
1946         my %params=@_;
1947         
1948         $glob=derel($glob, $params{location});
1950         my $regexp=IkiWiki::glob2re($glob);
1951         if ($page=~/^$regexp$/i) {
1952                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1953                         return IkiWiki::SuccessReason->new("$glob matches $page");
1954                 }
1955                 else {
1956                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1957                 }
1958         }
1959         else {
1960                 return IkiWiki::FailReason->new("$glob does not match $page");
1961         }
1964 sub match_internal ($$;@) {
1965         return match_glob($_[0], $_[1], @_, internal => 1)
1968 sub match_link ($$;@) {
1969         my $page=shift;
1970         my $link=lc(shift);
1971         my %params=@_;
1973         $link=derel($link, $params{location});
1974         my $from=exists $params{location} ? $params{location} : '';
1976         my $links = $IkiWiki::links{$page};
1977         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1978         my $bestlink = IkiWiki::bestlink($from, $link);
1979         foreach my $p (@{$links}) {
1980                 if (length $bestlink) {
1981                         return IkiWiki::SuccessReason->new("$page links to $link")
1982                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1983                 }
1984                 else {
1985                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1986                                 if match_glob($p, $link, %params);
1987                         $p=~s/^\///;
1988                         $link=~s/^\///;
1989                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1990                                 if match_glob($p, $link, %params);
1991                 }
1992         }
1993         return IkiWiki::FailReason->new("$page does not link to $link");
1996 sub match_backlink ($$;@) {
1997         return match_link($_[1], $_[0], @_);
2000 sub match_created_before ($$;@) {
2001         my $page=shift;
2002         my $testpage=shift;
2003         my %params=@_;
2004         
2005         $testpage=derel($testpage, $params{location});
2007         if (exists $IkiWiki::pagectime{$testpage}) {
2008                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2009                         return IkiWiki::SuccessReason->new("$page created before $testpage");
2010                 }
2011                 else {
2012                         return IkiWiki::FailReason->new("$page not created before $testpage");
2013                 }
2014         }
2015         else {
2016                 return IkiWiki::FailReason->new("$testpage has no ctime");
2017         }
2020 sub match_created_after ($$;@) {
2021         my $page=shift;
2022         my $testpage=shift;
2023         my %params=@_;
2024         
2025         $testpage=derel($testpage, $params{location});
2027         if (exists $IkiWiki::pagectime{$testpage}) {
2028                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2029                         return IkiWiki::SuccessReason->new("$page created after $testpage");
2030                 }
2031                 else {
2032                         return IkiWiki::FailReason->new("$page not created after $testpage");
2033                 }
2034         }
2035         else {
2036                 return IkiWiki::FailReason->new("$testpage has no ctime");
2037         }
2040 sub match_creation_day ($$;@) {
2041         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2042                 return IkiWiki::SuccessReason->new('creation_day matched');
2043         }
2044         else {
2045                 return IkiWiki::FailReason->new('creation_day did not match');
2046         }
2049 sub match_creation_month ($$;@) {
2050         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2051                 return IkiWiki::SuccessReason->new('creation_month matched');
2052         }
2053         else {
2054                 return IkiWiki::FailReason->new('creation_month did not match');
2055         }
2058 sub match_creation_year ($$;@) {
2059         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2060                 return IkiWiki::SuccessReason->new('creation_year matched');
2061         }
2062         else {
2063                 return IkiWiki::FailReason->new('creation_year did not match');
2064         }
2067 sub match_user ($$;@) {
2068         shift;
2069         my $user=shift;
2070         my %params=@_;
2071         
2072         if (! exists $params{user}) {
2073                 return IkiWiki::ErrorReason->new("no user specified");
2074         }
2076         if (defined $params{user} && lc $params{user} eq lc $user) {
2077                 return IkiWiki::SuccessReason->new("user is $user");
2078         }
2079         elsif (! defined $params{user}) {
2080                 return IkiWiki::FailReason->new("not logged in");
2081         }
2082         else {
2083                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2084         }
2087 sub match_admin ($$;@) {
2088         shift;
2089         shift;
2090         my %params=@_;
2091         
2092         if (! exists $params{user}) {
2093                 return IkiWiki::ErrorReason->new("no user specified");
2094         }
2096         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2097                 return IkiWiki::SuccessReason->new("user is an admin");
2098         }
2099         elsif (! defined $params{user}) {
2100                 return IkiWiki::FailReason->new("not logged in");
2101         }
2102         else {
2103                 return IkiWiki::FailReason->new("user is not an admin");
2104         }
2107 sub match_ip ($$;@) {
2108         shift;
2109         my $ip=shift;
2110         my %params=@_;
2111         
2112         if (! exists $params{ip}) {
2113                 return IkiWiki::ErrorReason->new("no IP specified");
2114         }
2116         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2117                 return IkiWiki::SuccessReason->new("IP is $ip");
2118         }
2119         else {
2120                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2121         }