8 use URI::Escape q{uri_escape_utf8};
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14 %pagestate %renderedfiles %oldrenderedfiles %pagesources
15 %destsources %depends %hooks %forcerebuild $gettext_obj};
17 use Exporter q{import};
18 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
19 bestlink htmllink readfile writefile pagetype srcfile pagename
20 displaytime will_render gettext urlto targetpage
22 %config %links %pagestate %renderedfiles
23 %pagesources %destsources);
24 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
25 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
26 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
31 memoize("pagespec_translate");
32 memoize("file_pruned");
34 sub defaultconfig () { #{{{
36 wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
37 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
38 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
41 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
42 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
46 default_pageext => "mdwn",
67 gitorigin_branch => "origin",
68 gitmaster_branch => "master",
72 templatedir => "$installdir/share/ikiwiki/templates",
73 underlaydir => "$installdir/share/ikiwiki/basewiki",
78 plugin => [qw{mdwn link inline htmlscrubber passwordauth openid
79 signinedit lockedit conditional recentchanges}],
88 account_creation_password => "",
89 prefix_directives => 0,
93 sub checkconfig () { #{{{
94 # locale stuff; avoid LC_ALL since it overrides everything
95 if (defined $ENV{LC_ALL}) {
96 $ENV{LANG} = $ENV{LC_ALL};
99 if (defined $config{locale}) {
100 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
101 $ENV{LANG}=$config{locale};
106 if (ref $config{ENV} eq 'HASH') {
107 foreach my $val (keys %{$config{ENV}}) {
108 $ENV{$val}=$config{ENV}{$val};
112 if ($config{w3mmode}) {
113 eval q{use Cwd q{abs_path}};
115 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
116 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
117 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
118 unless $config{cgiurl} =~ m!file:///!;
119 $config{url}="file://".$config{destdir};
122 if ($config{cgi} && ! length $config{url}) {
123 error(gettext("Must specify url to wiki with --url when using --cgi"));
126 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
127 unless exists $config{wikistatedir};
130 eval qq{use IkiWiki::Rcs::$config{rcs}};
132 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
136 require IkiWiki::Rcs::Stub;
139 if (exists $config{umask}) {
140 umask(possibly_foolish_untaint($config{umask}));
143 run_hooks(checkconfig => sub { shift->() });
148 sub loadplugins () { #{{{
149 if (defined $config{libdir}) {
150 unshift @INC, possibly_foolish_untaint($config{libdir});
153 loadplugin($_) foreach @{$config{plugin}};
155 run_hooks(getopt => sub { shift->() });
156 if (grep /^-/, @ARGV) {
157 print STDERR "Unknown option: $_\n"
158 foreach grep /^-/, @ARGV;
165 sub loadplugin ($) { #{{{
168 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
170 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
171 "$installdir/lib/ikiwiki") {
172 if (defined $dir && -x "$dir/plugins/$plugin") {
173 require IkiWiki::Plugin::external;
174 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
179 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
182 error("Failed to load plugin $mod: $@");
187 sub error ($;$) { #{{{
191 print "Content-type: text/html\n\n";
192 print misctemplate(gettext("Error"),
193 "<p>".gettext("Error").": $message</p>");
195 log_message('err' => $message) if $config{syslog};
196 if (defined $cleaner) {
203 return unless $config{verbose};
204 return log_message(debug => @_);
208 sub log_message ($$) { #{{{
211 if ($config{syslog}) {
214 Sys::Syslog::setlogsock('unix');
215 Sys::Syslog::openlog('ikiwiki', '', 'user');
219 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
222 elsif (! $config{cgi}) {
226 return print STDERR "@_\n";
230 sub possibly_foolish_untaint ($) { #{{{
232 my ($untainted)=$tainted=~/(.*)/s;
236 sub basename ($) { #{{{
243 sub dirname ($) { #{{{
250 sub pagetype ($) { #{{{
253 if ($page =~ /\.([^.]+)$/) {
254 return $1 if exists $hooks{htmlize}{$1};
259 sub isinternal ($) { #{{{
261 return exists $pagesources{$page} &&
262 $pagesources{$page} =~ /\._([^.]+)$/;
265 sub pagename ($) { #{{{
268 my $type=pagetype($file);
270 $page=~s/\Q.$type\E*$// if defined $type;
274 sub targetpage ($$) { #{{{
278 if (! $config{usedirs} || $page =~ /^index$/ ) {
279 return $page.".".$ext;
281 return $page."/index.".$ext;
285 sub htmlpage ($) { #{{{
288 return targetpage($page, $config{htmlext});
291 sub srcfile_stat { #{{{
295 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
296 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
297 return "$dir/$file", stat(_) if -e "$dir/$file";
299 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
303 sub srcfile ($;$) { #{{{
304 return (srcfile_stat(@_))[0];
307 sub add_underlay ($) { #{{{
311 unshift @{$config{underlaydirs}}, $dir;
314 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
320 sub readfile ($;$$) { #{{{
326 error("cannot read a symlink ($file)");
330 open (my $in, "<", $file) || error("failed to read $file: $!");
331 binmode($in) if ($binary);
332 return \*$in if $wantfd;
334 close $in || error("failed to read $file: $!");
338 sub prep_writefile ($$) {
343 while (length $test) {
344 if (-l "$destdir/$test") {
345 error("cannot write to a symlink ($test)");
347 $test=dirname($test);
350 my $dir=dirname("$destdir/$file");
353 foreach my $s (split(m!/+!, $dir)) {
356 mkdir($d) || error("failed to create directory $d: $!");
364 sub writefile ($$$;$$) { #{{{
365 my $file=shift; # can include subdirs
366 my $destdir=shift; # directory to put file in
371 prep_writefile($file, $destdir);
373 my $newfile="$destdir/$file.ikiwiki-new";
375 error("cannot write to a symlink ($newfile)");
378 my $cleanup = sub { unlink($newfile) };
379 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
380 binmode($out) if ($binary);
382 $writer->(\*$out, $cleanup);
385 print $out $content or error("failed writing to $newfile: $!", $cleanup);
387 close $out || error("failed saving $newfile: $!", $cleanup);
388 rename($newfile, "$destdir/$file") ||
389 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
395 sub will_render ($$;$) { #{{{
400 # Important security check.
401 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
402 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
403 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
406 if (! $clear || $cleared{$page}) {
407 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
410 foreach my $old (@{$renderedfiles{$page}}) {
411 delete $destsources{$old};
413 $renderedfiles{$page}=[$dest];
416 $destsources{$dest}=$page;
421 sub bestlink ($$) { #{{{
426 if ($link=~s/^\/+//) {
434 $l.="/" if length $l;
437 if (exists $links{$l}) {
440 elsif (exists $pagecase{lc $l}) {
441 return $pagecase{lc $l};
443 } while $cwd=~s!/?[^/]+$!!;
445 if (length $config{userdir}) {
446 my $l = "$config{userdir}/".lc($link);
447 if (exists $links{$l}) {
450 elsif (exists $pagecase{lc $l}) {
451 return $pagecase{lc $l};
455 #print STDERR "warning: page $page, broken link: $link\n";
459 sub isinlinableimage ($) { #{{{
462 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
465 sub pagetitle ($;$) { #{{{
470 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
473 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
479 sub titlepage ($) { #{{{
481 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
485 sub linkpage ($) { #{{{
487 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
491 sub cgiurl (@) { #{{{
494 return $config{cgiurl}."?".
495 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
498 sub baseurl (;$) { #{{{
501 return "$config{url}/" if ! defined $page;
503 $page=htmlpage($page);
505 $page=~s/[^\/]+\//..\//g;
509 sub abs2rel ($$) { #{{{
510 # Work around very innefficient behavior in File::Spec if abs2rel
511 # is passed two relative paths. It's much faster if paths are
512 # absolute! (Debian bug #376658; fixed in debian unstable now)
517 my $ret=File::Spec->abs2rel($path, $base);
518 $ret=~s/^// if defined $ret;
522 sub displaytime ($;$) { #{{{
525 if (! defined $format) {
526 $format=$config{timeformat};
529 # strftime doesn't know about encodings, so make sure
530 # its output is properly treated as utf8
531 return decode_utf8(POSIX::strftime($format, localtime($time)));
534 sub beautify_url ($) { #{{{
537 if ($config{usedirs}) {
538 $url =~ s!/index.$config{htmlext}$!/!;
540 $url =~ s!^$!./!; # Browsers don't like empty links...
545 sub urlto ($$) { #{{{
550 return beautify_url(baseurl($from));
553 if (! $destsources{$to}) {
557 my $link = abs2rel($to, dirname(htmlpage($from)));
559 return beautify_url($link);
562 sub htmllink ($$$;@) { #{{{
563 my $lpage=shift; # the page doing the linking
564 my $page=shift; # the page that will contain the link (different for inline)
571 if (! $opts{forcesubpage}) {
572 $bestlink=bestlink($lpage, $link);
575 $bestlink="$lpage/".lc($link);
579 if (defined $opts{linktext}) {
580 $linktext=$opts{linktext};
583 $linktext=pagetitle(basename($link));
586 return "<span class=\"selflink\">$linktext</span>"
587 if length $bestlink && $page eq $bestlink &&
588 ! defined $opts{anchor};
590 if (! $destsources{$bestlink}) {
591 $bestlink=htmlpage($bestlink);
593 if (! $destsources{$bestlink}) {
594 return $linktext unless length $config{cgiurl};
595 return "<span class=\"createlink\"><a href=\"".
598 page => pagetitle(lc($link), 1),
601 "\">?</a>$linktext</span>"
605 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
606 $bestlink=beautify_url($bestlink);
608 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
609 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
612 if (defined $opts{anchor}) {
613 $bestlink.="#".$opts{anchor};
617 if (defined $opts{rel}) {
618 push @attrs, ' rel="'.$opts{rel}.'"';
620 if (defined $opts{class}) {
621 push @attrs, ' class="'.$opts{class}.'"';
624 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
627 sub userlink ($) { #{{{
630 my $oiduser=eval { openiduser($user) };
631 if (defined $oiduser) {
632 return "<a href=\"$user\">$oiduser</a>";
635 eval q{use CGI 'escapeHTML'};
638 return htmllink("", "", escapeHTML(
639 length $config{userdir} ? $config{userdir}."/".$user : $user
640 ), noimageinline => 1);
644 sub htmlize ($$$) { #{{{
649 my $oneline = $content !~ /\n/;
651 if (exists $hooks{htmlize}{$type}) {
652 $content=$hooks{htmlize}{$type}{call}->(
658 error("htmlization of $type not supported");
661 run_hooks(sanitize => sub {
669 # hack to get rid of enclosing junk added by markdown
670 # and other htmlizers
672 $content=~s/<\/p>$//i;
679 sub linkify ($$$) { #{{{
684 run_hooks(linkify => sub {
687 destpage => $destpage,
696 our $preprocess_preview=0;
697 sub preprocess ($$$;$$) { #{{{
698 my $page=shift; # the page the data comes from
699 my $destpage=shift; # the page the data will appear in (different for inline)
704 # Using local because it needs to be set within any nested calls
706 local $preprocess_preview=$preview if defined $preview;
713 if (length $escape) {
714 return "[[$prefix$command $params]]";
716 elsif (exists $hooks{preprocess}{$command}) {
717 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
718 # Note: preserve order of params, some plugins may
719 # consider it significant.
722 (?:([-\w]+)=)? # 1: named parameter key?
724 """(.*?)""" # 2: triple-quoted value
726 "([^"]+)" # 3: single-quoted value
728 (\S+) # 4: unquoted value
730 (?:\s+|$) # delimiter to next param
748 push @params, $key, $val;
751 push @params, $val, '';
754 if ($preprocessing{$page}++ > 3) {
755 # Avoid loops of preprocessed pages preprocessing
756 # other pages that preprocess them, etc.
757 #translators: The first parameter is a
758 #translators: preprocessor directive name,
759 #translators: the second a page name, the
760 #translators: third a number.
761 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
762 $command, $page, $preprocessing{$page}).
767 $ret=$hooks{preprocess}{$command}{call}->(
770 destpage => $destpage,
771 preview => $preprocess_preview,
775 # use void context during scan pass
776 $hooks{preprocess}{$command}{call}->(
779 destpage => $destpage,
780 preview => $preprocess_preview,
784 $preprocessing{$page}--;
788 return "[[$prefix$command $params]]";
793 if ($config{prefix_directives}) {
796 \[\[(!) # directive open; 2: prefix
797 ([-\w]+) # 3: command
798 ( # 4: the parameters..
799 \s+ # Must have space if parameters present
801 (?:[-\w]+=)? # named parameter key?
803 """.*?""" # triple-quoted value
805 "[^"]+" # single-quoted value
807 [^\s\]]+ # unquoted value
809 \s* # whitespace or end
812 *)? # 0 or more parameters
813 \]\] # directive closed
818 \[\[(!?) # directive open; 2: optional prefix
819 ([-\w]+) # 3: command
821 ( # 4: the parameters..
823 (?:[-\w]+=)? # named parameter key?
825 """.*?""" # triple-quoted value
827 "[^"]+" # single-quoted value
829 [^\s\]]+ # unquoted value
831 \s* # whitespace or end
834 *) # 0 or more parameters
835 \]\] # directive closed
839 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
843 sub filter ($$$) { #{{{
848 run_hooks(filter => sub {
849 $content=shift->(page => $page, destpage => $destpage,
850 content => $content);
856 sub indexlink () { #{{{
857 return "<a href=\"$config{url}\">$config{wikiname}</a>";
862 sub lockwiki (;$) { #{{{
863 my $wait=@_ ? shift : 1;
864 # Take an exclusive lock on the wiki to prevent multiple concurrent
865 # run issues. The lock will be dropped on program exit.
866 if (! -d $config{wikistatedir}) {
867 mkdir($config{wikistatedir});
869 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
870 error ("cannot write to $config{wikistatedir}/lockfile: $!");
871 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
873 debug("wiki seems to be locked, waiting for lock");
874 my $wait=600; # arbitrary, but don't hang forever to
875 # prevent process pileup
877 return if flock($wikilock, 2 | 4);
880 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
889 sub unlockwiki () { #{{{
890 return close($wikilock) if $wikilock;
896 sub commit_hook_enabled () { #{{{
897 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
898 error("cannot write to $config{wikistatedir}/commitlock: $!");
899 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
900 close($commitlock) || error("failed closing commitlock: $!");
903 close($commitlock) || error("failed closing commitlock: $!");
907 sub disable_commit_hook () { #{{{
908 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
909 error("cannot write to $config{wikistatedir}/commitlock: $!");
910 if (! flock($commitlock, 2)) { # LOCK_EX
911 error("failed to get commit lock");
916 sub enable_commit_hook () { #{{{
917 return close($commitlock) if $commitlock;
921 sub loadindex () { #{{{
922 %oldrenderedfiles=%pagectime=();
923 if (! $config{rebuild}) {
924 %pagesources=%pagemtime=%oldlinks=%links=%depends=
925 %destsources=%renderedfiles=%pagecase=%pagestate=();
928 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
929 if (-e "$config{wikistatedir}/index") {
930 system("ikiwiki-transition", "indexdb", $config{srcdir});
931 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
937 my $ret=Storable::fd_retrieve($in);
938 if (! defined $ret) {
942 foreach my $src (keys %index) {
943 my %d=%{$index{$src}};
944 my $page=pagename($src);
945 $pagectime{$page}=$d{ctime};
946 if (! $config{rebuild}) {
947 $pagesources{$page}=$src;
948 $pagemtime{$page}=$d{mtime};
949 $renderedfiles{$page}=$d{dest};
950 if (exists $d{links} && ref $d{links}) {
951 $links{$page}=$d{links};
952 $oldlinks{$page}=[@{$d{links}}];
954 if (exists $d{depends}) {
955 $depends{$page}=$d{depends};
957 if (exists $d{state}) {
958 $pagestate{$page}=$d{state};
961 $oldrenderedfiles{$page}=[@{$d{dest}}];
963 foreach my $page (keys %pagesources) {
964 $pagecase{lc $page}=$page;
966 foreach my $page (keys %renderedfiles) {
967 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
972 sub saveindex () { #{{{
973 run_hooks(savestate => sub { shift->() });
976 foreach my $type (keys %hooks) {
977 $hookids{$_}=1 foreach keys %{$hooks{$type}};
979 my @hookids=keys %hookids;
981 if (! -d $config{wikistatedir}) {
982 mkdir($config{wikistatedir});
984 my $newfile="$config{wikistatedir}/indexdb.new";
985 my $cleanup = sub { unlink($newfile) };
986 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
988 foreach my $page (keys %pagemtime) {
989 next unless $pagemtime{$page};
990 my $src=$pagesources{$page};
993 ctime => $pagectime{$page},
994 mtime => $pagemtime{$page},
995 dest => $renderedfiles{$page},
996 links => $links{$page},
999 if (exists $depends{$page}) {
1000 $index{$src}{depends} = $depends{$page};
1003 if (exists $pagestate{$page}) {
1004 foreach my $id (@hookids) {
1005 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1006 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1011 my $ret=Storable::nstore_fd(\%index, $out);
1012 return if ! defined $ret || ! $ret;
1013 close $out || error("failed saving to $newfile: $!", $cleanup);
1014 rename($newfile, "$config{wikistatedir}/indexdb") ||
1015 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1020 sub template_file ($) { #{{{
1023 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1024 return "$dir/$template" if -e "$dir/$template";
1029 sub template_params (@) { #{{{
1030 my $filename=template_file(shift);
1032 if (! defined $filename) {
1033 return if wantarray;
1039 my $text_ref = shift;
1040 ${$text_ref} = decode_utf8(${$text_ref});
1042 filename => $filename,
1043 loop_context_vars => 1,
1044 die_on_bad_params => 0,
1047 return wantarray ? @ret : {@ret};
1050 sub template ($;@) { #{{{
1051 require HTML::Template;
1052 return HTML::Template->new(template_params(@_));
1055 sub misctemplate ($$;@) { #{{{
1059 my $template=template("misc.tmpl");
1062 indexlink => indexlink(),
1063 wikiname => $config{wikiname},
1064 pagebody => $pagebody,
1065 baseurl => baseurl(),
1068 run_hooks(pagetemplate => sub {
1069 shift->(page => "", destpage => "", template => $template);
1071 return $template->output;
1074 sub hook (@) { # {{{
1077 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1078 error 'hook requires type, call, and id parameters';
1081 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1083 $hooks{$param{type}}{$param{id}}=\%param;
1087 sub run_hooks ($$) { # {{{
1088 # Calls the given sub for each hook of the given type,
1089 # passing it the hook function to call.
1093 if (exists $hooks{$type}) {
1095 foreach my $id (keys %{$hooks{$type}}) {
1096 if ($hooks{$type}{$id}{last}) {
1097 push @deferred, $id;
1100 $sub->($hooks{$type}{$id}{call});
1102 foreach my $id (@deferred) {
1103 $sub->($hooks{$type}{$id}{call});
1110 sub globlist_to_pagespec ($) { #{{{
1111 my @globlist=split(' ', shift);
1114 foreach my $glob (@globlist) {
1115 if ($glob=~/^!(.*)/) {
1123 my $spec=join(' or ', @spec);
1125 my $skip=join(' and ', @skip);
1127 $spec="$skip and ($spec)";
1136 sub is_globlist ($) { #{{{
1138 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1141 sub safequote ($) { #{{{
1147 sub add_depends ($$) { #{{{
1151 return unless pagespec_valid($pagespec);
1153 if (! exists $depends{$page}) {
1154 $depends{$page}=$pagespec;
1157 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1163 sub file_pruned ($$) { #{{{
1165 my $file=File::Spec->canonpath(shift);
1166 my $base=File::Spec->canonpath(shift);
1167 $file =~ s#^\Q$base\E/+##;
1169 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1170 return $file =~ m/$regexp/ && $file ne $base;
1174 # Only use gettext in the rare cases it's needed.
1175 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1176 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1177 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1178 if (! $gettext_obj) {
1179 $gettext_obj=eval q{
1180 use Locale::gettext q{textdomain};
1181 Locale::gettext->domain('ikiwiki')
1189 return $gettext_obj->get(shift);
1196 sub pagespec_merge ($$) { #{{{
1200 return $a if $a eq $b;
1202 # Support for old-style GlobLists.
1203 if (is_globlist($a)) {
1204 $a=globlist_to_pagespec($a);
1206 if (is_globlist($b)) {
1207 $b=globlist_to_pagespec($b);
1210 return "($a) or ($b)";
1213 sub pagespec_translate ($) { #{{{
1216 # Support for old-style GlobLists.
1217 if (is_globlist($spec)) {
1218 $spec=globlist_to_pagespec($spec);
1221 # Convert spec to perl code.
1224 \s* # ignore whitespace
1225 ( # 1: match a single word
1232 \w+\([^\)]*\) # command(params)
1234 [^\s()]+ # any other text
1236 \s* # ignore whitespace
1239 if (lc $word eq 'and') {
1242 elsif (lc $word eq 'or') {
1245 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1248 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1249 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1250 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1257 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1261 if (! length $code) {
1266 return eval 'sub { my $page=shift; '.$code.' }';
1269 sub pagespec_match ($$;@) { #{{{
1274 # Backwards compatability with old calling convention.
1276 unshift @params, 'location';
1279 my $sub=pagespec_translate($spec);
1280 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1281 return $sub->($page, @params);
1284 sub pagespec_valid ($) { #{{{
1287 my $sub=pagespec_translate($spec);
1291 package IkiWiki::FailReason;
1294 '""' => sub { ${$_[0]} },
1296 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1303 return bless \$value, $class;
1306 package IkiWiki::SuccessReason;
1309 '""' => sub { ${$_[0]} },
1311 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1318 return bless \$value, $class;
1321 package IkiWiki::PageSpec;
1323 sub match_glob ($$;@) { #{{{
1328 my $from=exists $params{location} ? $params{location} : '';
1331 if ($glob =~ m!^\./!) {
1332 $from=~s#/?[^/]+$##;
1334 $glob="$from/$glob" if length $from;
1337 # turn glob into safe regexp
1338 $glob=quotemeta($glob);
1342 if ($page=~/^$glob$/i) {
1343 if (! IkiWiki::isinternal($page) || $params{internal}) {
1344 return IkiWiki::SuccessReason->new("$glob matches $page");
1347 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1351 return IkiWiki::FailReason->new("$glob does not match $page");
1355 sub match_internal ($$;@) { #{{{
1356 return match_glob($_[0], $_[1], @_, internal => 1)
1359 sub match_link ($$;@) { #{{{
1364 my $from=exists $params{location} ? $params{location} : '';
1367 if ($link =~ m!^\.! && defined $from) {
1368 $from=~s#/?[^/]+$##;
1370 $link="$from/$link" if length $from;
1373 my $links = $IkiWiki::links{$page};
1374 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1375 my $bestlink = IkiWiki::bestlink($from, $link);
1376 foreach my $p (@{$links}) {
1377 if (length $bestlink) {
1378 return IkiWiki::SuccessReason->new("$page links to $link")
1379 if $bestlink eq IkiWiki::bestlink($page, $p);
1382 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1383 if match_glob($p, $link, %params);
1386 return IkiWiki::FailReason->new("$page does not link to $link");
1389 sub match_backlink ($$;@) { #{{{
1390 return match_link($_[1], $_[0], @_);
1393 sub match_created_before ($$;@) { #{{{
1397 if (exists $IkiWiki::pagectime{$testpage}) {
1398 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1399 return IkiWiki::SuccessReason->new("$page created before $testpage");
1402 return IkiWiki::FailReason->new("$page not created before $testpage");
1406 return IkiWiki::FailReason->new("$testpage has no ctime");
1410 sub match_created_after ($$;@) { #{{{
1414 if (exists $IkiWiki::pagectime{$testpage}) {
1415 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1416 return IkiWiki::SuccessReason->new("$page created after $testpage");
1419 return IkiWiki::FailReason->new("$page not created after $testpage");
1423 return IkiWiki::FailReason->new("$testpage has no ctime");
1427 sub match_creation_day ($$;@) { #{{{
1428 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1429 return IkiWiki::SuccessReason->new('creation_day matched');
1432 return IkiWiki::FailReason->new('creation_day did not match');
1436 sub match_creation_month ($$;@) { #{{{
1437 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1438 return IkiWiki::SuccessReason->new('creation_month matched');
1441 return IkiWiki::FailReason->new('creation_month did not match');
1445 sub match_creation_year ($$;@) { #{{{
1446 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1447 return IkiWiki::SuccessReason->new('creation_year matched');
1450 return IkiWiki::FailReason->new('creation_year did not match');