8 use URI::Escape q{uri_escape_utf8};
10 use open qw{:utf8 :std};
12 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
13 %pagestate %renderedfiles %oldrenderedfiles %pagesources
14 %destsources %depends %hooks %forcerebuild $gettext_obj};
16 use Exporter q{import};
17 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
18 bestlink htmllink readfile writefile pagetype srcfile pagename
19 displaytime will_render gettext urlto targetpage
21 %config %links %pagestate %renderedfiles
22 %pagesources %destsources);
23 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
24 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
25 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
30 memoize("pagespec_translate");
31 memoize("file_pruned");
33 sub defaultconfig () { #{{{
35 wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
36 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
37 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
40 wiki_link_regexp => qr{
41 \[\[(?=[^!]) # beginning of link
43 ([^\]\|]+) # 1: link text
47 ([^\s\]#]+) # 2: page to link to
49 \# # '#', beginning of anchor
50 ([^\s\]]+) # 3: anchor text
55 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
56 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
60 default_pageext => "mdwn",
81 gitorigin_branch => "origin",
82 gitmaster_branch => "master",
86 templatedir => "$installdir/share/ikiwiki/templates",
87 underlaydir => "$installdir/share/ikiwiki/basewiki",
92 plugin => [qw{mdwn inline htmlscrubber passwordauth openid signinedit
93 lockedit conditional}],
102 account_creation_password => "",
103 prefix_directives => 0,
106 sub checkconfig () { #{{{
107 # locale stuff; avoid LC_ALL since it overrides everything
108 if (defined $ENV{LC_ALL}) {
109 $ENV{LANG} = $ENV{LC_ALL};
112 if (defined $config{locale}) {
113 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
114 $ENV{LANG}=$config{locale};
119 if ($config{w3mmode}) {
120 eval q{use Cwd q{abs_path}};
122 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
123 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
124 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
125 unless $config{cgiurl} =~ m!file:///!;
126 $config{url}="file://".$config{destdir};
129 if ($config{cgi} && ! length $config{url}) {
130 error(gettext("Must specify url to wiki with --url when using --cgi"));
133 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
134 unless exists $config{wikistatedir};
137 eval qq{use IkiWiki::Rcs::$config{rcs}};
139 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
143 require IkiWiki::Rcs::Stub;
146 if (exists $config{umask}) {
147 umask(possibly_foolish_untaint($config{umask}));
150 if (!$config{prefix_directives}) {
151 $config{wiki_link_regexp} = qr{
152 \[\[ # beginning of link
154 ([^\]\|\n\s]+) # 1: link text
158 ([^\s\]#]+) # 2: page to link to
160 \# # '#', beginning of anchor
161 ([^\s\]]+) # 3: anchor text
168 run_hooks(checkconfig => sub { shift->() });
173 sub loadplugins () { #{{{
174 if (defined $config{libdir}) {
175 unshift @INC, possibly_foolish_untaint($config{libdir});
178 loadplugin($_) foreach @{$config{plugin}};
180 run_hooks(getopt => sub { shift->() });
181 if (grep /^-/, @ARGV) {
182 print STDERR "Unknown option: $_\n"
183 foreach grep /^-/, @ARGV;
190 sub loadplugin ($) { #{{{
193 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
195 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
196 "$installdir/lib/ikiwiki") {
197 if (defined $dir && -x "$dir/plugins/$plugin") {
198 require IkiWiki::Plugin::external;
199 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
204 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
207 error("Failed to load plugin $mod: $@");
212 sub error ($;$) { #{{{
216 print "Content-type: text/html\n\n";
217 print misctemplate(gettext("Error"),
218 "<p>".gettext("Error").": $message</p>");
220 log_message('err' => $message) if $config{syslog};
221 if (defined $cleaner) {
228 return unless $config{verbose};
229 return log_message(debug => @_);
233 sub log_message ($$) { #{{{
236 if ($config{syslog}) {
239 Sys::Syslog::setlogsock('unix');
240 Sys::Syslog::openlog('ikiwiki', '', 'user');
244 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
247 elsif (! $config{cgi}) {
251 return print STDERR "@_\n";
255 sub possibly_foolish_untaint ($) { #{{{
257 my ($untainted)=$tainted=~/(.*)/s;
261 sub basename ($) { #{{{
268 sub dirname ($) { #{{{
275 sub pagetype ($) { #{{{
278 if ($page =~ /\.([^.]+)$/) {
279 return $1 if exists $hooks{htmlize}{$1};
284 sub pagename ($) { #{{{
287 my $type=pagetype($file);
289 $page=~s/\Q.$type\E*$// if defined $type;
293 sub targetpage ($$) { #{{{
297 if (! $config{usedirs} || $page =~ /^index$/ ) {
298 return $page.".".$ext;
300 return $page."/index.".$ext;
304 sub htmlpage ($) { #{{{
307 return targetpage($page, $config{htmlext});
310 sub srcfile ($) { #{{{
313 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
314 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
315 return "$dir/$file" if -e "$dir/$file";
317 error("internal error: $file cannot be found in $config{srcdir} or underlay");
321 sub add_underlay ($) { #{{{
325 unshift @{$config{underlaydirs}}, $dir;
328 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
334 sub readfile ($;$$) { #{{{
340 error("cannot read a symlink ($file)");
344 open (my $in, "<", $file) || error("failed to read $file: $!");
345 binmode($in) if ($binary);
346 return \*$in if $wantfd;
348 close $in || error("failed to read $file: $!");
352 sub writefile ($$$;$$) { #{{{
353 my $file=shift; # can include subdirs
354 my $destdir=shift; # directory to put file in
360 while (length $test) {
361 if (-l "$destdir/$test") {
362 error("cannot write to a symlink ($test)");
364 $test=dirname($test);
366 my $newfile="$destdir/$file.ikiwiki-new";
368 error("cannot write to a symlink ($newfile)");
371 my $dir=dirname($newfile);
374 foreach my $s (split(m!/+!, $dir)) {
377 mkdir($d) || error("failed to create directory $d: $!");
382 my $cleanup = sub { unlink($newfile) };
383 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
384 binmode($out) if ($binary);
386 $writer->(\*$out, $cleanup);
389 print $out $content or error("failed writing to $newfile: $!", $cleanup);
391 close $out || error("failed saving $newfile: $!", $cleanup);
392 rename($newfile, "$destdir/$file") ||
393 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
399 sub will_render ($$;$) { #{{{
404 # Important security check.
405 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
406 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
407 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
410 if (! $clear || $cleared{$page}) {
411 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
414 foreach my $old (@{$renderedfiles{$page}}) {
415 delete $destsources{$old};
417 $renderedfiles{$page}=[$dest];
420 $destsources{$dest}=$page;
425 sub bestlink ($$) { #{{{
430 if ($link=~s/^\/+//) {
438 $l.="/" if length $l;
441 if (exists $links{$l}) {
444 elsif (exists $pagecase{lc $l}) {
445 return $pagecase{lc $l};
447 } while $cwd=~s!/?[^/]+$!!;
449 if (length $config{userdir}) {
450 my $l = "$config{userdir}/".lc($link);
451 if (exists $links{$l}) {
454 elsif (exists $pagecase{lc $l}) {
455 return $pagecase{lc $l};
459 #print STDERR "warning: page $page, broken link: $link\n";
463 sub isinlinableimage ($) { #{{{
466 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
469 sub pagetitle ($;$) { #{{{
474 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
477 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
483 sub titlepage ($) { #{{{
485 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
489 sub linkpage ($) { #{{{
491 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
495 sub cgiurl (@) { #{{{
498 return $config{cgiurl}."?".
499 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
502 sub baseurl (;$) { #{{{
505 return "$config{url}/" if ! defined $page;
507 $page=htmlpage($page);
509 $page=~s/[^\/]+\//..\//g;
513 sub abs2rel ($$) { #{{{
514 # Work around very innefficient behavior in File::Spec if abs2rel
515 # is passed two relative paths. It's much faster if paths are
516 # absolute! (Debian bug #376658; fixed in debian unstable now)
521 my $ret=File::Spec->abs2rel($path, $base);
522 $ret=~s/^// if defined $ret;
526 sub displaytime ($;$) { #{{{
529 if (! defined $format) {
530 $format=$config{timeformat};
533 # strftime doesn't know about encodings, so make sure
534 # its output is properly treated as utf8
535 return decode_utf8(POSIX::strftime($format, localtime($time)));
538 sub beautify_url ($) { #{{{
541 if ($config{usedirs}) {
542 $url =~ s!/index.$config{htmlext}$!/!;
544 $url =~ s!^$!./!; # Browsers don't like empty links...
549 sub urlto ($$) { #{{{
554 return beautify_url(baseurl($from));
557 if (! $destsources{$to}) {
561 my $link = abs2rel($to, dirname(htmlpage($from)));
563 return beautify_url($link);
566 sub htmllink ($$$;@) { #{{{
567 my $lpage=shift; # the page doing the linking
568 my $page=shift; # the page that will contain the link (different for inline)
575 if (! $opts{forcesubpage}) {
576 $bestlink=bestlink($lpage, $link);
579 $bestlink="$lpage/".lc($link);
583 if (defined $opts{linktext}) {
584 $linktext=$opts{linktext};
587 $linktext=pagetitle(basename($link));
590 return "<span class=\"selflink\">$linktext</span>"
591 if length $bestlink && $page eq $bestlink &&
592 ! defined $opts{anchor};
594 if (! $destsources{$bestlink}) {
595 $bestlink=htmlpage($bestlink);
597 if (! $destsources{$bestlink}) {
598 return $linktext unless length $config{cgiurl};
599 return "<span class=\"createlink\"><a href=\"".
602 page => pagetitle(lc($link), 1),
605 "\">?</a>$linktext</span>"
609 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
610 $bestlink=beautify_url($bestlink);
612 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
613 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
616 if (defined $opts{anchor}) {
617 $bestlink.="#".$opts{anchor};
621 if (defined $opts{rel}) {
622 push @attrs, ' rel="'.$opts{rel}.'"';
624 if (defined $opts{class}) {
625 push @attrs, ' class="'.$opts{class}.'"';
628 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
631 sub htmlize ($$$) { #{{{
636 my $oneline = $content !~ /\n/;
638 if (exists $hooks{htmlize}{$type}) {
639 $content=$hooks{htmlize}{$type}{call}->(
645 error("htmlization of $type not supported");
648 run_hooks(sanitize => sub {
656 # hack to get rid of enclosing junk added by markdown
657 # and other htmlizers
659 $content=~s/<\/p>$//i;
666 sub linkify ($$$) { #{{{
667 my $lpage=shift; # the page containing the links
668 my $page=shift; # the page the link will end up on (different for inline)
671 $content =~ s{(\\?)$config{wiki_link_regexp}}{
674 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
675 : htmllink($lpage, $page, linkpage($3),
676 anchor => $4, linktext => pagetitle($2)))
678 ? "[[$3".($4 ? "#$4" : "")."]]"
679 : htmllink($lpage, $page, linkpage($3),
687 our $preprocess_preview=0;
688 sub preprocess ($$$;$$) { #{{{
689 my $page=shift; # the page the data comes from
690 my $destpage=shift; # the page the data will appear in (different for inline)
695 # Using local because it needs to be set within any nested calls
697 local $preprocess_preview=$preview if defined $preview;
704 if (length $escape) {
705 return "[[$prefix$command $params]]";
707 elsif (exists $hooks{preprocess}{$command}) {
708 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
709 # Note: preserve order of params, some plugins may
710 # consider it significant.
713 (?:([-\w]+)=)? # 1: named parameter key?
715 """(.*?)""" # 2: triple-quoted value
717 "([^"]+)" # 3: single-quoted value
719 (\S+) # 4: unquoted value
721 (?:\s+|$) # delimiter to next param
739 push @params, $key, $val;
742 push @params, $val, '';
745 if ($preprocessing{$page}++ > 3) {
746 # Avoid loops of preprocessed pages preprocessing
747 # other pages that preprocess them, etc.
748 #translators: The first parameter is a
749 #translators: preprocessor directive name,
750 #translators: the second a page name, the
751 #translators: third a number.
752 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
753 $command, $page, $preprocessing{$page}).
758 $ret=$hooks{preprocess}{$command}{call}->(
761 destpage => $destpage,
762 preview => $preprocess_preview,
766 # use void context during scan pass
767 $hooks{preprocess}{$command}{call}->(
770 destpage => $destpage,
771 preview => $preprocess_preview,
775 $preprocessing{$page}--;
779 return "[[$prefix$command $params]]";
784 if ($config{prefix_directives}) {
787 \[\[(!) # directive open; 2: prefix
788 ([-\w]+) # 3: command
789 ( # 4: the parameters..
790 \s+ # Must have space if parameters present
792 (?:[-\w]+=)? # named parameter key?
794 """.*?""" # triple-quoted value
796 "[^"]+" # single-quoted value
798 [^\s\]]+ # unquoted value
800 \s* # whitespace or end
803 *)? # 0 or more parameters
804 \]\] # directive closed
809 \[\[(!?) # directive open; 2: optional prefix
810 ([-\w]+) # 3: command
812 ( # 4: the parameters..
814 (?:[-\w]+=)? # named parameter key?
816 """.*?""" # triple-quoted value
818 "[^"]+" # single-quoted value
820 [^\s\]]+ # unquoted value
822 \s* # whitespace or end
825 *) # 0 or more parameters
826 \]\] # directive closed
830 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
834 sub filter ($$$) { #{{{
839 run_hooks(filter => sub {
840 $content=shift->(page => $page, destpage => $destpage,
841 content => $content);
847 sub indexlink () { #{{{
848 return "<a href=\"$config{url}\">$config{wikiname}</a>";
853 sub lockwiki (;$) { #{{{
854 my $wait=@_ ? shift : 1;
855 # Take an exclusive lock on the wiki to prevent multiple concurrent
856 # run issues. The lock will be dropped on program exit.
857 if (! -d $config{wikistatedir}) {
858 mkdir($config{wikistatedir});
860 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
861 error ("cannot write to $config{wikistatedir}/lockfile: $!");
862 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
864 debug("wiki seems to be locked, waiting for lock");
865 my $wait=600; # arbitrary, but don't hang forever to
866 # prevent process pileup
868 return if flock($wikilock, 2 | 4);
871 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
880 sub unlockwiki () { #{{{
881 return close($wikilock) if $wikilock;
887 sub commit_hook_enabled () { #{{{
888 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
889 error("cannot write to $config{wikistatedir}/commitlock: $!");
890 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
891 close($commitlock) || error("failed closing commitlock: $!");
894 close($commitlock) || error("failed closing commitlock: $!");
898 sub disable_commit_hook () { #{{{
899 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
900 error("cannot write to $config{wikistatedir}/commitlock: $!");
901 if (! flock($commitlock, 2)) { # LOCK_EX
902 error("failed to get commit lock");
907 sub enable_commit_hook () { #{{{
908 return close($commitlock) if $commitlock;
912 sub loadindex () { #{{{
913 %oldrenderedfiles=%pagectime=();
914 if (! $config{rebuild}) {
915 %pagesources=%pagemtime=%oldlinks=%links=%depends=
916 %destsources=%renderedfiles=%pagecase=();
918 open (my $in, "<", "$config{wikistatedir}/index") || return;
920 $_=possibly_foolish_untaint($_);
925 foreach my $i (split(/ /, $_)) {
926 my ($item, $val)=split(/=/, $i, 2);
927 push @{$items{$item}}, decode_entities($val);
930 next unless exists $items{src}; # skip bad lines for now
932 my $page=pagename($items{src}[0]);
933 if (! $config{rebuild}) {
934 $pagesources{$page}=$items{src}[0];
935 $pagemtime{$page}=$items{mtime}[0];
936 $oldlinks{$page}=[@{$items{link}}];
937 $links{$page}=[@{$items{link}}];
938 $depends{$page}=$items{depends}[0] if exists $items{depends};
939 $destsources{$_}=$page foreach @{$items{dest}};
940 $renderedfiles{$page}=[@{$items{dest}}];
941 $pagecase{lc $page}=$page;
942 foreach my $k (grep /_/, keys %items) {
943 my ($id, $key)=split(/_/, $k, 2);
944 $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
947 $oldrenderedfiles{$page}=[@{$items{dest}}];
948 $pagectime{$page}=$items{ctime}[0];
953 sub saveindex () { #{{{
954 run_hooks(savestate => sub { shift->() });
957 foreach my $type (keys %hooks) {
958 $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
960 my @hookids=sort keys %hookids;
962 if (! -d $config{wikistatedir}) {
963 mkdir($config{wikistatedir});
965 my $newfile="$config{wikistatedir}/index.new";
966 my $cleanup = sub { unlink($newfile) };
967 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
968 foreach my $page (keys %pagemtime) {
969 next unless $pagemtime{$page};
970 my $line="mtime=$pagemtime{$page} ".
971 "ctime=$pagectime{$page} ".
972 "src=$pagesources{$page}";
973 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
975 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
976 if (exists $depends{$page}) {
977 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
979 if (exists $pagestate{$page}) {
980 foreach my $id (@hookids) {
981 foreach my $key (keys %{$pagestate{$page}{$id}}) {
982 $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key});
986 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
988 close $out || error("failed saving to $newfile: $!", $cleanup);
989 rename($newfile, "$config{wikistatedir}/index") ||
990 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
995 sub template_file ($) { #{{{
998 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
999 return "$dir/$template" if -e "$dir/$template";
1004 sub template_params (@) { #{{{
1005 my $filename=template_file(shift);
1007 if (! defined $filename) {
1008 return if wantarray;
1014 my $text_ref = shift;
1015 ${$text_ref} = decode_utf8(${$text_ref});
1017 filename => $filename,
1018 loop_context_vars => 1,
1019 die_on_bad_params => 0,
1022 return wantarray ? @ret : {@ret};
1025 sub template ($;@) { #{{{
1026 require HTML::Template;
1027 return HTML::Template->new(template_params(@_));
1030 sub misctemplate ($$;@) { #{{{
1034 my $template=template("misc.tmpl");
1037 indexlink => indexlink(),
1038 wikiname => $config{wikiname},
1039 pagebody => $pagebody,
1040 baseurl => baseurl(),
1043 run_hooks(pagetemplate => sub {
1044 shift->(page => "", destpage => "", template => $template);
1046 return $template->output;
1049 sub hook (@) { # {{{
1052 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1053 error 'hook requires type, call, and id parameters';
1056 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1058 $hooks{$param{type}}{$param{id}}=\%param;
1062 sub run_hooks ($$) { # {{{
1063 # Calls the given sub for each hook of the given type,
1064 # passing it the hook function to call.
1068 if (exists $hooks{$type}) {
1070 foreach my $id (keys %{$hooks{$type}}) {
1071 if ($hooks{$type}{$id}{last}) {
1072 push @deferred, $id;
1075 $sub->($hooks{$type}{$id}{call});
1077 foreach my $id (@deferred) {
1078 $sub->($hooks{$type}{$id}{call});
1085 sub globlist_to_pagespec ($) { #{{{
1086 my @globlist=split(' ', shift);
1089 foreach my $glob (@globlist) {
1090 if ($glob=~/^!(.*)/) {
1098 my $spec=join(' or ', @spec);
1100 my $skip=join(' and ', @skip);
1102 $spec="$skip and ($spec)";
1111 sub is_globlist ($) { #{{{
1113 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1116 sub safequote ($) { #{{{
1122 sub add_depends ($$) { #{{{
1126 if (! exists $depends{$page}) {
1127 $depends{$page}=$pagespec;
1130 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1136 sub file_pruned ($$) { #{{{
1138 my $file=File::Spec->canonpath(shift);
1139 my $base=File::Spec->canonpath(shift);
1140 $file =~ s#^\Q$base\E/+##;
1142 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1143 return $file =~ m/$regexp/ && $file ne $base;
1147 # Only use gettext in the rare cases it's needed.
1148 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1149 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1150 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1151 if (! $gettext_obj) {
1152 $gettext_obj=eval q{
1153 use Locale::gettext q{textdomain};
1154 Locale::gettext->domain('ikiwiki')
1162 return $gettext_obj->get(shift);
1169 sub pagespec_merge ($$) { #{{{
1173 return $a if $a eq $b;
1175 # Support for old-style GlobLists.
1176 if (is_globlist($a)) {
1177 $a=globlist_to_pagespec($a);
1179 if (is_globlist($b)) {
1180 $b=globlist_to_pagespec($b);
1183 return "($a) or ($b)";
1186 sub pagespec_translate ($) { #{{{
1187 # This assumes that $page is in scope in the function
1188 # that evalulates the translated pagespec code.
1191 # Support for old-style GlobLists.
1192 if (is_globlist($spec)) {
1193 $spec=globlist_to_pagespec($spec);
1196 # Convert spec to perl code.
1199 \s* # ignore whitespace
1200 ( # 1: match a single word
1207 \w+\([^\)]*\) # command(params)
1209 [^\s()]+ # any other text
1211 \s* # ignore whitespace
1214 if (lc $word eq 'and') {
1217 elsif (lc $word eq 'or') {
1220 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1223 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1224 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1225 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1232 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1239 sub pagespec_match ($$;@) { #{{{
1244 # Backwards compatability with old calling convention.
1246 unshift @params, 'location';
1249 my $ret=eval pagespec_translate($spec);
1250 return IkiWiki::FailReason->new('syntax error') if $@;
1254 package IkiWiki::FailReason;
1257 '""' => sub { ${$_[0]} },
1259 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1264 return bless \$_[1], $_[0];
1267 package IkiWiki::SuccessReason;
1270 '""' => sub { ${$_[0]} },
1272 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1277 return bless \$_[1], $_[0];
1280 package IkiWiki::PageSpec;
1282 sub match_glob ($$;@) { #{{{
1287 my $from=exists $params{location} ? $params{location} : '';
1290 if ($glob =~ m!^\./!) {
1291 $from=~s#/?[^/]+$##;
1293 $glob="$from/$glob" if length $from;
1296 # turn glob into safe regexp
1297 $glob=quotemeta($glob);
1301 if ($page=~/^$glob$/i) {
1302 return IkiWiki::SuccessReason->new("$glob matches $page");
1305 return IkiWiki::FailReason->new("$glob does not match $page");
1309 sub match_link ($$;@) { #{{{
1314 my $from=exists $params{location} ? $params{location} : '';
1317 if ($link =~ m!^\.! && defined $from) {
1318 $from=~s#/?[^/]+$##;
1320 $link="$from/$link" if length $from;
1323 my $links = $IkiWiki::links{$page};
1324 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1325 my $bestlink = IkiWiki::bestlink($from, $link);
1326 foreach my $p (@{$links}) {
1327 if (length $bestlink) {
1328 return IkiWiki::SuccessReason->new("$page links to $link")
1329 if $bestlink eq IkiWiki::bestlink($page, $p);
1332 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1333 if match_glob($p, $link, %params);
1336 return IkiWiki::FailReason->new("$page does not link to $link");
1339 sub match_backlink ($$;@) { #{{{
1340 return match_link($_[1], $_[0], @_);
1343 sub match_created_before ($$;@) { #{{{
1347 if (exists $IkiWiki::pagectime{$testpage}) {
1348 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1349 return IkiWiki::SuccessReason->new("$page created before $testpage");
1352 return IkiWiki::FailReason->new("$page not created before $testpage");
1356 return IkiWiki::FailReason->new("$testpage has no ctime");
1360 sub match_created_after ($$;@) { #{{{
1364 if (exists $IkiWiki::pagectime{$testpage}) {
1365 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1366 return IkiWiki::SuccessReason->new("$page created after $testpage");
1369 return IkiWiki::FailReason->new("$page not created after $testpage");
1373 return IkiWiki::FailReason->new("$testpage has no ctime");
1377 sub match_creation_day ($$;@) { #{{{
1378 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1379 return IkiWiki::SuccessReason->new('creation_day matched');
1382 return IkiWiki::FailReason->new('creation_day did not match');
1386 sub match_creation_month ($$;@) { #{{{
1387 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1388 return IkiWiki::SuccessReason->new('creation_month matched');
1391 return IkiWiki::FailReason->new('creation_month did not match');
1395 sub match_creation_year ($$;@) { #{{{
1396 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1397 return IkiWiki::SuccessReason->new('creation_year matched');
1400 return IkiWiki::FailReason->new('creation_year did not match');
1404 sub match_user ($$;@) { #{{{
1409 return IkiWiki::FailReason->new('cannot match user')
1410 unless exists $params{user};
1411 if ($user eq $params{user}) {
1412 return IkiWiki::SuccessReason->new("user is $user")
1415 return IkiWiki::FailReason->new("user is not $user");