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 ($;$) { #{{{
193 print "Content-type: text/html\n\n";
194 print misctemplate(gettext("Error"),
195 "<p>".gettext("Error").": $message</p>");
197 log_message('err' => $message) if $config{syslog};
198 if (defined $cleaner) {
205 return unless $config{verbose};
206 return log_message(debug => @_);
210 sub log_message ($$) { #{{{
213 if ($config{syslog}) {
216 Sys::Syslog::setlogsock('unix');
217 Sys::Syslog::openlog('ikiwiki', '', 'user');
221 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
224 elsif (! $config{cgi}) {
228 return print STDERR "@_\n";
232 sub possibly_foolish_untaint ($) { #{{{
234 my ($untainted)=$tainted=~/(.*)/s;
238 sub basename ($) { #{{{
245 sub dirname ($) { #{{{
252 sub pagetype ($) { #{{{
255 if ($page =~ /\.([^.]+)$/) {
256 return $1 if exists $hooks{htmlize}{$1};
261 sub isinternal ($) { #{{{
263 return exists $pagesources{$page} &&
264 $pagesources{$page} =~ /\._([^.]+)$/;
267 sub pagename ($) { #{{{
270 my $type=pagetype($file);
272 $page=~s/\Q.$type\E*$// if defined $type;
276 sub targetpage ($$) { #{{{
280 if (! $config{usedirs} || $page =~ /^index$/ ) {
281 return $page.".".$ext;
283 return $page."/index.".$ext;
287 sub htmlpage ($) { #{{{
290 return targetpage($page, $config{htmlext});
293 sub srcfile_stat { #{{{
297 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
298 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
299 return "$dir/$file", stat(_) if -e "$dir/$file";
301 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
305 sub srcfile ($;$) { #{{{
306 return (srcfile_stat(@_))[0];
309 sub add_underlay ($) { #{{{
313 unshift @{$config{underlaydirs}}, $dir;
316 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
322 sub readfile ($;$$) { #{{{
328 error("cannot read a symlink ($file)");
332 open (my $in, "<", $file) || error("failed to read $file: $!");
333 binmode($in) if ($binary);
334 return \*$in if $wantfd;
336 close $in || error("failed to read $file: $!");
340 sub prep_writefile ($$) { #{{{
345 while (length $test) {
346 if (-l "$destdir/$test") {
347 error("cannot write to a symlink ($test)");
349 $test=dirname($test);
352 my $dir=dirname("$destdir/$file");
355 foreach my $s (split(m!/+!, $dir)) {
358 mkdir($d) || error("failed to create directory $d: $!");
366 sub writefile ($$$;$$) { #{{{
367 my $file=shift; # can include subdirs
368 my $destdir=shift; # directory to put file in
373 prep_writefile($file, $destdir);
375 my $newfile="$destdir/$file.ikiwiki-new";
377 error("cannot write to a symlink ($newfile)");
380 my $cleanup = sub { unlink($newfile) };
381 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
382 binmode($out) if ($binary);
384 $writer->(\*$out, $cleanup);
387 print $out $content or error("failed writing to $newfile: $!", $cleanup);
389 close $out || error("failed saving $newfile: $!", $cleanup);
390 rename($newfile, "$destdir/$file") ||
391 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
397 sub will_render ($$;$) { #{{{
402 # Important security check.
403 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
404 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
405 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
408 if (! $clear || $cleared{$page}) {
409 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
412 foreach my $old (@{$renderedfiles{$page}}) {
413 delete $destsources{$old};
415 $renderedfiles{$page}=[$dest];
418 $destsources{$dest}=$page;
423 sub bestlink ($$) { #{{{
428 if ($link=~s/^\/+//) {
436 $l.="/" if length $l;
439 if (exists $links{$l}) {
442 elsif (exists $pagecase{lc $l}) {
443 return $pagecase{lc $l};
445 } while $cwd=~s!/?[^/]+$!!;
447 if (length $config{userdir}) {
448 my $l = "$config{userdir}/".lc($link);
449 if (exists $links{$l}) {
452 elsif (exists $pagecase{lc $l}) {
453 return $pagecase{lc $l};
457 #print STDERR "warning: page $page, broken link: $link\n";
461 sub isinlinableimage ($) { #{{{
464 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
467 sub pagetitle ($;$) { #{{{
472 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
475 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
481 sub titlepage ($) { #{{{
483 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
487 sub linkpage ($) { #{{{
489 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
493 sub cgiurl (@) { #{{{
496 return $config{cgiurl}."?".
497 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
500 sub baseurl (;$) { #{{{
503 return "$config{url}/" if ! defined $page;
505 $page=htmlpage($page);
507 $page=~s/[^\/]+\//..\//g;
511 sub abs2rel ($$) { #{{{
512 # Work around very innefficient behavior in File::Spec if abs2rel
513 # is passed two relative paths. It's much faster if paths are
514 # absolute! (Debian bug #376658; fixed in debian unstable now)
519 my $ret=File::Spec->abs2rel($path, $base);
520 $ret=~s/^// if defined $ret;
524 sub displaytime ($;$) { #{{{
527 if (! defined $format) {
528 $format=$config{timeformat};
531 # strftime doesn't know about encodings, so make sure
532 # its output is properly treated as utf8
533 return decode_utf8(POSIX::strftime($format, localtime($time)));
536 sub beautify_urlpath ($) { #{{{
539 if ($config{usedirs}) {
540 $url =~ s!/index.$config{htmlext}$!/!;
543 # Ensure url is not an empty link, and
544 # if it's relative, make that explicit to avoid colon confusion.
552 sub urlto ($$) { #{{{
557 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
560 if (! $destsources{$to}) {
564 my $link = abs2rel($to, dirname(htmlpage($from)));
566 return beautify_urlpath($link);
569 sub htmllink ($$$;@) { #{{{
570 my $lpage=shift; # the page doing the linking
571 my $page=shift; # the page that will contain the link (different for inline)
578 if (! $opts{forcesubpage}) {
579 $bestlink=bestlink($lpage, $link);
582 $bestlink="$lpage/".lc($link);
586 if (defined $opts{linktext}) {
587 $linktext=$opts{linktext};
590 $linktext=pagetitle(basename($link));
593 return "<span class=\"selflink\">$linktext</span>"
594 if length $bestlink && $page eq $bestlink &&
595 ! defined $opts{anchor};
597 if (! $destsources{$bestlink}) {
598 $bestlink=htmlpage($bestlink);
600 if (! $destsources{$bestlink}) {
601 return $linktext unless length $config{cgiurl};
602 return "<span class=\"createlink\"><a href=\"".
608 "\" rel=\"nofollow\">?</a>$linktext</span>"
612 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
613 $bestlink=beautify_urlpath($bestlink);
615 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
616 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
619 if (defined $opts{anchor}) {
620 $bestlink.="#".$opts{anchor};
624 if (defined $opts{rel}) {
625 push @attrs, ' rel="'.$opts{rel}.'"';
627 if (defined $opts{class}) {
628 push @attrs, ' class="'.$opts{class}.'"';
631 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
634 sub userlink ($) { #{{{
637 my $oiduser=eval { openiduser($user) };
638 if (defined $oiduser) {
639 return "<a href=\"$user\">$oiduser</a>";
642 eval q{use CGI 'escapeHTML'};
645 return htmllink("", "", escapeHTML(
646 length $config{userdir} ? $config{userdir}."/".$user : $user
647 ), noimageinline => 1);
651 sub htmlize ($$$$) { #{{{
657 my $oneline = $content !~ /\n/;
659 if (exists $hooks{htmlize}{$type}) {
660 $content=$hooks{htmlize}{$type}{call}->(
666 error("htmlization of $type not supported");
669 run_hooks(sanitize => sub {
672 destpage => $destpage,
678 # hack to get rid of enclosing junk added by markdown
679 # and other htmlizers
681 $content=~s/<\/p>$//i;
688 sub linkify ($$$) { #{{{
693 run_hooks(linkify => sub {
696 destpage => $destpage,
705 our $preprocess_preview=0;
706 sub preprocess ($$$;$$) { #{{{
707 my $page=shift; # the page the data comes from
708 my $destpage=shift; # the page the data will appear in (different for inline)
713 # Using local because it needs to be set within any nested calls
715 local $preprocess_preview=$preview if defined $preview;
722 if (length $escape) {
723 return "[[$prefix$command $params]]";
725 elsif (exists $hooks{preprocess}{$command}) {
726 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
727 # Note: preserve order of params, some plugins may
728 # consider it significant.
731 (?:([-\w]+)=)? # 1: named parameter key?
733 """(.*?)""" # 2: triple-quoted value
735 "([^"]+)" # 3: single-quoted value
737 (\S+) # 4: unquoted value
739 (?:\s+|$) # delimiter to next param
757 push @params, $key, $val;
760 push @params, $val, '';
763 if ($preprocessing{$page}++ > 3) {
764 # Avoid loops of preprocessed pages preprocessing
765 # other pages that preprocess them, etc.
766 #translators: The first parameter is a
767 #translators: preprocessor directive name,
768 #translators: the second a page name, the
769 #translators: third a number.
770 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
771 $command, $page, $preprocessing{$page}).
776 $ret=$hooks{preprocess}{$command}{call}->(
779 destpage => $destpage,
780 preview => $preprocess_preview,
784 # use void context during scan pass
785 $hooks{preprocess}{$command}{call}->(
788 destpage => $destpage,
789 preview => $preprocess_preview,
793 $preprocessing{$page}--;
797 return "[[$prefix$command $params]]";
802 if ($config{prefix_directives}) {
805 \[\[(!) # directive open; 2: prefix
806 ([-\w]+) # 3: command
807 ( # 4: the parameters..
808 \s+ # Must have space if parameters present
810 (?:[-\w]+=)? # named parameter key?
812 """.*?""" # triple-quoted value
814 "[^"]+" # single-quoted value
816 [^\s\]]+ # unquoted value
818 \s* # whitespace or end
821 *)? # 0 or more parameters
822 \]\] # directive closed
827 \[\[(!?) # directive open; 2: optional prefix
828 ([-\w]+) # 3: command
830 ( # 4: the parameters..
832 (?:[-\w]+=)? # named parameter key?
834 """.*?""" # triple-quoted value
836 "[^"]+" # single-quoted value
838 [^\s\]]+ # unquoted value
840 \s* # whitespace or end
843 *) # 0 or more parameters
844 \]\] # directive closed
848 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
852 sub filter ($$$) { #{{{
857 run_hooks(filter => sub {
858 $content=shift->(page => $page, destpage => $destpage,
859 content => $content);
865 sub indexlink () { #{{{
866 return "<a href=\"$config{url}\">$config{wikiname}</a>";
871 sub lockwiki (;$) { #{{{
872 my $wait=@_ ? shift : 1;
873 # Take an exclusive lock on the wiki to prevent multiple concurrent
874 # run issues. The lock will be dropped on program exit.
875 if (! -d $config{wikistatedir}) {
876 mkdir($config{wikistatedir});
878 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
879 error ("cannot write to $config{wikistatedir}/lockfile: $!");
880 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
882 debug("wiki seems to be locked, waiting for lock");
883 my $wait=600; # arbitrary, but don't hang forever to
884 # prevent process pileup
886 return if flock($wikilock, 2 | 4);
889 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
898 sub unlockwiki () { #{{{
899 return close($wikilock) if $wikilock;
905 sub commit_hook_enabled () { #{{{
906 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
907 error("cannot write to $config{wikistatedir}/commitlock: $!");
908 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
909 close($commitlock) || error("failed closing commitlock: $!");
912 close($commitlock) || error("failed closing commitlock: $!");
916 sub disable_commit_hook () { #{{{
917 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
918 error("cannot write to $config{wikistatedir}/commitlock: $!");
919 if (! flock($commitlock, 2)) { # LOCK_EX
920 error("failed to get commit lock");
925 sub enable_commit_hook () { #{{{
926 return close($commitlock) if $commitlock;
930 sub loadindex () { #{{{
931 %oldrenderedfiles=%pagectime=();
932 if (! $config{rebuild}) {
933 %pagesources=%pagemtime=%oldlinks=%links=%depends=
934 %destsources=%renderedfiles=%pagecase=%pagestate=();
937 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
938 if (-e "$config{wikistatedir}/index") {
939 system("ikiwiki-transition", "indexdb", $config{srcdir});
940 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
946 my $ret=Storable::fd_retrieve($in);
947 if (! defined $ret) {
951 foreach my $src (keys %index) {
952 my %d=%{$index{$src}};
953 my $page=pagename($src);
954 $pagectime{$page}=$d{ctime};
955 if (! $config{rebuild}) {
956 $pagesources{$page}=$src;
957 $pagemtime{$page}=$d{mtime};
958 $renderedfiles{$page}=$d{dest};
959 if (exists $d{links} && ref $d{links}) {
960 $links{$page}=$d{links};
961 $oldlinks{$page}=[@{$d{links}}];
963 if (exists $d{depends}) {
964 $depends{$page}=$d{depends};
966 if (exists $d{state}) {
967 $pagestate{$page}=$d{state};
970 $oldrenderedfiles{$page}=[@{$d{dest}}];
972 foreach my $page (keys %pagesources) {
973 $pagecase{lc $page}=$page;
975 foreach my $page (keys %renderedfiles) {
976 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
981 sub saveindex () { #{{{
982 run_hooks(savestate => sub { shift->() });
985 foreach my $type (keys %hooks) {
986 $hookids{$_}=1 foreach keys %{$hooks{$type}};
988 my @hookids=keys %hookids;
990 if (! -d $config{wikistatedir}) {
991 mkdir($config{wikistatedir});
993 my $newfile="$config{wikistatedir}/indexdb.new";
994 my $cleanup = sub { unlink($newfile) };
995 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
997 foreach my $page (keys %pagemtime) {
998 next unless $pagemtime{$page};
999 my $src=$pagesources{$page};
1002 ctime => $pagectime{$page},
1003 mtime => $pagemtime{$page},
1004 dest => $renderedfiles{$page},
1005 links => $links{$page},
1008 if (exists $depends{$page}) {
1009 $index{$src}{depends} = $depends{$page};
1012 if (exists $pagestate{$page}) {
1013 foreach my $id (@hookids) {
1014 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1015 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1020 my $ret=Storable::nstore_fd(\%index, $out);
1021 return if ! defined $ret || ! $ret;
1022 close $out || error("failed saving to $newfile: $!", $cleanup);
1023 rename($newfile, "$config{wikistatedir}/indexdb") ||
1024 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1029 sub template_file ($) { #{{{
1032 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1033 return "$dir/$template" if -e "$dir/$template";
1038 sub template_params (@) { #{{{
1039 my $filename=template_file(shift);
1041 if (! defined $filename) {
1042 return if wantarray;
1048 my $text_ref = shift;
1049 ${$text_ref} = decode_utf8(${$text_ref});
1051 filename => $filename,
1052 loop_context_vars => 1,
1053 die_on_bad_params => 0,
1056 return wantarray ? @ret : {@ret};
1059 sub template ($;@) { #{{{
1060 require HTML::Template;
1061 return HTML::Template->new(template_params(@_));
1064 sub misctemplate ($$;@) { #{{{
1068 my $template=template("misc.tmpl");
1071 indexlink => indexlink(),
1072 wikiname => $config{wikiname},
1073 pagebody => $pagebody,
1074 baseurl => baseurl(),
1077 run_hooks(pagetemplate => sub {
1078 shift->(page => "", destpage => "", template => $template);
1080 return $template->output;
1083 sub hook (@) { # {{{
1086 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1087 error 'hook requires type, call, and id parameters';
1090 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1092 $hooks{$param{type}}{$param{id}}=\%param;
1096 sub run_hooks ($$) { # {{{
1097 # Calls the given sub for each hook of the given type,
1098 # passing it the hook function to call.
1102 if (exists $hooks{$type}) {
1104 foreach my $id (keys %{$hooks{$type}}) {
1105 if ($hooks{$type}{$id}{last}) {
1106 push @deferred, $id;
1109 $sub->($hooks{$type}{$id}{call});
1111 foreach my $id (@deferred) {
1112 $sub->($hooks{$type}{$id}{call});
1119 sub globlist_to_pagespec ($) { #{{{
1120 my @globlist=split(' ', shift);
1123 foreach my $glob (@globlist) {
1124 if ($glob=~/^!(.*)/) {
1132 my $spec=join(' or ', @spec);
1134 my $skip=join(' and ', @skip);
1136 $spec="$skip and ($spec)";
1145 sub is_globlist ($) { #{{{
1147 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1150 sub safequote ($) { #{{{
1156 sub add_depends ($$) { #{{{
1160 return unless pagespec_valid($pagespec);
1162 if (! exists $depends{$page}) {
1163 $depends{$page}=$pagespec;
1166 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1172 sub file_pruned ($$) { #{{{
1174 my $file=File::Spec->canonpath(shift);
1175 my $base=File::Spec->canonpath(shift);
1176 $file =~ s#^\Q$base\E/+##;
1178 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1179 return $file =~ m/$regexp/ && $file ne $base;
1183 # Only use gettext in the rare cases it's needed.
1184 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1185 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1186 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1187 if (! $gettext_obj) {
1188 $gettext_obj=eval q{
1189 use Locale::gettext q{textdomain};
1190 Locale::gettext->domain('ikiwiki')
1198 return $gettext_obj->get(shift);
1205 sub yesno ($) { #{{{
1208 return (defined $val && lc($val) eq gettext("yes"));
1211 sub pagespec_merge ($$) { #{{{
1215 return $a if $a eq $b;
1217 # Support for old-style GlobLists.
1218 if (is_globlist($a)) {
1219 $a=globlist_to_pagespec($a);
1221 if (is_globlist($b)) {
1222 $b=globlist_to_pagespec($b);
1225 return "($a) or ($b)";
1228 sub pagespec_translate ($) { #{{{
1231 # Support for old-style GlobLists.
1232 if (is_globlist($spec)) {
1233 $spec=globlist_to_pagespec($spec);
1236 # Convert spec to perl code.
1239 \s* # ignore whitespace
1240 ( # 1: match a single word
1247 \w+\([^\)]*\) # command(params)
1249 [^\s()]+ # any other text
1251 \s* # ignore whitespace
1254 if (lc $word eq 'and') {
1257 elsif (lc $word eq 'or') {
1260 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1263 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1264 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1265 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1272 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1276 if (! length $code) {
1281 return eval 'sub { my $page=shift; '.$code.' }';
1284 sub pagespec_match ($$;@) { #{{{
1289 # Backwards compatability with old calling convention.
1291 unshift @params, 'location';
1294 my $sub=pagespec_translate($spec);
1295 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1296 return $sub->($page, @params);
1299 sub pagespec_valid ($) { #{{{
1302 my $sub=pagespec_translate($spec);
1306 sub glob2re ($) { #{{{
1307 my $re=quotemeta(shift);
1313 package IkiWiki::FailReason;
1316 '""' => sub { ${$_[0]} },
1318 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1325 return bless \$value, $class;
1328 package IkiWiki::SuccessReason;
1331 '""' => sub { ${$_[0]} },
1333 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1340 return bless \$value, $class;
1343 package IkiWiki::PageSpec;
1345 sub match_glob ($$;@) { #{{{
1350 my $from=exists $params{location} ? $params{location} : '';
1353 if ($glob =~ m!^\./!) {
1354 $from=~s#/?[^/]+$##;
1356 $glob="$from/$glob" if length $from;
1359 my $regexp=IkiWiki::glob2re($glob);
1360 if ($page=~/^$regexp$/i) {
1361 if (! IkiWiki::isinternal($page) || $params{internal}) {
1362 return IkiWiki::SuccessReason->new("$glob matches $page");
1365 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1369 return IkiWiki::FailReason->new("$glob does not match $page");
1373 sub match_internal ($$;@) { #{{{
1374 return match_glob($_[0], $_[1], @_, internal => 1)
1377 sub match_link ($$;@) { #{{{
1382 my $from=exists $params{location} ? $params{location} : '';
1385 if ($link =~ m!^\.! && defined $from) {
1386 $from=~s#/?[^/]+$##;
1388 $link="$from/$link" if length $from;
1391 my $links = $IkiWiki::links{$page};
1392 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1393 my $bestlink = IkiWiki::bestlink($from, $link);
1394 foreach my $p (@{$links}) {
1395 if (length $bestlink) {
1396 return IkiWiki::SuccessReason->new("$page links to $link")
1397 if $bestlink eq IkiWiki::bestlink($page, $p);
1400 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1401 if match_glob($p, $link, %params);
1404 return IkiWiki::FailReason->new("$page does not link to $link");
1407 sub match_backlink ($$;@) { #{{{
1408 return match_link($_[1], $_[0], @_);
1411 sub match_created_before ($$;@) { #{{{
1415 if (exists $IkiWiki::pagectime{$testpage}) {
1416 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1417 return IkiWiki::SuccessReason->new("$page created before $testpage");
1420 return IkiWiki::FailReason->new("$page not created before $testpage");
1424 return IkiWiki::FailReason->new("$testpage has no ctime");
1428 sub match_created_after ($$;@) { #{{{
1432 if (exists $IkiWiki::pagectime{$testpage}) {
1433 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1434 return IkiWiki::SuccessReason->new("$page created after $testpage");
1437 return IkiWiki::FailReason->new("$page not created after $testpage");
1441 return IkiWiki::FailReason->new("$testpage has no ctime");
1445 sub match_creation_day ($$;@) { #{{{
1446 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1447 return IkiWiki::SuccessReason->new('creation_day matched');
1450 return IkiWiki::FailReason->new('creation_day did not match');
1454 sub match_creation_month ($$;@) { #{{{
1455 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1456 return IkiWiki::SuccessReason->new('creation_month matched');
1459 return IkiWiki::FailReason->new('creation_month did not match');
1463 sub match_creation_year ($$;@) { #{{{
1464 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1465 return IkiWiki::SuccessReason->new('creation_year matched');
1468 return IkiWiki::FailReason->new('creation_year did not match');