9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %renderedfiles %oldrenderedfiles %pagesources
16 %destsources %depends %hooks %forcerebuild $gettext_obj};
18 use Exporter q{import};
19 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
20 bestlink htmllink readfile writefile pagetype srcfile pagename
21 displaytime will_render gettext urlto targetpage
23 %config %links %pagestate %renderedfiles
24 %pagesources %destsources);
25 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
26 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
27 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 memoize("pagespec_translate");
33 memoize("file_pruned");
35 sub defaultconfig () { #{{{
37 wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
38 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
39 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
42 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
43 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
47 default_pageext => "mdwn",
68 gitorigin_branch => "origin",
69 gitmaster_branch => "master",
73 templatedir => "$installdir/share/ikiwiki/templates",
74 underlaydir => "$installdir/share/ikiwiki/basewiki",
79 plugin => [qw{mdwn link inline htmlscrubber passwordauth openid
80 signinedit lockedit conditional recentchanges
90 account_creation_password => "",
91 prefix_directives => 0,
93 cgi_disable_uploads => 1,
96 sub checkconfig () { #{{{
97 # locale stuff; avoid LC_ALL since it overrides everything
98 if (defined $ENV{LC_ALL}) {
99 $ENV{LANG} = $ENV{LC_ALL};
102 if (defined $config{locale}) {
103 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
104 $ENV{LANG}=$config{locale};
109 if (ref $config{ENV} eq 'HASH') {
110 foreach my $val (keys %{$config{ENV}}) {
111 $ENV{$val}=$config{ENV}{$val};
115 if ($config{w3mmode}) {
116 eval q{use Cwd q{abs_path}};
118 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
119 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
120 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
121 unless $config{cgiurl} =~ m!file:///!;
122 $config{url}="file://".$config{destdir};
125 if ($config{cgi} && ! length $config{url}) {
126 error(gettext("Must specify url to wiki with --url when using --cgi"));
129 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
130 unless exists $config{wikistatedir};
133 eval qq{use IkiWiki::Rcs::$config{rcs}};
135 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
139 require IkiWiki::Rcs::Stub;
142 if (exists $config{umask}) {
143 umask(possibly_foolish_untaint($config{umask}));
146 run_hooks(checkconfig => sub { shift->() });
151 sub loadplugins () { #{{{
152 if (defined $config{libdir}) {
153 unshift @INC, possibly_foolish_untaint($config{libdir});
156 loadplugin($_) foreach @{$config{plugin}};
158 run_hooks(getopt => sub { shift->() });
159 if (grep /^-/, @ARGV) {
160 print STDERR "Unknown option: $_\n"
161 foreach grep /^-/, @ARGV;
168 sub loadplugin ($) { #{{{
171 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
173 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
174 "$installdir/lib/ikiwiki") {
175 if (defined $dir && -x "$dir/plugins/$plugin") {
176 require IkiWiki::Plugin::external;
177 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
182 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
185 error("Failed to load plugin $mod: $@");
190 sub error ($;$) { #{{{
193 log_message('err' => $message) if $config{syslog};
194 if (defined $cleaner) {
201 return unless $config{verbose};
202 return log_message(debug => @_);
206 sub log_message ($$) { #{{{
209 if ($config{syslog}) {
212 Sys::Syslog::setlogsock('unix');
213 Sys::Syslog::openlog('ikiwiki', '', 'user');
217 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
220 elsif (! $config{cgi}) {
224 return print STDERR "@_\n";
228 sub possibly_foolish_untaint ($) { #{{{
230 my ($untainted)=$tainted=~/(.*)/s;
234 sub basename ($) { #{{{
241 sub dirname ($) { #{{{
248 sub pagetype ($) { #{{{
251 if ($page =~ /\.([^.]+)$/) {
252 return $1 if exists $hooks{htmlize}{$1};
257 sub isinternal ($) { #{{{
259 return exists $pagesources{$page} &&
260 $pagesources{$page} =~ /\._([^.]+)$/;
263 sub pagename ($) { #{{{
266 my $type=pagetype($file);
268 $page=~s/\Q.$type\E*$// if defined $type;
272 sub targetpage ($$) { #{{{
276 if (! $config{usedirs} || $page =~ /^index$/ ) {
277 return $page.".".$ext;
279 return $page."/index.".$ext;
283 sub htmlpage ($) { #{{{
286 return targetpage($page, $config{htmlext});
289 sub srcfile_stat { #{{{
293 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
294 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
295 return "$dir/$file", stat(_) if -e "$dir/$file";
297 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
301 sub srcfile ($;$) { #{{{
302 return (srcfile_stat(@_))[0];
305 sub add_underlay ($) { #{{{
309 unshift @{$config{underlaydirs}}, $dir;
312 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
318 sub readfile ($;$$) { #{{{
324 error("cannot read a symlink ($file)");
328 open (my $in, "<", $file) || error("failed to read $file: $!");
329 binmode($in) if ($binary);
330 return \*$in if $wantfd;
332 close $in || error("failed to read $file: $!");
336 sub prep_writefile ($$) { #{{{
341 while (length $test) {
342 if (-l "$destdir/$test") {
343 error("cannot write to a symlink ($test)");
345 $test=dirname($test);
348 my $dir=dirname("$destdir/$file");
351 foreach my $s (split(m!/+!, $dir)) {
354 mkdir($d) || error("failed to create directory $d: $!");
362 sub writefile ($$$;$$) { #{{{
363 my $file=shift; # can include subdirs
364 my $destdir=shift; # directory to put file in
369 prep_writefile($file, $destdir);
371 my $newfile="$destdir/$file.ikiwiki-new";
373 error("cannot write to a symlink ($newfile)");
376 my $cleanup = sub { unlink($newfile) };
377 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
378 binmode($out) if ($binary);
380 $writer->(\*$out, $cleanup);
383 print $out $content or error("failed writing to $newfile: $!", $cleanup);
385 close $out || error("failed saving $newfile: $!", $cleanup);
386 rename($newfile, "$destdir/$file") ||
387 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
393 sub will_render ($$;$) { #{{{
398 # Important security check.
399 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
400 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
401 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
404 if (! $clear || $cleared{$page}) {
405 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
408 foreach my $old (@{$renderedfiles{$page}}) {
409 delete $destsources{$old};
411 $renderedfiles{$page}=[$dest];
414 $destsources{$dest}=$page;
419 sub bestlink ($$) { #{{{
424 if ($link=~s/^\/+//) {
432 $l.="/" if length $l;
435 if (exists $links{$l}) {
438 elsif (exists $pagecase{lc $l}) {
439 return $pagecase{lc $l};
441 } while $cwd=~s!/?[^/]+$!!;
443 if (length $config{userdir}) {
444 my $l = "$config{userdir}/".lc($link);
445 if (exists $links{$l}) {
448 elsif (exists $pagecase{lc $l}) {
449 return $pagecase{lc $l};
453 #print STDERR "warning: page $page, broken link: $link\n";
457 sub isinlinableimage ($) { #{{{
460 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
463 sub pagetitle ($;$) { #{{{
468 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
471 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
477 sub titlepage ($) { #{{{
479 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
483 sub linkpage ($) { #{{{
485 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
489 sub cgiurl (@) { #{{{
492 return $config{cgiurl}."?".
493 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
496 sub baseurl (;$) { #{{{
499 return "$config{url}/" if ! defined $page;
501 $page=htmlpage($page);
503 $page=~s/[^\/]+\//..\//g;
507 sub abs2rel ($$) { #{{{
508 # Work around very innefficient behavior in File::Spec if abs2rel
509 # is passed two relative paths. It's much faster if paths are
510 # absolute! (Debian bug #376658; fixed in debian unstable now)
515 my $ret=File::Spec->abs2rel($path, $base);
516 $ret=~s/^// if defined $ret;
520 sub displaytime ($;$) { #{{{
523 if (! defined $format) {
524 $format=$config{timeformat};
527 # strftime doesn't know about encodings, so make sure
528 # its output is properly treated as utf8
529 return decode_utf8(POSIX::strftime($format, localtime($time)));
532 sub beautify_urlpath ($) { #{{{
535 if ($config{usedirs}) {
536 $url =~ s!/index.$config{htmlext}$!/!;
539 # Ensure url is not an empty link, and
540 # if it's relative, make that explicit to avoid colon confusion.
548 sub urlto ($$;$) { #{{{
554 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
557 if (! $destsources{$to}) {
562 return $config{url}.beautify_urlpath("/".$to);
565 my $link = abs2rel($to, dirname(htmlpage($from)));
567 return beautify_urlpath($link);
570 sub htmllink ($$$;@) { #{{{
571 my $lpage=shift; # the page doing the linking
572 my $page=shift; # the page that will contain the link (different for inline)
579 if (! $opts{forcesubpage}) {
580 $bestlink=bestlink($lpage, $link);
583 $bestlink="$lpage/".lc($link);
587 if (defined $opts{linktext}) {
588 $linktext=$opts{linktext};
591 $linktext=pagetitle(basename($link));
594 return "<span class=\"selflink\">$linktext</span>"
595 if length $bestlink && $page eq $bestlink &&
596 ! defined $opts{anchor};
598 if (! $destsources{$bestlink}) {
599 $bestlink=htmlpage($bestlink);
601 if (! $destsources{$bestlink}) {
602 return $linktext unless length $config{cgiurl};
603 return "<span class=\"createlink\"><a href=\"".
609 "\" rel=\"nofollow\">?</a>$linktext</span>"
613 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
614 $bestlink=beautify_urlpath($bestlink);
616 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
617 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
620 if (defined $opts{anchor}) {
621 $bestlink.="#".$opts{anchor};
625 if (defined $opts{rel}) {
626 push @attrs, ' rel="'.$opts{rel}.'"';
628 if (defined $opts{class}) {
629 push @attrs, ' class="'.$opts{class}.'"';
632 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
635 sub userlink ($) { #{{{
638 my $oiduser=eval { openiduser($user) };
639 if (defined $oiduser) {
640 return "<a href=\"$user\">$oiduser</a>";
643 eval q{use CGI 'escapeHTML'};
646 return htmllink("", "", escapeHTML(
647 length $config{userdir} ? $config{userdir}."/".$user : $user
648 ), noimageinline => 1);
652 sub htmlize ($$$$) { #{{{
658 my $oneline = $content !~ /\n/;
660 if (exists $hooks{htmlize}{$type}) {
661 $content=$hooks{htmlize}{$type}{call}->(
667 error("htmlization of $type not supported");
670 run_hooks(sanitize => sub {
673 destpage => $destpage,
679 # hack to get rid of enclosing junk added by markdown
680 # and other htmlizers
682 $content=~s/<\/p>$//i;
689 sub linkify ($$$) { #{{{
694 run_hooks(linkify => sub {
697 destpage => $destpage,
706 our $preprocess_preview=0;
707 sub preprocess ($$$;$$) { #{{{
708 my $page=shift; # the page the data comes from
709 my $destpage=shift; # the page the data will appear in (different for inline)
714 # Using local because it needs to be set within any nested calls
716 local $preprocess_preview=$preview if defined $preview;
723 if (length $escape) {
724 return "[[$prefix$command $params]]";
726 elsif (exists $hooks{preprocess}{$command}) {
727 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
728 # Note: preserve order of params, some plugins may
729 # consider it significant.
732 (?:([-\w]+)=)? # 1: named parameter key?
734 """(.*?)""" # 2: triple-quoted value
736 "([^"]+)" # 3: single-quoted value
738 (\S+) # 4: unquoted value
740 (?:\s+|$) # delimiter to next param
758 push @params, $key, $val;
761 push @params, $val, '';
764 if ($preprocessing{$page}++ > 3) {
765 # Avoid loops of preprocessed pages preprocessing
766 # other pages that preprocess them, etc.
767 #translators: The first parameter is a
768 #translators: preprocessor directive name,
769 #translators: the second a page name, the
770 #translators: third a number.
771 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
772 $command, $page, $preprocessing{$page}).
778 $hooks{preprocess}{$command}{call}->(
781 destpage => $destpage,
782 preview => $preprocess_preview,
787 $ret="[[!$command <span class=\"error\">".
788 gettext("Error").": $@"."</span>]]";
792 # use void context during scan pass
794 $hooks{preprocess}{$command}{call}->(
797 destpage => $destpage,
798 preview => $preprocess_preview,
803 $preprocessing{$page}--;
807 return "[[$prefix$command $params]]";
812 if ($config{prefix_directives}) {
815 \[\[(!) # directive open; 2: prefix
816 ([-\w]+) # 3: command
817 ( # 4: the parameters..
818 \s+ # Must have space if parameters present
820 (?:[-\w]+=)? # named parameter key?
822 """.*?""" # triple-quoted value
824 "[^"]+" # single-quoted value
826 [^\s\]]+ # unquoted value
828 \s* # whitespace or end
831 *)? # 0 or more parameters
832 \]\] # directive closed
838 \[\[(!?) # directive open; 2: optional prefix
839 ([-\w]+) # 3: command
841 ( # 4: the parameters..
843 (?:[-\w]+=)? # named parameter key?
845 """.*?""" # triple-quoted value
847 "[^"]+" # single-quoted value
849 [^\s\]]+ # unquoted value
851 \s* # whitespace or end
854 *) # 0 or more parameters
855 \]\] # directive closed
859 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
863 sub filter ($$$) { #{{{
868 run_hooks(filter => sub {
869 $content=shift->(page => $page, destpage => $destpage,
870 content => $content);
876 sub indexlink () { #{{{
877 return "<a href=\"$config{url}\">$config{wikiname}</a>";
882 sub lockwiki (;$) { #{{{
883 my $wait=@_ ? shift : 1;
884 # Take an exclusive lock on the wiki to prevent multiple concurrent
885 # run issues. The lock will be dropped on program exit.
886 if (! -d $config{wikistatedir}) {
887 mkdir($config{wikistatedir});
889 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
890 error ("cannot write to $config{wikistatedir}/lockfile: $!");
891 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
893 debug("wiki seems to be locked, waiting for lock");
894 my $wait=600; # arbitrary, but don't hang forever to
895 # prevent process pileup
897 return if flock($wikilock, 2 | 4);
900 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
909 sub unlockwiki () { #{{{
910 return close($wikilock) if $wikilock;
916 sub commit_hook_enabled () { #{{{
917 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
918 error("cannot write to $config{wikistatedir}/commitlock: $!");
919 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
920 close($commitlock) || error("failed closing commitlock: $!");
923 close($commitlock) || error("failed closing commitlock: $!");
927 sub disable_commit_hook () { #{{{
928 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
929 error("cannot write to $config{wikistatedir}/commitlock: $!");
930 if (! flock($commitlock, 2)) { # LOCK_EX
931 error("failed to get commit lock");
936 sub enable_commit_hook () { #{{{
937 return close($commitlock) if $commitlock;
941 sub loadindex () { #{{{
942 %oldrenderedfiles=%pagectime=();
943 if (! $config{rebuild}) {
944 %pagesources=%pagemtime=%oldlinks=%links=%depends=
945 %destsources=%renderedfiles=%pagecase=%pagestate=();
948 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
949 if (-e "$config{wikistatedir}/index") {
950 system("ikiwiki-transition", "indexdb", $config{srcdir});
951 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
957 my $ret=Storable::fd_retrieve($in);
958 if (! defined $ret) {
962 foreach my $src (keys %index) {
963 my %d=%{$index{$src}};
964 my $page=pagename($src);
965 $pagectime{$page}=$d{ctime};
966 if (! $config{rebuild}) {
967 $pagesources{$page}=$src;
968 $pagemtime{$page}=$d{mtime};
969 $renderedfiles{$page}=$d{dest};
970 if (exists $d{links} && ref $d{links}) {
971 $links{$page}=$d{links};
972 $oldlinks{$page}=[@{$d{links}}];
974 if (exists $d{depends}) {
975 $depends{$page}=$d{depends};
977 if (exists $d{state}) {
978 $pagestate{$page}=$d{state};
981 $oldrenderedfiles{$page}=[@{$d{dest}}];
983 foreach my $page (keys %pagesources) {
984 $pagecase{lc $page}=$page;
986 foreach my $page (keys %renderedfiles) {
987 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
992 sub saveindex () { #{{{
993 run_hooks(savestate => sub { shift->() });
996 foreach my $type (keys %hooks) {
997 $hookids{$_}=1 foreach keys %{$hooks{$type}};
999 my @hookids=keys %hookids;
1001 if (! -d $config{wikistatedir}) {
1002 mkdir($config{wikistatedir});
1004 my $newfile="$config{wikistatedir}/indexdb.new";
1005 my $cleanup = sub { unlink($newfile) };
1006 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1008 foreach my $page (keys %pagemtime) {
1009 next unless $pagemtime{$page};
1010 my $src=$pagesources{$page};
1013 ctime => $pagectime{$page},
1014 mtime => $pagemtime{$page},
1015 dest => $renderedfiles{$page},
1016 links => $links{$page},
1019 if (exists $depends{$page}) {
1020 $index{$src}{depends} = $depends{$page};
1023 if (exists $pagestate{$page}) {
1024 foreach my $id (@hookids) {
1025 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1026 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1031 my $ret=Storable::nstore_fd(\%index, $out);
1032 return if ! defined $ret || ! $ret;
1033 close $out || error("failed saving to $newfile: $!", $cleanup);
1034 rename($newfile, "$config{wikistatedir}/indexdb") ||
1035 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1040 sub template_file ($) { #{{{
1043 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1044 return "$dir/$template" if -e "$dir/$template";
1049 sub template_params (@) { #{{{
1050 my $filename=template_file(shift);
1052 if (! defined $filename) {
1053 return if wantarray;
1059 my $text_ref = shift;
1060 ${$text_ref} = decode_utf8(${$text_ref});
1062 filename => $filename,
1063 loop_context_vars => 1,
1064 die_on_bad_params => 0,
1067 return wantarray ? @ret : {@ret};
1070 sub template ($;@) { #{{{
1071 require HTML::Template;
1072 return HTML::Template->new(template_params(@_));
1075 sub misctemplate ($$;@) { #{{{
1079 my $template=template("misc.tmpl");
1082 indexlink => indexlink(),
1083 wikiname => $config{wikiname},
1084 pagebody => $pagebody,
1085 baseurl => baseurl(),
1088 run_hooks(pagetemplate => sub {
1089 shift->(page => "", destpage => "", template => $template);
1091 return $template->output;
1094 sub hook (@) { # {{{
1097 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1098 error 'hook requires type, call, and id parameters';
1101 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1103 $hooks{$param{type}}{$param{id}}=\%param;
1107 sub run_hooks ($$) { # {{{
1108 # Calls the given sub for each hook of the given type,
1109 # passing it the hook function to call.
1113 if (exists $hooks{$type}) {
1115 foreach my $id (keys %{$hooks{$type}}) {
1116 if ($hooks{$type}{$id}{last}) {
1117 push @deferred, $id;
1120 $sub->($hooks{$type}{$id}{call});
1122 foreach my $id (@deferred) {
1123 $sub->($hooks{$type}{$id}{call});
1130 sub globlist_to_pagespec ($) { #{{{
1131 my @globlist=split(' ', shift);
1134 foreach my $glob (@globlist) {
1135 if ($glob=~/^!(.*)/) {
1143 my $spec=join(' or ', @spec);
1145 my $skip=join(' and ', @skip);
1147 $spec="$skip and ($spec)";
1156 sub is_globlist ($) { #{{{
1158 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1161 sub safequote ($) { #{{{
1167 sub add_depends ($$) { #{{{
1171 return unless pagespec_valid($pagespec);
1173 if (! exists $depends{$page}) {
1174 $depends{$page}=$pagespec;
1177 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1183 sub file_pruned ($$) { #{{{
1185 my $file=File::Spec->canonpath(shift);
1186 my $base=File::Spec->canonpath(shift);
1187 $file =~ s#^\Q$base\E/+##;
1189 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1190 return $file =~ m/$regexp/ && $file ne $base;
1194 # Only use gettext in the rare cases it's needed.
1195 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1196 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1197 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1198 if (! $gettext_obj) {
1199 $gettext_obj=eval q{
1200 use Locale::gettext q{textdomain};
1201 Locale::gettext->domain('ikiwiki')
1209 return $gettext_obj->get(shift);
1216 sub yesno ($) { #{{{
1219 return (defined $val && lc($val) eq gettext("yes"));
1222 sub pagespec_merge ($$) { #{{{
1226 return $a if $a eq $b;
1228 # Support for old-style GlobLists.
1229 if (is_globlist($a)) {
1230 $a=globlist_to_pagespec($a);
1232 if (is_globlist($b)) {
1233 $b=globlist_to_pagespec($b);
1236 return "($a) or ($b)";
1239 sub pagespec_translate ($) { #{{{
1242 # Support for old-style GlobLists.
1243 if (is_globlist($spec)) {
1244 $spec=globlist_to_pagespec($spec);
1247 # Convert spec to perl code.
1250 \s* # ignore whitespace
1251 ( # 1: match a single word
1258 \w+\([^\)]*\) # command(params)
1260 [^\s()]+ # any other text
1262 \s* # ignore whitespace
1265 if (lc $word eq 'and') {
1268 elsif (lc $word eq 'or') {
1271 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1274 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1275 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1276 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1283 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1287 if (! length $code) {
1292 return eval 'sub { my $page=shift; '.$code.' }';
1295 sub pagespec_match ($$;@) { #{{{
1300 # Backwards compatability with old calling convention.
1302 unshift @params, 'location';
1305 my $sub=pagespec_translate($spec);
1306 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1307 return $sub->($page, @params);
1310 sub pagespec_valid ($) { #{{{
1313 my $sub=pagespec_translate($spec);
1317 sub glob2re ($) { #{{{
1318 my $re=quotemeta(shift);
1324 package IkiWiki::FailReason;
1327 '""' => sub { ${$_[0]} },
1329 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1336 return bless \$value, $class;
1339 package IkiWiki::SuccessReason;
1342 '""' => sub { ${$_[0]} },
1344 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1351 return bless \$value, $class;
1354 package IkiWiki::PageSpec;
1356 sub match_glob ($$;@) { #{{{
1361 my $from=exists $params{location} ? $params{location} : '';
1364 if ($glob =~ m!^\./!) {
1365 $from=~s#/?[^/]+$##;
1367 $glob="$from/$glob" if length $from;
1370 my $regexp=IkiWiki::glob2re($glob);
1371 if ($page=~/^$regexp$/i) {
1372 if (! IkiWiki::isinternal($page) || $params{internal}) {
1373 return IkiWiki::SuccessReason->new("$glob matches $page");
1376 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1380 return IkiWiki::FailReason->new("$glob does not match $page");
1384 sub match_internal ($$;@) { #{{{
1385 return match_glob($_[0], $_[1], @_, internal => 1)
1388 sub match_link ($$;@) { #{{{
1393 my $from=exists $params{location} ? $params{location} : '';
1396 if ($link =~ m!^\.! && defined $from) {
1397 $from=~s#/?[^/]+$##;
1399 $link="$from/$link" if length $from;
1402 my $links = $IkiWiki::links{$page};
1403 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1404 my $bestlink = IkiWiki::bestlink($from, $link);
1405 foreach my $p (@{$links}) {
1406 if (length $bestlink) {
1407 return IkiWiki::SuccessReason->new("$page links to $link")
1408 if $bestlink eq IkiWiki::bestlink($page, $p);
1411 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1412 if match_glob($p, $link, %params);
1415 return IkiWiki::FailReason->new("$page does not link to $link");
1418 sub match_backlink ($$;@) { #{{{
1419 return match_link($_[1], $_[0], @_);
1422 sub match_created_before ($$;@) { #{{{
1426 if (exists $IkiWiki::pagectime{$testpage}) {
1427 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1428 return IkiWiki::SuccessReason->new("$page created before $testpage");
1431 return IkiWiki::FailReason->new("$page not created before $testpage");
1435 return IkiWiki::FailReason->new("$testpage has no ctime");
1439 sub match_created_after ($$;@) { #{{{
1443 if (exists $IkiWiki::pagectime{$testpage}) {
1444 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1445 return IkiWiki::SuccessReason->new("$page created after $testpage");
1448 return IkiWiki::FailReason->new("$page not created after $testpage");
1452 return IkiWiki::FailReason->new("$testpage has no ctime");
1456 sub match_creation_day ($$;@) { #{{{
1457 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1458 return IkiWiki::SuccessReason->new('creation_day matched');
1461 return IkiWiki::FailReason->new('creation_day did not match');
1465 sub match_creation_month ($$;@) { #{{{
1466 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1467 return IkiWiki::SuccessReason->new('creation_month matched');
1470 return IkiWiki::FailReason->new('creation_month did not match');
1474 sub match_creation_year ($$;@) { #{{{
1475 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1476 return IkiWiki::SuccessReason->new('creation_year matched');
1479 return IkiWiki::FailReason->new('creation_year did not match');