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)."index.$config{htmlext}");
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 "\" rel=\"nofollow\">?</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 ($$$$) { #{{{
650 my $oneline = $content !~ /\n/;
652 if (exists $hooks{htmlize}{$type}) {
653 $content=$hooks{htmlize}{$type}{call}->(
659 error("htmlization of $type not supported");
662 run_hooks(sanitize => sub {
665 destpage => $destpage,
671 # hack to get rid of enclosing junk added by markdown
672 # and other htmlizers
674 $content=~s/<\/p>$//i;
681 sub linkify ($$$) { #{{{
686 run_hooks(linkify => sub {
689 destpage => $destpage,
698 our $preprocess_preview=0;
699 sub preprocess ($$$;$$) { #{{{
700 my $page=shift; # the page the data comes from
701 my $destpage=shift; # the page the data will appear in (different for inline)
706 # Using local because it needs to be set within any nested calls
708 local $preprocess_preview=$preview if defined $preview;
715 if (length $escape) {
716 return "[[$prefix$command $params]]";
718 elsif (exists $hooks{preprocess}{$command}) {
719 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
720 # Note: preserve order of params, some plugins may
721 # consider it significant.
724 (?:([-\w]+)=)? # 1: named parameter key?
726 """(.*?)""" # 2: triple-quoted value
728 "([^"]+)" # 3: single-quoted value
730 (\S+) # 4: unquoted value
732 (?:\s+|$) # delimiter to next param
750 push @params, $key, $val;
753 push @params, $val, '';
756 if ($preprocessing{$page}++ > 3) {
757 # Avoid loops of preprocessed pages preprocessing
758 # other pages that preprocess them, etc.
759 #translators: The first parameter is a
760 #translators: preprocessor directive name,
761 #translators: the second a page name, the
762 #translators: third a number.
763 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
764 $command, $page, $preprocessing{$page}).
769 $ret=$hooks{preprocess}{$command}{call}->(
772 destpage => $destpage,
773 preview => $preprocess_preview,
777 # use void context during scan pass
778 $hooks{preprocess}{$command}{call}->(
781 destpage => $destpage,
782 preview => $preprocess_preview,
786 $preprocessing{$page}--;
790 return "[[$prefix$command $params]]";
795 if ($config{prefix_directives}) {
798 \[\[(!) # directive open; 2: prefix
799 ([-\w]+) # 3: command
800 ( # 4: the parameters..
801 \s+ # Must have space if parameters present
803 (?:[-\w]+=)? # named parameter key?
805 """.*?""" # triple-quoted value
807 "[^"]+" # single-quoted value
809 [^\s\]]+ # unquoted value
811 \s* # whitespace or end
814 *)? # 0 or more parameters
815 \]\] # directive closed
820 \[\[(!?) # directive open; 2: optional prefix
821 ([-\w]+) # 3: command
823 ( # 4: the parameters..
825 (?:[-\w]+=)? # named parameter key?
827 """.*?""" # triple-quoted value
829 "[^"]+" # single-quoted value
831 [^\s\]]+ # unquoted value
833 \s* # whitespace or end
836 *) # 0 or more parameters
837 \]\] # directive closed
841 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
845 sub filter ($$$) { #{{{
850 run_hooks(filter => sub {
851 $content=shift->(page => $page, destpage => $destpage,
852 content => $content);
858 sub indexlink () { #{{{
859 return "<a href=\"$config{url}\">$config{wikiname}</a>";
864 sub lockwiki (;$) { #{{{
865 my $wait=@_ ? shift : 1;
866 # Take an exclusive lock on the wiki to prevent multiple concurrent
867 # run issues. The lock will be dropped on program exit.
868 if (! -d $config{wikistatedir}) {
869 mkdir($config{wikistatedir});
871 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
872 error ("cannot write to $config{wikistatedir}/lockfile: $!");
873 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
875 debug("wiki seems to be locked, waiting for lock");
876 my $wait=600; # arbitrary, but don't hang forever to
877 # prevent process pileup
879 return if flock($wikilock, 2 | 4);
882 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
891 sub unlockwiki () { #{{{
892 return close($wikilock) if $wikilock;
898 sub commit_hook_enabled () { #{{{
899 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
900 error("cannot write to $config{wikistatedir}/commitlock: $!");
901 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
902 close($commitlock) || error("failed closing commitlock: $!");
905 close($commitlock) || error("failed closing commitlock: $!");
909 sub disable_commit_hook () { #{{{
910 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
911 error("cannot write to $config{wikistatedir}/commitlock: $!");
912 if (! flock($commitlock, 2)) { # LOCK_EX
913 error("failed to get commit lock");
918 sub enable_commit_hook () { #{{{
919 return close($commitlock) if $commitlock;
923 sub loadindex () { #{{{
924 %oldrenderedfiles=%pagectime=();
925 if (! $config{rebuild}) {
926 %pagesources=%pagemtime=%oldlinks=%links=%depends=
927 %destsources=%renderedfiles=%pagecase=%pagestate=();
930 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
931 if (-e "$config{wikistatedir}/index") {
932 system("ikiwiki-transition", "indexdb", $config{srcdir});
933 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
939 my $ret=Storable::fd_retrieve($in);
940 if (! defined $ret) {
944 foreach my $src (keys %index) {
945 my %d=%{$index{$src}};
946 my $page=pagename($src);
947 $pagectime{$page}=$d{ctime};
948 if (! $config{rebuild}) {
949 $pagesources{$page}=$src;
950 $pagemtime{$page}=$d{mtime};
951 $renderedfiles{$page}=$d{dest};
952 if (exists $d{links} && ref $d{links}) {
953 $links{$page}=$d{links};
954 $oldlinks{$page}=[@{$d{links}}];
956 if (exists $d{depends}) {
957 $depends{$page}=$d{depends};
959 if (exists $d{state}) {
960 $pagestate{$page}=$d{state};
963 $oldrenderedfiles{$page}=[@{$d{dest}}];
965 foreach my $page (keys %pagesources) {
966 $pagecase{lc $page}=$page;
968 foreach my $page (keys %renderedfiles) {
969 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
974 sub saveindex () { #{{{
975 run_hooks(savestate => sub { shift->() });
978 foreach my $type (keys %hooks) {
979 $hookids{$_}=1 foreach keys %{$hooks{$type}};
981 my @hookids=keys %hookids;
983 if (! -d $config{wikistatedir}) {
984 mkdir($config{wikistatedir});
986 my $newfile="$config{wikistatedir}/indexdb.new";
987 my $cleanup = sub { unlink($newfile) };
988 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
990 foreach my $page (keys %pagemtime) {
991 next unless $pagemtime{$page};
992 my $src=$pagesources{$page};
995 ctime => $pagectime{$page},
996 mtime => $pagemtime{$page},
997 dest => $renderedfiles{$page},
998 links => $links{$page},
1001 if (exists $depends{$page}) {
1002 $index{$src}{depends} = $depends{$page};
1005 if (exists $pagestate{$page}) {
1006 foreach my $id (@hookids) {
1007 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1008 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1013 my $ret=Storable::nstore_fd(\%index, $out);
1014 return if ! defined $ret || ! $ret;
1015 close $out || error("failed saving to $newfile: $!", $cleanup);
1016 rename($newfile, "$config{wikistatedir}/indexdb") ||
1017 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1022 sub template_file ($) { #{{{
1025 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1026 return "$dir/$template" if -e "$dir/$template";
1031 sub template_params (@) { #{{{
1032 my $filename=template_file(shift);
1034 if (! defined $filename) {
1035 return if wantarray;
1041 my $text_ref = shift;
1042 ${$text_ref} = decode_utf8(${$text_ref});
1044 filename => $filename,
1045 loop_context_vars => 1,
1046 die_on_bad_params => 0,
1049 return wantarray ? @ret : {@ret};
1052 sub template ($;@) { #{{{
1053 require HTML::Template;
1054 return HTML::Template->new(template_params(@_));
1057 sub misctemplate ($$;@) { #{{{
1061 my $template=template("misc.tmpl");
1064 indexlink => indexlink(),
1065 wikiname => $config{wikiname},
1066 pagebody => $pagebody,
1067 baseurl => baseurl(),
1070 run_hooks(pagetemplate => sub {
1071 shift->(page => "", destpage => "", template => $template);
1073 return $template->output;
1076 sub hook (@) { # {{{
1079 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1080 error 'hook requires type, call, and id parameters';
1083 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1085 $hooks{$param{type}}{$param{id}}=\%param;
1089 sub run_hooks ($$) { # {{{
1090 # Calls the given sub for each hook of the given type,
1091 # passing it the hook function to call.
1095 if (exists $hooks{$type}) {
1097 foreach my $id (keys %{$hooks{$type}}) {
1098 if ($hooks{$type}{$id}{last}) {
1099 push @deferred, $id;
1102 $sub->($hooks{$type}{$id}{call});
1104 foreach my $id (@deferred) {
1105 $sub->($hooks{$type}{$id}{call});
1112 sub globlist_to_pagespec ($) { #{{{
1113 my @globlist=split(' ', shift);
1116 foreach my $glob (@globlist) {
1117 if ($glob=~/^!(.*)/) {
1125 my $spec=join(' or ', @spec);
1127 my $skip=join(' and ', @skip);
1129 $spec="$skip and ($spec)";
1138 sub is_globlist ($) { #{{{
1140 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1143 sub safequote ($) { #{{{
1149 sub add_depends ($$) { #{{{
1153 return unless pagespec_valid($pagespec);
1155 if (! exists $depends{$page}) {
1156 $depends{$page}=$pagespec;
1159 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1165 sub file_pruned ($$) { #{{{
1167 my $file=File::Spec->canonpath(shift);
1168 my $base=File::Spec->canonpath(shift);
1169 $file =~ s#^\Q$base\E/+##;
1171 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1172 return $file =~ m/$regexp/ && $file ne $base;
1176 # Only use gettext in the rare cases it's needed.
1177 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1178 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1179 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1180 if (! $gettext_obj) {
1181 $gettext_obj=eval q{
1182 use Locale::gettext q{textdomain};
1183 Locale::gettext->domain('ikiwiki')
1191 return $gettext_obj->get(shift);
1198 sub pagespec_merge ($$) { #{{{
1202 return $a if $a eq $b;
1204 # Support for old-style GlobLists.
1205 if (is_globlist($a)) {
1206 $a=globlist_to_pagespec($a);
1208 if (is_globlist($b)) {
1209 $b=globlist_to_pagespec($b);
1212 return "($a) or ($b)";
1215 sub pagespec_translate ($) { #{{{
1218 # Support for old-style GlobLists.
1219 if (is_globlist($spec)) {
1220 $spec=globlist_to_pagespec($spec);
1223 # Convert spec to perl code.
1226 \s* # ignore whitespace
1227 ( # 1: match a single word
1234 \w+\([^\)]*\) # command(params)
1236 [^\s()]+ # any other text
1238 \s* # ignore whitespace
1241 if (lc $word eq 'and') {
1244 elsif (lc $word eq 'or') {
1247 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1250 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1251 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1252 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1259 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1263 if (! length $code) {
1268 return eval 'sub { my $page=shift; '.$code.' }';
1271 sub pagespec_match ($$;@) { #{{{
1276 # Backwards compatability with old calling convention.
1278 unshift @params, 'location';
1281 my $sub=pagespec_translate($spec);
1282 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1283 return $sub->($page, @params);
1286 sub pagespec_valid ($) { #{{{
1289 my $sub=pagespec_translate($spec);
1293 package IkiWiki::FailReason;
1296 '""' => sub { ${$_[0]} },
1298 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1305 return bless \$value, $class;
1308 package IkiWiki::SuccessReason;
1311 '""' => sub { ${$_[0]} },
1313 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1320 return bless \$value, $class;
1323 package IkiWiki::PageSpec;
1325 sub match_glob ($$;@) { #{{{
1330 my $from=exists $params{location} ? $params{location} : '';
1333 if ($glob =~ m!^\./!) {
1334 $from=~s#/?[^/]+$##;
1336 $glob="$from/$glob" if length $from;
1339 # turn glob into safe regexp
1340 $glob=quotemeta($glob);
1344 if ($page=~/^$glob$/i) {
1345 if (! IkiWiki::isinternal($page) || $params{internal}) {
1346 return IkiWiki::SuccessReason->new("$glob matches $page");
1349 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1353 return IkiWiki::FailReason->new("$glob does not match $page");
1357 sub match_internal ($$;@) { #{{{
1358 return match_glob($_[0], $_[1], @_, internal => 1)
1361 sub match_link ($$;@) { #{{{
1366 my $from=exists $params{location} ? $params{location} : '';
1369 if ($link =~ m!^\.! && defined $from) {
1370 $from=~s#/?[^/]+$##;
1372 $link="$from/$link" if length $from;
1375 my $links = $IkiWiki::links{$page};
1376 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1377 my $bestlink = IkiWiki::bestlink($from, $link);
1378 foreach my $p (@{$links}) {
1379 if (length $bestlink) {
1380 return IkiWiki::SuccessReason->new("$page links to $link")
1381 if $bestlink eq IkiWiki::bestlink($page, $p);
1384 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1385 if match_glob($p, $link, %params);
1388 return IkiWiki::FailReason->new("$page does not link to $link");
1391 sub match_backlink ($$;@) { #{{{
1392 return match_link($_[1], $_[0], @_);
1395 sub match_created_before ($$;@) { #{{{
1399 if (exists $IkiWiki::pagectime{$testpage}) {
1400 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1401 return IkiWiki::SuccessReason->new("$page created before $testpage");
1404 return IkiWiki::FailReason->new("$page not created before $testpage");
1408 return IkiWiki::FailReason->new("$testpage has no ctime");
1412 sub match_created_after ($$;@) { #{{{
1416 if (exists $IkiWiki::pagectime{$testpage}) {
1417 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1418 return IkiWiki::SuccessReason->new("$page created after $testpage");
1421 return IkiWiki::FailReason->new("$page not created after $testpage");
1425 return IkiWiki::FailReason->new("$testpage has no ctime");
1429 sub match_creation_day ($$;@) { #{{{
1430 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1431 return IkiWiki::SuccessReason->new('creation_day matched');
1434 return IkiWiki::FailReason->new('creation_day did not match');
1438 sub match_creation_month ($$;@) { #{{{
1439 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1440 return IkiWiki::SuccessReason->new('creation_month matched');
1443 return IkiWiki::FailReason->new('creation_month did not match');
1447 sub match_creation_year ($$;@) { #{{{
1448 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1449 return IkiWiki::SuccessReason->new('creation_year matched');
1452 return IkiWiki::FailReason->new('creation_year did not match');