9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %renderedfiles %oldrenderedfiles %pagesources
16 %destsources %depends %hooks %forcerebuild $gettext_obj};
18 use Exporter q{import};
19 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
20 bestlink htmllink readfile writefile pagetype srcfile pagename
21 displaytime will_render gettext urlto targetpage
23 %config %links %pagestate %renderedfiles
24 %pagesources %destsources);
25 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
26 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
27 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 memoize("pagespec_translate");
33 memoize("file_pruned");
35 sub defaultconfig () { #{{{
37 wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
38 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
39 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
42 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
43 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
47 default_pageext => "mdwn",
68 gitorigin_branch => "origin",
69 gitmaster_branch => "master",
73 templatedir => "$installdir/share/ikiwiki/templates",
74 underlaydir => "$installdir/share/ikiwiki/basewiki",
79 plugin => [qw{mdwn link inline htmlscrubber passwordauth openid
80 signinedit lockedit conditional recentchanges
90 account_creation_password => "",
91 prefix_directives => 0,
93 cgi_disable_uploads => 1,
96 sub checkconfig () { #{{{
97 # locale stuff; avoid LC_ALL since it overrides everything
98 if (defined $ENV{LC_ALL}) {
99 $ENV{LANG} = $ENV{LC_ALL};
102 if (defined $config{locale}) {
103 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
104 $ENV{LANG}=$config{locale};
109 if (ref $config{ENV} eq 'HASH') {
110 foreach my $val (keys %{$config{ENV}}) {
111 $ENV{$val}=$config{ENV}{$val};
115 if ($config{w3mmode}) {
116 eval q{use Cwd q{abs_path}};
118 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
119 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
120 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
121 unless $config{cgiurl} =~ m!file:///!;
122 $config{url}="file://".$config{destdir};
125 if ($config{cgi} && ! length $config{url}) {
126 error(gettext("Must specify url to wiki with --url when using --cgi"));
129 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
130 unless exists $config{wikistatedir};
133 eval qq{use IkiWiki::Rcs::$config{rcs}};
135 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
139 require IkiWiki::Rcs::Stub;
142 if (exists $config{umask}) {
143 umask(possibly_foolish_untaint($config{umask}));
146 run_hooks(checkconfig => sub { shift->() });
151 sub loadplugins () { #{{{
152 if (defined $config{libdir}) {
153 unshift @INC, possibly_foolish_untaint($config{libdir});
156 loadplugin($_) foreach @{$config{plugin}};
158 run_hooks(getopt => sub { shift->() });
159 if (grep /^-/, @ARGV) {
160 print STDERR "Unknown option: $_\n"
161 foreach grep /^-/, @ARGV;
168 sub loadplugin ($) { #{{{
171 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
173 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
174 "$installdir/lib/ikiwiki") {
175 if (defined $dir && -x "$dir/plugins/$plugin") {
176 require IkiWiki::Plugin::external;
177 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
182 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
185 error("Failed to load plugin $mod: $@");
190 sub error ($;$) { #{{{
193 log_message('err' => $message) if $config{syslog};
194 if (defined $cleaner) {
201 return unless $config{verbose};
202 return log_message(debug => @_);
206 sub log_message ($$) { #{{{
209 if ($config{syslog}) {
212 Sys::Syslog::setlogsock('unix');
213 Sys::Syslog::openlog('ikiwiki', '', 'user');
217 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
220 elsif (! $config{cgi}) {
224 return print STDERR "@_\n";
228 sub possibly_foolish_untaint ($) { #{{{
230 my ($untainted)=$tainted=~/(.*)/s;
234 sub basename ($) { #{{{
241 sub dirname ($) { #{{{
248 sub pagetype ($) { #{{{
251 if ($page =~ /\.([^.]+)$/) {
252 return $1 if exists $hooks{htmlize}{$1};
257 sub isinternal ($) { #{{{
259 return exists $pagesources{$page} &&
260 $pagesources{$page} =~ /\._([^.]+)$/;
263 sub pagename ($) { #{{{
266 my $type=pagetype($file);
268 $page=~s/\Q.$type\E*$// if defined $type;
272 sub targetpage ($$) { #{{{
276 if (! $config{usedirs} || $page =~ /^index$/ ) {
277 return $page.".".$ext;
279 return $page."/index.".$ext;
283 sub htmlpage ($) { #{{{
286 return targetpage($page, $config{htmlext});
289 sub srcfile_stat { #{{{
293 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
294 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
295 return "$dir/$file", stat(_) if -e "$dir/$file";
297 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
301 sub srcfile ($;$) { #{{{
302 return (srcfile_stat(@_))[0];
305 sub add_underlay ($) { #{{{
309 unshift @{$config{underlaydirs}}, $dir;
312 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
318 sub readfile ($;$$) { #{{{
324 error("cannot read a symlink ($file)");
328 open (my $in, "<", $file) || error("failed to read $file: $!");
329 binmode($in) if ($binary);
330 return \*$in if $wantfd;
332 close $in || error("failed to read $file: $!");
336 sub prep_writefile ($$) { #{{{
341 while (length $test) {
342 if (-l "$destdir/$test") {
343 error("cannot write to a symlink ($test)");
345 $test=dirname($test);
348 my $dir=dirname("$destdir/$file");
351 foreach my $s (split(m!/+!, $dir)) {
354 mkdir($d) || error("failed to create directory $d: $!");
362 sub writefile ($$$;$$) { #{{{
363 my $file=shift; # can include subdirs
364 my $destdir=shift; # directory to put file in
369 prep_writefile($file, $destdir);
371 my $newfile="$destdir/$file.ikiwiki-new";
373 error("cannot write to a symlink ($newfile)");
376 my $cleanup = sub { unlink($newfile) };
377 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
378 binmode($out) if ($binary);
380 $writer->(\*$out, $cleanup);
383 print $out $content or error("failed writing to $newfile: $!", $cleanup);
385 close $out || error("failed saving $newfile: $!", $cleanup);
386 rename($newfile, "$destdir/$file") ||
387 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
393 sub will_render ($$;$) { #{{{
398 # Important security check.
399 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
400 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
401 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
404 if (! $clear || $cleared{$page}) {
405 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
408 foreach my $old (@{$renderedfiles{$page}}) {
409 delete $destsources{$old};
411 $renderedfiles{$page}=[$dest];
414 $destsources{$dest}=$page;
419 sub bestlink ($$) { #{{{
424 if ($link=~s/^\/+//) {
432 $l.="/" if length $l;
435 if (exists $links{$l}) {
438 elsif (exists $pagecase{lc $l}) {
439 return $pagecase{lc $l};
441 } while $cwd=~s!/?[^/]+$!!;
443 if (length $config{userdir}) {
444 my $l = "$config{userdir}/".lc($link);
445 if (exists $links{$l}) {
448 elsif (exists $pagecase{lc $l}) {
449 return $pagecase{lc $l};
453 #print STDERR "warning: page $page, broken link: $link\n";
457 sub isinlinableimage ($) { #{{{
460 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
463 sub pagetitle ($;$) { #{{{
468 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
471 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
477 sub titlepage ($) { #{{{
479 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
483 sub linkpage ($) { #{{{
485 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
489 sub cgiurl (@) { #{{{
492 return $config{cgiurl}."?".
493 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
496 sub baseurl (;$) { #{{{
499 return "$config{url}/" if ! defined $page;
501 $page=htmlpage($page);
503 $page=~s/[^\/]+\//..\//g;
507 sub abs2rel ($$) { #{{{
508 # Work around very innefficient behavior in File::Spec if abs2rel
509 # is passed two relative paths. It's much faster if paths are
510 # absolute! (Debian bug #376658; fixed in debian unstable now)
515 my $ret=File::Spec->abs2rel($path, $base);
516 $ret=~s/^// if defined $ret;
520 sub displaytime ($;$) { #{{{
523 if (! defined $format) {
524 $format=$config{timeformat};
527 # strftime doesn't know about encodings, so make sure
528 # its output is properly treated as utf8
529 return decode_utf8(POSIX::strftime($format, localtime($time)));
532 sub beautify_urlpath ($) { #{{{
535 if ($config{usedirs}) {
536 $url =~ s!/index.$config{htmlext}$!/!;
539 # Ensure url is not an empty link, and
540 # if it's relative, make that explicit to avoid colon confusion.
548 sub urlto ($$;$) { #{{{
554 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
557 if (! $destsources{$to}) {
562 return $config{url}.beautify_urlpath("/".$to);
565 my $link = abs2rel($to, dirname(htmlpage($from)));
567 return beautify_urlpath($link);
570 sub htmllink ($$$;@) { #{{{
571 my $lpage=shift; # the page doing the linking
572 my $page=shift; # the page that will contain the link (different for inline)
579 if (! $opts{forcesubpage}) {
580 $bestlink=bestlink($lpage, $link);
583 $bestlink="$lpage/".lc($link);
587 if (defined $opts{linktext}) {
588 $linktext=$opts{linktext};
591 $linktext=pagetitle(basename($link));
594 return "<span class=\"selflink\">$linktext</span>"
595 if length $bestlink && $page eq $bestlink &&
596 ! defined $opts{anchor};
598 if (! $destsources{$bestlink}) {
599 $bestlink=htmlpage($bestlink);
601 if (! $destsources{$bestlink}) {
602 return $linktext unless length $config{cgiurl};
603 return "<span class=\"createlink\"><a href=\"".
609 "\" rel=\"nofollow\">?</a>$linktext</span>"
613 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
614 $bestlink=beautify_urlpath($bestlink);
616 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
617 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
620 if (defined $opts{anchor}) {
621 $bestlink.="#".$opts{anchor};
625 if (defined $opts{rel}) {
626 push @attrs, ' rel="'.$opts{rel}.'"';
628 if (defined $opts{class}) {
629 push @attrs, ' class="'.$opts{class}.'"';
632 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
635 sub userlink ($) { #{{{
638 my $oiduser=eval { openiduser($user) };
639 if (defined $oiduser) {
640 return "<a href=\"$user\">$oiduser</a>";
643 eval q{use CGI 'escapeHTML'};
646 return htmllink("", "", escapeHTML(
647 length $config{userdir} ? $config{userdir}."/".$user : $user
648 ), noimageinline => 1);
652 sub htmlize ($$$$) { #{{{
658 my $oneline = $content !~ /\n/;
660 if (exists $hooks{htmlize}{$type}) {
661 $content=$hooks{htmlize}{$type}{call}->(
667 error("htmlization of $type not supported");
670 run_hooks(sanitize => sub {
673 destpage => $destpage,
679 # hack to get rid of enclosing junk added by markdown
680 # and other htmlizers
682 $content=~s/<\/p>$//i;
689 sub linkify ($$$) { #{{{
694 run_hooks(linkify => sub {
697 destpage => $destpage,
706 our $preprocess_preview=0;
707 sub preprocess ($$$;$$) { #{{{
708 my $page=shift; # the page the data comes from
709 my $destpage=shift; # the page the data will appear in (different for inline)
714 # Using local because it needs to be set within any nested calls
716 local $preprocess_preview=$preview if defined $preview;
723 if (length $escape) {
724 return "[[$prefix$command $params]]";
726 elsif (exists $hooks{preprocess}{$command}) {
727 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
728 # Note: preserve order of params, some plugins may
729 # consider it significant.
732 (?:([-\w]+)=)? # 1: named parameter key?
734 """(.*?)""" # 2: triple-quoted value
736 "([^"]+)" # 3: single-quoted value
738 (\S+) # 4: unquoted value
740 (?:\s+|$) # delimiter to next param
758 push @params, $key, $val;
761 push @params, $val, '';
764 if ($preprocessing{$page}++ > 3) {
765 # Avoid loops of preprocessed pages preprocessing
766 # other pages that preprocess them, etc.
767 return "[[!$command <span class=\"error\">".
768 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
769 $page, $preprocessing{$page}).
775 $hooks{preprocess}{$command}{call}->(
778 destpage => $destpage,
779 preview => $preprocess_preview,
784 $ret="[[!$command <span class=\"error\">".
785 gettext("Error").": $@"."</span>]]";
789 # use void context during scan pass
791 $hooks{preprocess}{$command}{call}->(
794 destpage => $destpage,
795 preview => $preprocess_preview,
800 $preprocessing{$page}--;
804 return "[[$prefix$command $params]]";
809 if ($config{prefix_directives}) {
812 \[\[(!) # directive open; 2: prefix
813 ([-\w]+) # 3: command
814 ( # 4: the parameters..
815 \s+ # Must have space if parameters present
817 (?:[-\w]+=)? # named parameter key?
819 """.*?""" # triple-quoted value
821 "[^"]+" # single-quoted value
823 [^\s\]]+ # unquoted value
825 \s* # whitespace or end
828 *)? # 0 or more parameters
829 \]\] # directive closed
835 \[\[(!?) # directive open; 2: optional prefix
836 ([-\w]+) # 3: command
838 ( # 4: the parameters..
840 (?:[-\w]+=)? # named parameter key?
842 """.*?""" # triple-quoted value
844 "[^"]+" # single-quoted value
846 [^\s\]]+ # unquoted value
848 \s* # whitespace or end
851 *) # 0 or more parameters
852 \]\] # directive closed
856 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
860 sub filter ($$$) { #{{{
865 run_hooks(filter => sub {
866 $content=shift->(page => $page, destpage => $destpage,
867 content => $content);
873 sub indexlink () { #{{{
874 return "<a href=\"$config{url}\">$config{wikiname}</a>";
879 sub lockwiki (;$) { #{{{
880 my $wait=@_ ? shift : 1;
881 # Take an exclusive lock on the wiki to prevent multiple concurrent
882 # run issues. The lock will be dropped on program exit.
883 if (! -d $config{wikistatedir}) {
884 mkdir($config{wikistatedir});
886 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
887 error ("cannot write to $config{wikistatedir}/lockfile: $!");
888 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
890 debug("wiki seems to be locked, waiting for lock");
891 my $wait=600; # arbitrary, but don't hang forever to
892 # prevent process pileup
894 return if flock($wikilock, 2 | 4);
897 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
906 sub unlockwiki () { #{{{
907 return close($wikilock) if $wikilock;
913 sub commit_hook_enabled () { #{{{
914 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
915 error("cannot write to $config{wikistatedir}/commitlock: $!");
916 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
917 close($commitlock) || error("failed closing commitlock: $!");
920 close($commitlock) || error("failed closing commitlock: $!");
924 sub disable_commit_hook () { #{{{
925 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
926 error("cannot write to $config{wikistatedir}/commitlock: $!");
927 if (! flock($commitlock, 2)) { # LOCK_EX
928 error("failed to get commit lock");
933 sub enable_commit_hook () { #{{{
934 return close($commitlock) if $commitlock;
938 sub loadindex () { #{{{
939 %oldrenderedfiles=%pagectime=();
940 if (! $config{rebuild}) {
941 %pagesources=%pagemtime=%oldlinks=%links=%depends=
942 %destsources=%renderedfiles=%pagecase=%pagestate=();
945 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
946 if (-e "$config{wikistatedir}/index") {
947 system("ikiwiki-transition", "indexdb", $config{srcdir});
948 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
954 my $ret=Storable::fd_retrieve($in);
955 if (! defined $ret) {
959 foreach my $src (keys %index) {
960 my %d=%{$index{$src}};
961 my $page=pagename($src);
962 $pagectime{$page}=$d{ctime};
963 if (! $config{rebuild}) {
964 $pagesources{$page}=$src;
965 $pagemtime{$page}=$d{mtime};
966 $renderedfiles{$page}=$d{dest};
967 if (exists $d{links} && ref $d{links}) {
968 $links{$page}=$d{links};
969 $oldlinks{$page}=[@{$d{links}}];
971 if (exists $d{depends}) {
972 $depends{$page}=$d{depends};
974 if (exists $d{state}) {
975 $pagestate{$page}=$d{state};
978 $oldrenderedfiles{$page}=[@{$d{dest}}];
980 foreach my $page (keys %pagesources) {
981 $pagecase{lc $page}=$page;
983 foreach my $page (keys %renderedfiles) {
984 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
989 sub saveindex () { #{{{
990 run_hooks(savestate => sub { shift->() });
993 foreach my $type (keys %hooks) {
994 $hookids{$_}=1 foreach keys %{$hooks{$type}};
996 my @hookids=keys %hookids;
998 if (! -d $config{wikistatedir}) {
999 mkdir($config{wikistatedir});
1001 my $newfile="$config{wikistatedir}/indexdb.new";
1002 my $cleanup = sub { unlink($newfile) };
1003 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1005 foreach my $page (keys %pagemtime) {
1006 next unless $pagemtime{$page};
1007 my $src=$pagesources{$page};
1010 ctime => $pagectime{$page},
1011 mtime => $pagemtime{$page},
1012 dest => $renderedfiles{$page},
1013 links => $links{$page},
1016 if (exists $depends{$page}) {
1017 $index{$src}{depends} = $depends{$page};
1020 if (exists $pagestate{$page}) {
1021 foreach my $id (@hookids) {
1022 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1023 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1028 my $ret=Storable::nstore_fd(\%index, $out);
1029 return if ! defined $ret || ! $ret;
1030 close $out || error("failed saving to $newfile: $!", $cleanup);
1031 rename($newfile, "$config{wikistatedir}/indexdb") ||
1032 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1037 sub template_file ($) { #{{{
1040 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1041 return "$dir/$template" if -e "$dir/$template";
1046 sub template_params (@) { #{{{
1047 my $filename=template_file(shift);
1049 if (! defined $filename) {
1050 return if wantarray;
1056 my $text_ref = shift;
1057 ${$text_ref} = decode_utf8(${$text_ref});
1059 filename => $filename,
1060 loop_context_vars => 1,
1061 die_on_bad_params => 0,
1064 return wantarray ? @ret : {@ret};
1067 sub template ($;@) { #{{{
1068 require HTML::Template;
1069 return HTML::Template->new(template_params(@_));
1072 sub misctemplate ($$;@) { #{{{
1076 my $template=template("misc.tmpl");
1079 indexlink => indexlink(),
1080 wikiname => $config{wikiname},
1081 pagebody => $pagebody,
1082 baseurl => baseurl(),
1085 run_hooks(pagetemplate => sub {
1086 shift->(page => "", destpage => "", template => $template);
1088 return $template->output;
1091 sub hook (@) { # {{{
1094 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1095 error 'hook requires type, call, and id parameters';
1098 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1100 $hooks{$param{type}}{$param{id}}=\%param;
1104 sub run_hooks ($$) { # {{{
1105 # Calls the given sub for each hook of the given type,
1106 # passing it the hook function to call.
1110 if (exists $hooks{$type}) {
1112 foreach my $id (keys %{$hooks{$type}}) {
1113 if ($hooks{$type}{$id}{last}) {
1114 push @deferred, $id;
1117 $sub->($hooks{$type}{$id}{call});
1119 foreach my $id (@deferred) {
1120 $sub->($hooks{$type}{$id}{call});
1127 sub globlist_to_pagespec ($) { #{{{
1128 my @globlist=split(' ', shift);
1131 foreach my $glob (@globlist) {
1132 if ($glob=~/^!(.*)/) {
1140 my $spec=join(' or ', @spec);
1142 my $skip=join(' and ', @skip);
1144 $spec="$skip and ($spec)";
1153 sub is_globlist ($) { #{{{
1155 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1158 sub safequote ($) { #{{{
1164 sub add_depends ($$) { #{{{
1168 return unless pagespec_valid($pagespec);
1170 if (! exists $depends{$page}) {
1171 $depends{$page}=$pagespec;
1174 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1180 sub file_pruned ($$) { #{{{
1182 my $file=File::Spec->canonpath(shift);
1183 my $base=File::Spec->canonpath(shift);
1184 $file =~ s#^\Q$base\E/+##;
1186 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1187 return $file =~ m/$regexp/ && $file ne $base;
1191 # Only use gettext in the rare cases it's needed.
1192 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1193 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1194 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1195 if (! $gettext_obj) {
1196 $gettext_obj=eval q{
1197 use Locale::gettext q{textdomain};
1198 Locale::gettext->domain('ikiwiki')
1206 return $gettext_obj->get(shift);
1213 sub yesno ($) { #{{{
1216 return (defined $val && lc($val) eq gettext("yes"));
1219 sub pagespec_merge ($$) { #{{{
1223 return $a if $a eq $b;
1225 # Support for old-style GlobLists.
1226 if (is_globlist($a)) {
1227 $a=globlist_to_pagespec($a);
1229 if (is_globlist($b)) {
1230 $b=globlist_to_pagespec($b);
1233 return "($a) or ($b)";
1236 sub pagespec_translate ($) { #{{{
1239 # Support for old-style GlobLists.
1240 if (is_globlist($spec)) {
1241 $spec=globlist_to_pagespec($spec);
1244 # Convert spec to perl code.
1247 \s* # ignore whitespace
1248 ( # 1: match a single word
1255 \w+\([^\)]*\) # command(params)
1257 [^\s()]+ # any other text
1259 \s* # ignore whitespace
1262 if (lc $word eq 'and') {
1265 elsif (lc $word eq 'or') {
1268 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1271 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1272 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1273 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1280 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1284 if (! length $code) {
1289 return eval 'sub { my $page=shift; '.$code.' }';
1292 sub pagespec_match ($$;@) { #{{{
1297 # Backwards compatability with old calling convention.
1299 unshift @params, 'location';
1302 my $sub=pagespec_translate($spec);
1303 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1304 return $sub->($page, @params);
1307 sub pagespec_valid ($) { #{{{
1310 my $sub=pagespec_translate($spec);
1314 sub glob2re ($) { #{{{
1315 my $re=quotemeta(shift);
1321 package IkiWiki::FailReason;
1324 '""' => sub { ${$_[0]} },
1326 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1333 return bless \$value, $class;
1336 package IkiWiki::SuccessReason;
1339 '""' => sub { ${$_[0]} },
1341 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1348 return bless \$value, $class;
1351 package IkiWiki::PageSpec;
1353 sub match_glob ($$;@) { #{{{
1358 my $from=exists $params{location} ? $params{location} : '';
1361 if ($glob =~ m!^\./!) {
1362 $from=~s#/?[^/]+$##;
1364 $glob="$from/$glob" if length $from;
1367 my $regexp=IkiWiki::glob2re($glob);
1368 if ($page=~/^$regexp$/i) {
1369 if (! IkiWiki::isinternal($page) || $params{internal}) {
1370 return IkiWiki::SuccessReason->new("$glob matches $page");
1373 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1377 return IkiWiki::FailReason->new("$glob does not match $page");
1381 sub match_internal ($$;@) { #{{{
1382 return match_glob($_[0], $_[1], @_, internal => 1)
1385 sub match_link ($$;@) { #{{{
1390 my $from=exists $params{location} ? $params{location} : '';
1393 if ($link =~ m!^\.! && defined $from) {
1394 $from=~s#/?[^/]+$##;
1396 $link="$from/$link" if length $from;
1399 my $links = $IkiWiki::links{$page};
1400 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1401 my $bestlink = IkiWiki::bestlink($from, $link);
1402 foreach my $p (@{$links}) {
1403 if (length $bestlink) {
1404 return IkiWiki::SuccessReason->new("$page links to $link")
1405 if $bestlink eq IkiWiki::bestlink($page, $p);
1408 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1409 if match_glob($p, $link, %params);
1412 return IkiWiki::FailReason->new("$page does not link to $link");
1415 sub match_backlink ($$;@) { #{{{
1416 return match_link($_[1], $_[0], @_);
1419 sub match_created_before ($$;@) { #{{{
1423 if (exists $IkiWiki::pagectime{$testpage}) {
1424 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1425 return IkiWiki::SuccessReason->new("$page created before $testpage");
1428 return IkiWiki::FailReason->new("$page not created before $testpage");
1432 return IkiWiki::FailReason->new("$testpage has no ctime");
1436 sub match_created_after ($$;@) { #{{{
1440 if (exists $IkiWiki::pagectime{$testpage}) {
1441 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1442 return IkiWiki::SuccessReason->new("$page created after $testpage");
1445 return IkiWiki::FailReason->new("$page not created after $testpage");
1449 return IkiWiki::FailReason->new("$testpage has no ctime");
1453 sub match_creation_day ($$;@) { #{{{
1454 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1455 return IkiWiki::SuccessReason->new('creation_day matched');
1458 return IkiWiki::FailReason->new('creation_day did not match');
1462 sub match_creation_month ($$;@) { #{{{
1463 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1464 return IkiWiki::SuccessReason->new('creation_month matched');
1467 return IkiWiki::FailReason->new('creation_month did not match');
1471 sub match_creation_year ($$;@) { #{{{
1472 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1473 return IkiWiki::SuccessReason->new('creation_year matched');
1476 return IkiWiki::FailReason->new('creation_year did not match');