8 use URI::Escape q{uri_escape_utf8};
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14 %pagestate %renderedfiles %oldrenderedfiles %pagesources
15 %destsources %depends %hooks %forcerebuild $gettext_obj};
17 use Exporter q{import};
18 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
19 bestlink htmllink readfile writefile pagetype srcfile pagename
20 displaytime will_render gettext urlto targetpage
22 %config %links %pagestate %renderedfiles
23 %pagesources %destsources);
24 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
25 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
26 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
31 memoize("pagespec_translate");
32 memoize("file_pruned");
34 sub defaultconfig () { #{{{
36 wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
37 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
38 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
41 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
42 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
46 default_pageext => "mdwn",
67 gitorigin_branch => "origin",
68 gitmaster_branch => "master",
72 templatedir => "$installdir/share/ikiwiki/templates",
73 underlaydir => "$installdir/share/ikiwiki/basewiki",
78 plugin => [qw{mdwn link inline htmlscrubber passwordauth openid
79 signinedit lockedit conditional recentchanges}],
88 account_creation_password => "",
89 prefix_directives => 0,
91 cgi_disable_uploads => 1,
94 sub checkconfig () { #{{{
95 # locale stuff; avoid LC_ALL since it overrides everything
96 if (defined $ENV{LC_ALL}) {
97 $ENV{LANG} = $ENV{LC_ALL};
100 if (defined $config{locale}) {
101 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
102 $ENV{LANG}=$config{locale};
107 if (ref $config{ENV} eq 'HASH') {
108 foreach my $val (keys %{$config{ENV}}) {
109 $ENV{$val}=$config{ENV}{$val};
113 if ($config{w3mmode}) {
114 eval q{use Cwd q{abs_path}};
116 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
117 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
118 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
119 unless $config{cgiurl} =~ m!file:///!;
120 $config{url}="file://".$config{destdir};
123 if ($config{cgi} && ! length $config{url}) {
124 error(gettext("Must specify url to wiki with --url when using --cgi"));
127 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
128 unless exists $config{wikistatedir};
131 eval qq{use IkiWiki::Rcs::$config{rcs}};
133 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
137 require IkiWiki::Rcs::Stub;
140 if (exists $config{umask}) {
141 umask(possibly_foolish_untaint($config{umask}));
144 run_hooks(checkconfig => sub { shift->() });
149 sub loadplugins () { #{{{
150 if (defined $config{libdir}) {
151 unshift @INC, possibly_foolish_untaint($config{libdir});
154 foreach my $plugin (@{$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 ($;$) { #{{{
194 print "Content-type: text/html\n\n";
195 print misctemplate(gettext("Error"),
196 "<p>".gettext("Error").": $message</p>");
198 log_message('err' => $message) if $config{syslog};
199 if (defined $cleaner) {
206 return unless $config{verbose};
207 return log_message(debug => @_);
211 sub log_message ($$) { #{{{
214 if ($config{syslog}) {
217 Sys::Syslog::setlogsock('unix');
218 Sys::Syslog::openlog('ikiwiki', '', 'user');
222 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
225 elsif (! $config{cgi}) {
229 return print STDERR "@_\n";
233 sub possibly_foolish_untaint ($) { #{{{
235 my ($untainted)=$tainted=~/(.*)/s;
239 sub basename ($) { #{{{
246 sub dirname ($) { #{{{
253 sub pagetype ($) { #{{{
256 if ($page =~ /\.([^.]+)$/) {
257 return $1 if exists $hooks{htmlize}{$1};
262 sub isinternal ($) { #{{{
264 return exists $pagesources{$page} &&
265 $pagesources{$page} =~ /\._([^.]+)$/;
268 sub pagename ($) { #{{{
271 my $type=pagetype($file);
273 $page=~s/\Q.$type\E*$// if defined $type;
277 sub targetpage ($$) { #{{{
281 if (! $config{usedirs} || $page =~ /^index$/ ) {
282 return $page.".".$ext;
284 return $page."/index.".$ext;
288 sub htmlpage ($) { #{{{
291 return targetpage($page, $config{htmlext});
294 sub srcfile_stat { #{{{
298 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
299 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
300 return "$dir/$file", stat(_) if -e "$dir/$file";
302 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
306 sub srcfile ($;$) { #{{{
307 return (srcfile_stat(@_))[0];
310 sub add_underlay ($) { #{{{
314 unshift @{$config{underlaydirs}}, $dir;
317 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
323 sub readfile ($;$$) { #{{{
329 error("cannot read a symlink ($file)");
333 open (my $in, "<", $file) || error("failed to read $file: $!");
334 binmode($in) if ($binary);
335 return \*$in if $wantfd;
337 # check for invalid utf-8, and toss it back to avoid crashes
338 if (! utf8::valid($ret)) {
339 $ret=encode_utf8($ret);
341 close $in || error("failed to read $file: $!");
345 sub prep_writefile ($$) {
350 while (length $test) {
351 if (-l "$destdir/$test") {
352 error("cannot write to a symlink ($test)");
354 $test=dirname($test);
357 my $dir=dirname("$destdir/$file");
360 foreach my $s (split(m!/+!, $dir)) {
363 mkdir($d) || error("failed to create directory $d: $!");
371 sub writefile ($$$;$$) { #{{{
372 my $file=shift; # can include subdirs
373 my $destdir=shift; # directory to put file in
378 prep_writefile($file, $destdir);
380 my $newfile="$destdir/$file.ikiwiki-new";
382 error("cannot write to a symlink ($newfile)");
385 my $cleanup = sub { unlink($newfile) };
386 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
387 binmode($out) if ($binary);
389 $writer->(\*$out, $cleanup);
392 print $out $content or error("failed writing to $newfile: $!", $cleanup);
394 close $out || error("failed saving $newfile: $!", $cleanup);
395 rename($newfile, "$destdir/$file") ||
396 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
402 sub will_render ($$;$) { #{{{
407 # Important security check.
408 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
409 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
410 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
413 if (! $clear || $cleared{$page}) {
414 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
417 foreach my $old (@{$renderedfiles{$page}}) {
418 delete $destsources{$old};
420 $renderedfiles{$page}=[$dest];
423 $destsources{$dest}=$page;
428 sub bestlink ($$) { #{{{
433 if ($link=~s/^\/+//) {
441 $l.="/" if length $l;
444 if (exists $links{$l}) {
447 elsif (exists $pagecase{lc $l}) {
448 return $pagecase{lc $l};
450 } while $cwd=~s!/?[^/]+$!!;
452 if (length $config{userdir}) {
453 my $l = "$config{userdir}/".lc($link);
454 if (exists $links{$l}) {
457 elsif (exists $pagecase{lc $l}) {
458 return $pagecase{lc $l};
462 #print STDERR "warning: page $page, broken link: $link\n";
466 sub isinlinableimage ($) { #{{{
469 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
472 sub pagetitle ($;$) { #{{{
477 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
480 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
486 sub titlepage ($) { #{{{
488 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
492 sub linkpage ($) { #{{{
494 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
498 sub cgiurl (@) { #{{{
501 return $config{cgiurl}."?".
502 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
505 sub baseurl (;$) { #{{{
508 return "$config{url}/" if ! defined $page;
510 $page=htmlpage($page);
512 $page=~s/[^\/]+\//..\//g;
516 sub abs2rel ($$) { #{{{
517 # Work around very innefficient behavior in File::Spec if abs2rel
518 # is passed two relative paths. It's much faster if paths are
519 # absolute! (Debian bug #376658; fixed in debian unstable now)
524 my $ret=File::Spec->abs2rel($path, $base);
525 $ret=~s/^// if defined $ret;
529 sub displaytime ($;$) { #{{{
532 if (! defined $format) {
533 $format=$config{timeformat};
536 # strftime doesn't know about encodings, so make sure
537 # its output is properly treated as utf8
538 return decode_utf8(POSIX::strftime($format, localtime($time)));
541 sub beautify_url ($) { #{{{
544 if ($config{usedirs}) {
545 $url =~ s!/index.$config{htmlext}$!/!;
548 # Ensure url is not an empty link, and
549 # if it's relative, make that explicit to avoid colon confusion.
557 sub urlto ($$;$) { #{{{
563 return beautify_url(baseurl($from)."index.$config{htmlext}");
566 if (! $destsources{$to}) {
571 return $config{url}.beautify_url("/".$to);
574 my $link = abs2rel($to, dirname(htmlpage($from)));
576 return beautify_url($link);
579 sub htmllink ($$$;@) { #{{{
580 my $lpage=shift; # the page doing the linking
581 my $page=shift; # the page that will contain the link (different for inline)
588 if (! $opts{forcesubpage}) {
589 $bestlink=bestlink($lpage, $link);
592 $bestlink="$lpage/".lc($link);
596 if (defined $opts{linktext}) {
597 $linktext=$opts{linktext};
600 $linktext=pagetitle(basename($link));
603 return "<span class=\"selflink\">$linktext</span>"
604 if length $bestlink && $page eq $bestlink &&
605 ! defined $opts{anchor};
607 if (! $destsources{$bestlink}) {
608 $bestlink=htmlpage($bestlink);
610 if (! $destsources{$bestlink}) {
611 return $linktext unless length $config{cgiurl};
612 return "<span class=\"createlink\"><a href=\"".
618 "\" rel=\"nofollow\">?</a>$linktext</span>"
622 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
623 $bestlink=beautify_url($bestlink);
625 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
626 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
629 if (defined $opts{anchor}) {
630 $bestlink.="#".$opts{anchor};
634 if (defined $opts{rel}) {
635 push @attrs, ' rel="'.$opts{rel}.'"';
637 if (defined $opts{class}) {
638 push @attrs, ' class="'.$opts{class}.'"';
641 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
644 sub userlink ($) { #{{{
647 my $oiduser=eval { openiduser($user) };
648 if (defined $oiduser) {
649 return "<a href=\"$user\">$oiduser</a>";
652 eval q{use CGI 'escapeHTML'};
655 return htmllink("", "", escapeHTML(
656 length $config{userdir} ? $config{userdir}."/".$user : $user
657 ), noimageinline => 1);
661 sub htmlize ($$$$) { #{{{
667 my $oneline = $content !~ /\n/;
669 if (exists $hooks{htmlize}{$type}) {
670 $content=$hooks{htmlize}{$type}{call}->(
676 error("htmlization of $type not supported");
679 run_hooks(sanitize => sub {
682 destpage => $destpage,
688 # hack to get rid of enclosing junk added by markdown
689 # and other htmlizers
691 $content=~s/<\/p>$//i;
698 sub linkify ($$$) { #{{{
703 run_hooks(linkify => sub {
706 destpage => $destpage,
715 our $preprocess_preview=0;
716 sub preprocess ($$$;$$) { #{{{
717 my $page=shift; # the page the data comes from
718 my $destpage=shift; # the page the data will appear in (different for inline)
723 # Using local because it needs to be set within any nested calls
725 local $preprocess_preview=$preview if defined $preview;
732 $params="" if ! defined $params;
734 if (length $escape) {
735 return "[[$prefix$command $params]]";
737 elsif (exists $hooks{preprocess}{$command}) {
738 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
739 # Note: preserve order of params, some plugins may
740 # consider it significant.
743 (?:([-\w]+)=)? # 1: named parameter key?
745 """(.*?)""" # 2: triple-quoted value
747 "([^"]+)" # 3: single-quoted value
749 (\S+) # 4: unquoted value
751 (?:\s+|$) # delimiter to next param
769 push @params, $key, $val;
772 push @params, $val, '';
775 if ($preprocessing{$page}++ > 3) {
776 # Avoid loops of preprocessed pages preprocessing
777 # other pages that preprocess them, etc.
778 #translators: The first parameter is a
779 #translators: preprocessor directive name,
780 #translators: the second a page name, the
781 #translators: third a number.
782 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
783 $command, $page, $preprocessing{$page}).
788 $ret=$hooks{preprocess}{$command}{call}->(
791 destpage => $destpage,
792 preview => $preprocess_preview,
796 # use void context during scan pass
797 $hooks{preprocess}{$command}{call}->(
800 destpage => $destpage,
801 preview => $preprocess_preview,
805 $preprocessing{$page}--;
809 return "[[$prefix$command $params]]";
814 if ($config{prefix_directives}) {
817 \[\[(!) # directive open; 2: prefix
818 ([-\w]+) # 3: command
819 ( # 4: the parameters..
820 \s+ # Must have space if parameters present
822 (?:[-\w]+=)? # named parameter key?
824 """.*?""" # triple-quoted value
826 "[^"]+" # single-quoted value
828 [^\s\]]+ # unquoted value
830 \s* # whitespace or end
833 *)? # 0 or more parameters
834 \]\] # directive closed
839 \[\[(!?) # directive open; 2: optional prefix
840 ([-\w]+) # 3: command
842 ( # 4: the parameters..
844 (?:[-\w]+=)? # named parameter key?
846 """.*?""" # triple-quoted value
848 "[^"]+" # single-quoted value
850 [^\s\]]+ # unquoted value
852 \s* # whitespace or end
855 *) # 0 or more parameters
856 \]\] # directive closed
860 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
864 sub filter ($$$) { #{{{
869 run_hooks(filter => sub {
870 $content=shift->(page => $page, destpage => $destpage,
871 content => $content);
877 sub indexlink () { #{{{
878 return "<a href=\"$config{url}\">$config{wikiname}</a>";
883 sub lockwiki (;$) { #{{{
884 my $wait=@_ ? shift : 1;
885 # Take an exclusive lock on the wiki to prevent multiple concurrent
886 # run issues. The lock will be dropped on program exit.
887 if (! -d $config{wikistatedir}) {
888 mkdir($config{wikistatedir});
890 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
891 error ("cannot write to $config{wikistatedir}/lockfile: $!");
892 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
894 debug("wiki seems to be locked, waiting for lock");
895 my $wait=600; # arbitrary, but don't hang forever to
896 # prevent process pileup
898 return if flock($wikilock, 2 | 4);
901 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
910 sub unlockwiki () { #{{{
911 return close($wikilock) if $wikilock;
917 sub commit_hook_enabled () { #{{{
918 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
919 error("cannot write to $config{wikistatedir}/commitlock: $!");
920 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
921 close($commitlock) || error("failed closing commitlock: $!");
924 close($commitlock) || error("failed closing commitlock: $!");
928 sub disable_commit_hook () { #{{{
929 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
930 error("cannot write to $config{wikistatedir}/commitlock: $!");
931 if (! flock($commitlock, 2)) { # LOCK_EX
932 error("failed to get commit lock");
937 sub enable_commit_hook () { #{{{
938 return close($commitlock) if $commitlock;
942 sub loadindex () { #{{{
943 %oldrenderedfiles=%pagectime=();
944 if (! $config{rebuild}) {
945 %pagesources=%pagemtime=%oldlinks=%links=%depends=
946 %destsources=%renderedfiles=%pagecase=%pagestate=();
949 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
950 if (-e "$config{wikistatedir}/index") {
951 system("ikiwiki-transition", "indexdb", $config{srcdir});
952 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
958 my $ret=Storable::fd_retrieve($in);
959 if (! defined $ret) {
963 foreach my $src (keys %index) {
964 my %d=%{$index{$src}};
965 my $page=pagename($src);
966 $pagectime{$page}=$d{ctime};
967 if (! $config{rebuild}) {
968 $pagesources{$page}=$src;
969 $pagemtime{$page}=$d{mtime};
970 $renderedfiles{$page}=$d{dest};
971 if (exists $d{links} && ref $d{links}) {
972 $links{$page}=$d{links};
973 $oldlinks{$page}=[@{$d{links}}];
975 if (exists $d{depends}) {
976 $depends{$page}=$d{depends};
978 if (exists $d{state}) {
979 $pagestate{$page}=$d{state};
982 $oldrenderedfiles{$page}=[@{$d{dest}}];
984 foreach my $page (keys %pagesources) {
985 $pagecase{lc $page}=$page;
987 foreach my $page (keys %renderedfiles) {
988 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
993 sub saveindex () { #{{{
994 run_hooks(savestate => sub { shift->() });
997 foreach my $type (keys %hooks) {
998 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1000 my @hookids=keys %hookids;
1002 if (! -d $config{wikistatedir}) {
1003 mkdir($config{wikistatedir});
1005 my $newfile="$config{wikistatedir}/indexdb.new";
1006 my $cleanup = sub { unlink($newfile) };
1007 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1009 foreach my $page (keys %pagemtime) {
1010 next unless $pagemtime{$page};
1011 my $src=$pagesources{$page};
1014 ctime => $pagectime{$page},
1015 mtime => $pagemtime{$page},
1016 dest => $renderedfiles{$page},
1017 links => $links{$page},
1020 if (exists $depends{$page}) {
1021 $index{$src}{depends} = $depends{$page};
1024 if (exists $pagestate{$page}) {
1025 foreach my $id (@hookids) {
1026 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1027 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1032 my $ret=Storable::nstore_fd(\%index, $out);
1033 return if ! defined $ret || ! $ret;
1034 close $out || error("failed saving to $newfile: $!", $cleanup);
1035 rename($newfile, "$config{wikistatedir}/indexdb") ||
1036 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1041 sub template_file ($) { #{{{
1044 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1045 return "$dir/$template" if -e "$dir/$template";
1050 sub template_params (@) { #{{{
1051 my $filename=template_file(shift);
1053 if (! defined $filename) {
1054 return if wantarray;
1060 my $text_ref = shift;
1061 ${$text_ref} = decode_utf8(${$text_ref});
1063 filename => $filename,
1064 loop_context_vars => 1,
1065 die_on_bad_params => 0,
1068 return wantarray ? @ret : {@ret};
1071 sub template ($;@) { #{{{
1072 require HTML::Template;
1073 return HTML::Template->new(template_params(@_));
1076 sub misctemplate ($$;@) { #{{{
1080 my $template=template("misc.tmpl");
1083 indexlink => indexlink(),
1084 wikiname => $config{wikiname},
1085 pagebody => $pagebody,
1086 baseurl => baseurl(),
1089 run_hooks(pagetemplate => sub {
1090 shift->(page => "", destpage => "", template => $template);
1092 return $template->output;
1095 sub hook (@) { # {{{
1098 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1099 error 'hook requires type, call, and id parameters';
1102 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1104 $hooks{$param{type}}{$param{id}}=\%param;
1108 sub run_hooks ($$) { # {{{
1109 # Calls the given sub for each hook of the given type,
1110 # passing it the hook function to call.
1114 if (exists $hooks{$type}) {
1116 foreach my $id (keys %{$hooks{$type}}) {
1117 if ($hooks{$type}{$id}{last}) {
1118 push @deferred, $id;
1121 $sub->($hooks{$type}{$id}{call});
1123 foreach my $id (@deferred) {
1124 $sub->($hooks{$type}{$id}{call});
1131 sub globlist_to_pagespec ($) { #{{{
1132 my @globlist=split(' ', shift);
1135 foreach my $glob (@globlist) {
1136 if ($glob=~/^!(.*)/) {
1144 my $spec=join(' or ', @spec);
1146 my $skip=join(' and ', @skip);
1148 $spec="$skip and ($spec)";
1157 sub is_globlist ($) { #{{{
1159 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1162 sub safequote ($) { #{{{
1168 sub add_depends ($$) { #{{{
1172 return unless pagespec_valid($pagespec);
1174 if (! exists $depends{$page}) {
1175 $depends{$page}=$pagespec;
1178 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1184 sub file_pruned ($$) { #{{{
1186 my $file=File::Spec->canonpath(shift);
1187 my $base=File::Spec->canonpath(shift);
1188 $file =~ s#^\Q$base\E/+##;
1190 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1191 return $file =~ m/$regexp/ && $file ne $base;
1195 # Only use gettext in the rare cases it's needed.
1196 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1197 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1198 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1199 if (! $gettext_obj) {
1200 $gettext_obj=eval q{
1201 use Locale::gettext q{textdomain};
1202 Locale::gettext->domain('ikiwiki')
1210 return $gettext_obj->get(shift);
1217 sub pagespec_merge ($$) { #{{{
1221 return $a if $a eq $b;
1223 # Support for old-style GlobLists.
1224 if (is_globlist($a)) {
1225 $a=globlist_to_pagespec($a);
1227 if (is_globlist($b)) {
1228 $b=globlist_to_pagespec($b);
1231 return "($a) or ($b)";
1234 sub pagespec_translate ($) { #{{{
1237 # Support for old-style GlobLists.
1238 if (is_globlist($spec)) {
1239 $spec=globlist_to_pagespec($spec);
1242 # Convert spec to perl code.
1245 \s* # ignore whitespace
1246 ( # 1: match a single word
1253 \w+\([^\)]*\) # command(params)
1255 [^\s()]+ # any other text
1257 \s* # ignore whitespace
1260 if (lc $word eq 'and') {
1263 elsif (lc $word eq 'or') {
1266 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1269 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1270 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1271 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1278 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1282 if (! length $code) {
1287 return eval 'sub { my $page=shift; '.$code.' }';
1290 sub pagespec_match ($$;@) { #{{{
1295 # Backwards compatability with old calling convention.
1297 unshift @params, 'location';
1300 my $sub=pagespec_translate($spec);
1301 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1302 return $sub->($page, @params);
1305 sub pagespec_valid ($) { #{{{
1308 my $sub=pagespec_translate($spec);
1312 sub glob2re ($) { #{{{
1313 my $re=quotemeta(shift);
1319 package IkiWiki::FailReason;
1322 '""' => sub { ${$_[0]} },
1324 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1331 return bless \$value, $class;
1334 package IkiWiki::SuccessReason;
1337 '""' => sub { ${$_[0]} },
1339 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1346 return bless \$value, $class;
1349 package IkiWiki::PageSpec;
1351 sub match_glob ($$;@) { #{{{
1356 my $from=exists $params{location} ? $params{location} : '';
1359 if ($glob =~ m!^\./!) {
1360 $from=~s#/?[^/]+$##;
1362 $glob="$from/$glob" if length $from;
1365 my $regexp=IkiWiki::glob2re($glob);
1366 if ($page=~/^$regexp$/i) {
1367 if (! IkiWiki::isinternal($page) || $params{internal}) {
1368 return IkiWiki::SuccessReason->new("$glob matches $page");
1371 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1375 return IkiWiki::FailReason->new("$glob does not match $page");
1379 sub match_internal ($$;@) { #{{{
1380 return match_glob($_[0], $_[1], @_, internal => 1)
1383 sub match_link ($$;@) { #{{{
1388 my $from=exists $params{location} ? $params{location} : '';
1391 if ($link =~ m!^\.! && defined $from) {
1392 $from=~s#/?[^/]+$##;
1394 $link="$from/$link" if length $from;
1397 my $links = $IkiWiki::links{$page};
1398 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1399 my $bestlink = IkiWiki::bestlink($from, $link);
1400 foreach my $p (@{$links}) {
1401 if (length $bestlink) {
1402 return IkiWiki::SuccessReason->new("$page links to $link")
1403 if $bestlink eq IkiWiki::bestlink($page, $p);
1406 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1407 if match_glob($p, $link, %params);
1410 return IkiWiki::FailReason->new("$page does not link to $link");
1413 sub match_backlink ($$;@) { #{{{
1414 return match_link($_[1], $_[0], @_);
1417 sub match_created_before ($$;@) { #{{{
1421 if (exists $IkiWiki::pagectime{$testpage}) {
1422 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1423 return IkiWiki::SuccessReason->new("$page created before $testpage");
1426 return IkiWiki::FailReason->new("$page not created before $testpage");
1430 return IkiWiki::FailReason->new("$testpage has no ctime");
1434 sub match_created_after ($$;@) { #{{{
1438 if (exists $IkiWiki::pagectime{$testpage}) {
1439 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1440 return IkiWiki::SuccessReason->new("$page created after $testpage");
1443 return IkiWiki::FailReason->new("$page not created after $testpage");
1447 return IkiWiki::FailReason->new("$testpage has no ctime");
1451 sub match_creation_day ($$;@) { #{{{
1452 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1453 return IkiWiki::SuccessReason->new('creation_day matched');
1456 return IkiWiki::FailReason->new('creation_day did not match');
1460 sub match_creation_month ($$;@) { #{{{
1461 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1462 return IkiWiki::SuccessReason->new('creation_month matched');
1465 return IkiWiki::FailReason->new('creation_month did not match');
1469 sub match_creation_year ($$;@) { #{{{
1470 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1471 return IkiWiki::SuccessReason->new('creation_year matched');
1474 return IkiWiki::FailReason->new('creation_year did not match');