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}],
89 account_creation_password => "",
90 prefix_directives => 0,
92 cgi_disable_uploads => 1,
95 sub checkconfig () { #{{{
96 # locale stuff; avoid LC_ALL since it overrides everything
97 if (defined $ENV{LC_ALL}) {
98 $ENV{LANG} = $ENV{LC_ALL};
101 if (defined $config{locale}) {
102 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
103 $ENV{LANG}=$config{locale};
108 if (ref $config{ENV} eq 'HASH') {
109 foreach my $val (keys %{$config{ENV}}) {
110 $ENV{$val}=$config{ENV}{$val};
114 if ($config{w3mmode}) {
115 eval q{use Cwd q{abs_path}};
117 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
118 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
119 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
120 unless $config{cgiurl} =~ m!file:///!;
121 $config{url}="file://".$config{destdir};
124 if ($config{cgi} && ! length $config{url}) {
125 error(gettext("Must specify url to wiki with --url when using --cgi"));
128 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
129 unless exists $config{wikistatedir};
132 eval qq{use IkiWiki::Rcs::$config{rcs}};
134 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
138 require IkiWiki::Rcs::Stub;
141 if (exists $config{umask}) {
142 umask(possibly_foolish_untaint($config{umask}));
145 run_hooks(checkconfig => sub { shift->() });
150 sub loadplugins () { #{{{
151 if (defined $config{libdir}) {
152 unshift @INC, possibly_foolish_untaint($config{libdir});
155 loadplugin($_) foreach @{$config{plugin}};
157 run_hooks(getopt => sub { shift->() });
158 if (grep /^-/, @ARGV) {
159 print STDERR "Unknown option: $_\n"
160 foreach grep /^-/, @ARGV;
167 sub loadplugin ($) { #{{{
170 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
172 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
173 "$installdir/lib/ikiwiki") {
174 if (defined $dir && -x "$dir/plugins/$plugin") {
175 require IkiWiki::Plugin::external;
176 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
181 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
184 error("Failed to load plugin $mod: $@");
189 sub error ($;$) { #{{{
192 log_message('err' => $message) if $config{syslog};
193 if (defined $cleaner) {
200 return unless $config{verbose};
201 return log_message(debug => @_);
205 sub log_message ($$) { #{{{
208 if ($config{syslog}) {
211 Sys::Syslog::setlogsock('unix');
212 Sys::Syslog::openlog('ikiwiki', '', 'user');
216 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
219 elsif (! $config{cgi}) {
223 return print STDERR "@_\n";
227 sub possibly_foolish_untaint ($) { #{{{
229 my ($untainted)=$tainted=~/(.*)/s;
233 sub basename ($) { #{{{
240 sub dirname ($) { #{{{
247 sub pagetype ($) { #{{{
250 if ($page =~ /\.([^.]+)$/) {
251 return $1 if exists $hooks{htmlize}{$1};
256 sub isinternal ($) { #{{{
258 return exists $pagesources{$page} &&
259 $pagesources{$page} =~ /\._([^.]+)$/;
262 sub pagename ($) { #{{{
265 my $type=pagetype($file);
267 $page=~s/\Q.$type\E*$// if defined $type;
271 sub targetpage ($$) { #{{{
275 if (! $config{usedirs} || $page =~ /^index$/ ) {
276 return $page.".".$ext;
278 return $page."/index.".$ext;
282 sub htmlpage ($) { #{{{
285 return targetpage($page, $config{htmlext});
288 sub srcfile_stat { #{{{
292 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
293 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
294 return "$dir/$file", stat(_) if -e "$dir/$file";
296 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
300 sub srcfile ($;$) { #{{{
301 return (srcfile_stat(@_))[0];
304 sub add_underlay ($) { #{{{
308 unshift @{$config{underlaydirs}}, $dir;
311 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
317 sub readfile ($;$$) { #{{{
323 error("cannot read a symlink ($file)");
327 open (my $in, "<", $file) || error("failed to read $file: $!");
328 binmode($in) if ($binary);
329 return \*$in if $wantfd;
331 close $in || error("failed to read $file: $!");
335 sub prep_writefile ($$) { #{{{
340 while (length $test) {
341 if (-l "$destdir/$test") {
342 error("cannot write to a symlink ($test)");
344 $test=dirname($test);
347 my $dir=dirname("$destdir/$file");
350 foreach my $s (split(m!/+!, $dir)) {
353 mkdir($d) || error("failed to create directory $d: $!");
361 sub writefile ($$$;$$) { #{{{
362 my $file=shift; # can include subdirs
363 my $destdir=shift; # directory to put file in
368 prep_writefile($file, $destdir);
370 my $newfile="$destdir/$file.ikiwiki-new";
372 error("cannot write to a symlink ($newfile)");
375 my $cleanup = sub { unlink($newfile) };
376 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
377 binmode($out) if ($binary);
379 $writer->(\*$out, $cleanup);
382 print $out $content or error("failed writing to $newfile: $!", $cleanup);
384 close $out || error("failed saving $newfile: $!", $cleanup);
385 rename($newfile, "$destdir/$file") ||
386 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
392 sub will_render ($$;$) { #{{{
397 # Important security check.
398 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
399 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
400 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
403 if (! $clear || $cleared{$page}) {
404 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
407 foreach my $old (@{$renderedfiles{$page}}) {
408 delete $destsources{$old};
410 $renderedfiles{$page}=[$dest];
413 $destsources{$dest}=$page;
418 sub bestlink ($$) { #{{{
423 if ($link=~s/^\/+//) {
431 $l.="/" if length $l;
434 if (exists $links{$l}) {
437 elsif (exists $pagecase{lc $l}) {
438 return $pagecase{lc $l};
440 } while $cwd=~s!/?[^/]+$!!;
442 if (length $config{userdir}) {
443 my $l = "$config{userdir}/".lc($link);
444 if (exists $links{$l}) {
447 elsif (exists $pagecase{lc $l}) {
448 return $pagecase{lc $l};
452 #print STDERR "warning: page $page, broken link: $link\n";
456 sub isinlinableimage ($) { #{{{
459 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
462 sub pagetitle ($;$) { #{{{
467 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
470 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
476 sub titlepage ($) { #{{{
478 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
482 sub linkpage ($) { #{{{
484 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
488 sub cgiurl (@) { #{{{
491 return $config{cgiurl}."?".
492 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
495 sub baseurl (;$) { #{{{
498 return "$config{url}/" if ! defined $page;
500 $page=htmlpage($page);
502 $page=~s/[^\/]+\//..\//g;
506 sub abs2rel ($$) { #{{{
507 # Work around very innefficient behavior in File::Spec if abs2rel
508 # is passed two relative paths. It's much faster if paths are
509 # absolute! (Debian bug #376658; fixed in debian unstable now)
514 my $ret=File::Spec->abs2rel($path, $base);
515 $ret=~s/^// if defined $ret;
519 sub displaytime ($;$) { #{{{
522 if (! defined $format) {
523 $format=$config{timeformat};
526 # strftime doesn't know about encodings, so make sure
527 # its output is properly treated as utf8
528 return decode_utf8(POSIX::strftime($format, localtime($time)));
531 sub beautify_urlpath ($) { #{{{
534 if ($config{usedirs}) {
535 $url =~ s!/index.$config{htmlext}$!/!;
538 # Ensure url is not an empty link, and
539 # if it's relative, make that explicit to avoid colon confusion.
547 sub urlto ($$) { #{{{
552 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
555 if (! $destsources{$to}) {
559 my $link = abs2rel($to, dirname(htmlpage($from)));
561 return beautify_urlpath($link);
564 sub htmllink ($$$;@) { #{{{
565 my $lpage=shift; # the page doing the linking
566 my $page=shift; # the page that will contain the link (different for inline)
573 if (! $opts{forcesubpage}) {
574 $bestlink=bestlink($lpage, $link);
577 $bestlink="$lpage/".lc($link);
581 if (defined $opts{linktext}) {
582 $linktext=$opts{linktext};
585 $linktext=pagetitle(basename($link));
588 return "<span class=\"selflink\">$linktext</span>"
589 if length $bestlink && $page eq $bestlink &&
590 ! defined $opts{anchor};
592 if (! $destsources{$bestlink}) {
593 $bestlink=htmlpage($bestlink);
595 if (! $destsources{$bestlink}) {
596 return $linktext unless length $config{cgiurl};
597 return "<span class=\"createlink\"><a href=\"".
603 "\" rel=\"nofollow\">?</a>$linktext</span>"
607 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
608 $bestlink=beautify_urlpath($bestlink);
610 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
611 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
614 if (defined $opts{anchor}) {
615 $bestlink.="#".$opts{anchor};
619 if (defined $opts{rel}) {
620 push @attrs, ' rel="'.$opts{rel}.'"';
622 if (defined $opts{class}) {
623 push @attrs, ' class="'.$opts{class}.'"';
626 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
629 sub userlink ($) { #{{{
632 my $oiduser=eval { openiduser($user) };
633 if (defined $oiduser) {
634 return "<a href=\"$user\">$oiduser</a>";
637 eval q{use CGI 'escapeHTML'};
640 return htmllink("", "", escapeHTML(
641 length $config{userdir} ? $config{userdir}."/".$user : $user
642 ), noimageinline => 1);
646 sub htmlize ($$$$) { #{{{
652 my $oneline = $content !~ /\n/;
654 if (exists $hooks{htmlize}{$type}) {
655 $content=$hooks{htmlize}{$type}{call}->(
661 error("htmlization of $type not supported");
664 run_hooks(sanitize => sub {
667 destpage => $destpage,
673 # hack to get rid of enclosing junk added by markdown
674 # and other htmlizers
676 $content=~s/<\/p>$//i;
683 sub linkify ($$$) { #{{{
688 run_hooks(linkify => sub {
691 destpage => $destpage,
700 our $preprocess_preview=0;
701 sub preprocess ($$$;$$) { #{{{
702 my $page=shift; # the page the data comes from
703 my $destpage=shift; # the page the data will appear in (different for inline)
708 # Using local because it needs to be set within any nested calls
710 local $preprocess_preview=$preview if defined $preview;
717 if (length $escape) {
718 return "[[$prefix$command $params]]";
720 elsif (exists $hooks{preprocess}{$command}) {
721 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
722 # Note: preserve order of params, some plugins may
723 # consider it significant.
726 (?:([-\w]+)=)? # 1: named parameter key?
728 """(.*?)""" # 2: triple-quoted value
730 "([^"]+)" # 3: single-quoted value
732 (\S+) # 4: unquoted value
734 (?:\s+|$) # delimiter to next param
752 push @params, $key, $val;
755 push @params, $val, '';
758 if ($preprocessing{$page}++ > 3) {
759 # Avoid loops of preprocessed pages preprocessing
760 # other pages that preprocess them, etc.
761 #translators: The first parameter is a
762 #translators: preprocessor directive name,
763 #translators: the second a page name, the
764 #translators: third a number.
765 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
766 $command, $page, $preprocessing{$page}).
771 $ret=$hooks{preprocess}{$command}{call}->(
774 destpage => $destpage,
775 preview => $preprocess_preview,
779 # use void context during scan pass
780 $hooks{preprocess}{$command}{call}->(
783 destpage => $destpage,
784 preview => $preprocess_preview,
788 $preprocessing{$page}--;
792 return "[[$prefix$command $params]]";
797 if ($config{prefix_directives}) {
800 \[\[(!) # directive open; 2: prefix
801 ([-\w]+) # 3: command
802 ( # 4: the parameters..
803 \s+ # Must have space if parameters present
805 (?:[-\w]+=)? # named parameter key?
807 """.*?""" # triple-quoted value
809 "[^"]+" # single-quoted value
811 [^\s\]]+ # unquoted value
813 \s* # whitespace or end
816 *)? # 0 or more parameters
817 \]\] # directive closed
822 \[\[(!?) # directive open; 2: optional prefix
823 ([-\w]+) # 3: command
825 ( # 4: the parameters..
827 (?:[-\w]+=)? # named parameter key?
829 """.*?""" # triple-quoted value
831 "[^"]+" # single-quoted value
833 [^\s\]]+ # unquoted value
835 \s* # whitespace or end
838 *) # 0 or more parameters
839 \]\] # directive closed
843 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
847 sub filter ($$$) { #{{{
852 run_hooks(filter => sub {
853 $content=shift->(page => $page, destpage => $destpage,
854 content => $content);
860 sub indexlink () { #{{{
861 return "<a href=\"$config{url}\">$config{wikiname}</a>";
866 sub lockwiki (;$) { #{{{
867 my $wait=@_ ? shift : 1;
868 # Take an exclusive lock on the wiki to prevent multiple concurrent
869 # run issues. The lock will be dropped on program exit.
870 if (! -d $config{wikistatedir}) {
871 mkdir($config{wikistatedir});
873 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
874 error ("cannot write to $config{wikistatedir}/lockfile: $!");
875 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
877 debug("wiki seems to be locked, waiting for lock");
878 my $wait=600; # arbitrary, but don't hang forever to
879 # prevent process pileup
881 return if flock($wikilock, 2 | 4);
884 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
893 sub unlockwiki () { #{{{
894 return close($wikilock) if $wikilock;
900 sub commit_hook_enabled () { #{{{
901 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
902 error("cannot write to $config{wikistatedir}/commitlock: $!");
903 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
904 close($commitlock) || error("failed closing commitlock: $!");
907 close($commitlock) || error("failed closing commitlock: $!");
911 sub disable_commit_hook () { #{{{
912 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
913 error("cannot write to $config{wikistatedir}/commitlock: $!");
914 if (! flock($commitlock, 2)) { # LOCK_EX
915 error("failed to get commit lock");
920 sub enable_commit_hook () { #{{{
921 return close($commitlock) if $commitlock;
925 sub loadindex () { #{{{
926 %oldrenderedfiles=%pagectime=();
927 if (! $config{rebuild}) {
928 %pagesources=%pagemtime=%oldlinks=%links=%depends=
929 %destsources=%renderedfiles=%pagecase=%pagestate=();
932 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
933 if (-e "$config{wikistatedir}/index") {
934 system("ikiwiki-transition", "indexdb", $config{srcdir});
935 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
941 my $ret=Storable::fd_retrieve($in);
942 if (! defined $ret) {
946 foreach my $src (keys %index) {
947 my %d=%{$index{$src}};
948 my $page=pagename($src);
949 $pagectime{$page}=$d{ctime};
950 if (! $config{rebuild}) {
951 $pagesources{$page}=$src;
952 $pagemtime{$page}=$d{mtime};
953 $renderedfiles{$page}=$d{dest};
954 if (exists $d{links} && ref $d{links}) {
955 $links{$page}=$d{links};
956 $oldlinks{$page}=[@{$d{links}}];
958 if (exists $d{depends}) {
959 $depends{$page}=$d{depends};
961 if (exists $d{state}) {
962 $pagestate{$page}=$d{state};
965 $oldrenderedfiles{$page}=[@{$d{dest}}];
967 foreach my $page (keys %pagesources) {
968 $pagecase{lc $page}=$page;
970 foreach my $page (keys %renderedfiles) {
971 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
976 sub saveindex () { #{{{
977 run_hooks(savestate => sub { shift->() });
980 foreach my $type (keys %hooks) {
981 $hookids{$_}=1 foreach keys %{$hooks{$type}};
983 my @hookids=keys %hookids;
985 if (! -d $config{wikistatedir}) {
986 mkdir($config{wikistatedir});
988 my $newfile="$config{wikistatedir}/indexdb.new";
989 my $cleanup = sub { unlink($newfile) };
990 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
992 foreach my $page (keys %pagemtime) {
993 next unless $pagemtime{$page};
994 my $src=$pagesources{$page};
997 ctime => $pagectime{$page},
998 mtime => $pagemtime{$page},
999 dest => $renderedfiles{$page},
1000 links => $links{$page},
1003 if (exists $depends{$page}) {
1004 $index{$src}{depends} = $depends{$page};
1007 if (exists $pagestate{$page}) {
1008 foreach my $id (@hookids) {
1009 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1010 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1015 my $ret=Storable::nstore_fd(\%index, $out);
1016 return if ! defined $ret || ! $ret;
1017 close $out || error("failed saving to $newfile: $!", $cleanup);
1018 rename($newfile, "$config{wikistatedir}/indexdb") ||
1019 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1024 sub template_file ($) { #{{{
1027 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1028 return "$dir/$template" if -e "$dir/$template";
1033 sub template_params (@) { #{{{
1034 my $filename=template_file(shift);
1036 if (! defined $filename) {
1037 return if wantarray;
1043 my $text_ref = shift;
1044 ${$text_ref} = decode_utf8(${$text_ref});
1046 filename => $filename,
1047 loop_context_vars => 1,
1048 die_on_bad_params => 0,
1051 return wantarray ? @ret : {@ret};
1054 sub template ($;@) { #{{{
1055 require HTML::Template;
1056 return HTML::Template->new(template_params(@_));
1059 sub misctemplate ($$;@) { #{{{
1063 my $template=template("misc.tmpl");
1066 indexlink => indexlink(),
1067 wikiname => $config{wikiname},
1068 pagebody => $pagebody,
1069 baseurl => baseurl(),
1072 run_hooks(pagetemplate => sub {
1073 shift->(page => "", destpage => "", template => $template);
1075 return $template->output;
1078 sub hook (@) { # {{{
1081 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1082 error 'hook requires type, call, and id parameters';
1085 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1087 $hooks{$param{type}}{$param{id}}=\%param;
1091 sub run_hooks ($$) { # {{{
1092 # Calls the given sub for each hook of the given type,
1093 # passing it the hook function to call.
1097 if (exists $hooks{$type}) {
1099 foreach my $id (keys %{$hooks{$type}}) {
1100 if ($hooks{$type}{$id}{last}) {
1101 push @deferred, $id;
1104 $sub->($hooks{$type}{$id}{call});
1106 foreach my $id (@deferred) {
1107 $sub->($hooks{$type}{$id}{call});
1114 sub globlist_to_pagespec ($) { #{{{
1115 my @globlist=split(' ', shift);
1118 foreach my $glob (@globlist) {
1119 if ($glob=~/^!(.*)/) {
1127 my $spec=join(' or ', @spec);
1129 my $skip=join(' and ', @skip);
1131 $spec="$skip and ($spec)";
1140 sub is_globlist ($) { #{{{
1142 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1145 sub safequote ($) { #{{{
1151 sub add_depends ($$) { #{{{
1155 return unless pagespec_valid($pagespec);
1157 if (! exists $depends{$page}) {
1158 $depends{$page}=$pagespec;
1161 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1167 sub file_pruned ($$) { #{{{
1169 my $file=File::Spec->canonpath(shift);
1170 my $base=File::Spec->canonpath(shift);
1171 $file =~ s#^\Q$base\E/+##;
1173 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1174 return $file =~ m/$regexp/ && $file ne $base;
1178 # Only use gettext in the rare cases it's needed.
1179 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1180 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1181 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1182 if (! $gettext_obj) {
1183 $gettext_obj=eval q{
1184 use Locale::gettext q{textdomain};
1185 Locale::gettext->domain('ikiwiki')
1193 return $gettext_obj->get(shift);
1200 sub yesno ($) { #{{{
1203 return (defined $val && lc($val) eq gettext("yes"));
1206 sub pagespec_merge ($$) { #{{{
1210 return $a if $a eq $b;
1212 # Support for old-style GlobLists.
1213 if (is_globlist($a)) {
1214 $a=globlist_to_pagespec($a);
1216 if (is_globlist($b)) {
1217 $b=globlist_to_pagespec($b);
1220 return "($a) or ($b)";
1223 sub pagespec_translate ($) { #{{{
1226 # Support for old-style GlobLists.
1227 if (is_globlist($spec)) {
1228 $spec=globlist_to_pagespec($spec);
1231 # Convert spec to perl code.
1234 \s* # ignore whitespace
1235 ( # 1: match a single word
1242 \w+\([^\)]*\) # command(params)
1244 [^\s()]+ # any other text
1246 \s* # ignore whitespace
1249 if (lc $word eq 'and') {
1252 elsif (lc $word eq 'or') {
1255 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1258 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1259 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1260 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1267 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1271 if (! length $code) {
1276 return eval 'sub { my $page=shift; '.$code.' }';
1279 sub pagespec_match ($$;@) { #{{{
1284 # Backwards compatability with old calling convention.
1286 unshift @params, 'location';
1289 my $sub=pagespec_translate($spec);
1290 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1291 return $sub->($page, @params);
1294 sub pagespec_valid ($) { #{{{
1297 my $sub=pagespec_translate($spec);
1301 sub glob2re ($) { #{{{
1302 my $re=quotemeta(shift);
1308 package IkiWiki::FailReason;
1311 '""' => sub { ${$_[0]} },
1313 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1320 return bless \$value, $class;
1323 package IkiWiki::SuccessReason;
1326 '""' => sub { ${$_[0]} },
1328 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1335 return bless \$value, $class;
1338 package IkiWiki::PageSpec;
1340 sub match_glob ($$;@) { #{{{
1345 my $from=exists $params{location} ? $params{location} : '';
1348 if ($glob =~ m!^\./!) {
1349 $from=~s#/?[^/]+$##;
1351 $glob="$from/$glob" if length $from;
1354 my $regexp=IkiWiki::glob2re($glob);
1355 if ($page=~/^$regexp$/i) {
1356 if (! IkiWiki::isinternal($page) || $params{internal}) {
1357 return IkiWiki::SuccessReason->new("$glob matches $page");
1360 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1364 return IkiWiki::FailReason->new("$glob does not match $page");
1368 sub match_internal ($$;@) { #{{{
1369 return match_glob($_[0], $_[1], @_, internal => 1)
1372 sub match_link ($$;@) { #{{{
1377 my $from=exists $params{location} ? $params{location} : '';
1380 if ($link =~ m!^\.! && defined $from) {
1381 $from=~s#/?[^/]+$##;
1383 $link="$from/$link" if length $from;
1386 my $links = $IkiWiki::links{$page};
1387 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1388 my $bestlink = IkiWiki::bestlink($from, $link);
1389 foreach my $p (@{$links}) {
1390 if (length $bestlink) {
1391 return IkiWiki::SuccessReason->new("$page links to $link")
1392 if $bestlink eq IkiWiki::bestlink($page, $p);
1395 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1396 if match_glob($p, $link, %params);
1399 return IkiWiki::FailReason->new("$page does not link to $link");
1402 sub match_backlink ($$;@) { #{{{
1403 return match_link($_[1], $_[0], @_);
1406 sub match_created_before ($$;@) { #{{{
1410 if (exists $IkiWiki::pagectime{$testpage}) {
1411 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1412 return IkiWiki::SuccessReason->new("$page created before $testpage");
1415 return IkiWiki::FailReason->new("$page not created before $testpage");
1419 return IkiWiki::FailReason->new("$testpage has no ctime");
1423 sub match_created_after ($$;@) { #{{{
1427 if (exists $IkiWiki::pagectime{$testpage}) {
1428 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1429 return IkiWiki::SuccessReason->new("$page created after $testpage");
1432 return IkiWiki::FailReason->new("$page not created after $testpage");
1436 return IkiWiki::FailReason->new("$testpage has no ctime");
1440 sub match_creation_day ($$;@) { #{{{
1441 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1442 return IkiWiki::SuccessReason->new('creation_day matched');
1445 return IkiWiki::FailReason->new('creation_day did not match');
1449 sub match_creation_month ($$;@) { #{{{
1450 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1451 return IkiWiki::SuccessReason->new('creation_month matched');
1454 return IkiWiki::FailReason->new('creation_month did not match');
1458 sub match_creation_year ($$;@) { #{{{
1459 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1460 return IkiWiki::SuccessReason->new('creation_year matched');
1463 return IkiWiki::FailReason->new('creation_year did not match');