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