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 ($$) { #{{{
553 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
556 if (! $destsources{$to}) {
560 my $link = abs2rel($to, dirname(htmlpage($from)));
562 return beautify_urlpath($link);
565 sub htmllink ($$$;@) { #{{{
566 my $lpage=shift; # the page doing the linking
567 my $page=shift; # the page that will contain the link (different for inline)
574 if (! $opts{forcesubpage}) {
575 $bestlink=bestlink($lpage, $link);
578 $bestlink="$lpage/".lc($link);
582 if (defined $opts{linktext}) {
583 $linktext=$opts{linktext};
586 $linktext=pagetitle(basename($link));
589 return "<span class=\"selflink\">$linktext</span>"
590 if length $bestlink && $page eq $bestlink &&
591 ! defined $opts{anchor};
593 if (! $destsources{$bestlink}) {
594 $bestlink=htmlpage($bestlink);
596 if (! $destsources{$bestlink}) {
597 return $linktext unless length $config{cgiurl};
598 return "<span class=\"createlink\"><a href=\"".
604 "\" rel=\"nofollow\">?</a>$linktext</span>"
608 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
609 $bestlink=beautify_urlpath($bestlink);
611 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
612 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
615 if (defined $opts{anchor}) {
616 $bestlink.="#".$opts{anchor};
620 if (defined $opts{rel}) {
621 push @attrs, ' rel="'.$opts{rel}.'"';
623 if (defined $opts{class}) {
624 push @attrs, ' class="'.$opts{class}.'"';
627 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
630 sub userlink ($) { #{{{
633 my $oiduser=eval { openiduser($user) };
634 if (defined $oiduser) {
635 return "<a href=\"$user\">$oiduser</a>";
638 eval q{use CGI 'escapeHTML'};
641 return htmllink("", "", escapeHTML(
642 length $config{userdir} ? $config{userdir}."/".$user : $user
643 ), noimageinline => 1);
647 sub htmlize ($$$$) { #{{{
653 my $oneline = $content !~ /\n/;
655 if (exists $hooks{htmlize}{$type}) {
656 $content=$hooks{htmlize}{$type}{call}->(
662 error("htmlization of $type not supported");
665 run_hooks(sanitize => sub {
668 destpage => $destpage,
674 # hack to get rid of enclosing junk added by markdown
675 # and other htmlizers
677 $content=~s/<\/p>$//i;
684 sub linkify ($$$) { #{{{
689 run_hooks(linkify => sub {
692 destpage => $destpage,
701 our $preprocess_preview=0;
702 sub preprocess ($$$;$$) { #{{{
703 my $page=shift; # the page the data comes from
704 my $destpage=shift; # the page the data will appear in (different for inline)
709 # Using local because it needs to be set within any nested calls
711 local $preprocess_preview=$preview if defined $preview;
718 if (length $escape) {
719 return "[[$prefix$command $params]]";
721 elsif (exists $hooks{preprocess}{$command}) {
722 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
723 # Note: preserve order of params, some plugins may
724 # consider it significant.
727 (?:([-\w]+)=)? # 1: named parameter key?
729 """(.*?)""" # 2: triple-quoted value
731 "([^"]+)" # 3: single-quoted value
733 (\S+) # 4: unquoted value
735 (?:\s+|$) # delimiter to next param
753 push @params, $key, $val;
756 push @params, $val, '';
759 if ($preprocessing{$page}++ > 3) {
760 # Avoid loops of preprocessed pages preprocessing
761 # other pages that preprocess them, etc.
762 #translators: The first parameter is a
763 #translators: preprocessor directive name,
764 #translators: the second a page name, the
765 #translators: third a number.
766 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
767 $command, $page, $preprocessing{$page}).
773 $hooks{preprocess}{$command}{call}->(
776 destpage => $destpage,
777 preview => $preprocess_preview,
782 $ret="[[!$command <span class=\"error\">".
783 gettext("Error").": $@"."</span>]]";
787 # use void context during scan pass
789 $hooks{preprocess}{$command}{call}->(
792 destpage => $destpage,
793 preview => $preprocess_preview,
798 $preprocessing{$page}--;
802 return "[[$prefix$command $params]]";
807 if ($config{prefix_directives}) {
810 \[\[(!) # directive open; 2: prefix
811 ([-\w]+) # 3: command
812 ( # 4: the parameters..
813 \s+ # Must have space if parameters present
815 (?:[-\w]+=)? # named parameter key?
817 """.*?""" # triple-quoted value
819 "[^"]+" # single-quoted value
821 [^\s\]]+ # unquoted value
823 \s* # whitespace or end
826 *)? # 0 or more parameters
827 \]\] # directive closed
833 \[\[(!?) # directive open; 2: optional prefix
834 ([-\w]+) # 3: command
836 ( # 4: the parameters..
838 (?:[-\w]+=)? # named parameter key?
840 """.*?""" # triple-quoted value
842 "[^"]+" # single-quoted value
844 [^\s\]]+ # unquoted value
846 \s* # whitespace or end
849 *) # 0 or more parameters
850 \]\] # directive closed
854 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
858 sub filter ($$$) { #{{{
863 run_hooks(filter => sub {
864 $content=shift->(page => $page, destpage => $destpage,
865 content => $content);
871 sub indexlink () { #{{{
872 return "<a href=\"$config{url}\">$config{wikiname}</a>";
877 sub lockwiki (;$) { #{{{
878 my $wait=@_ ? shift : 1;
879 # Take an exclusive lock on the wiki to prevent multiple concurrent
880 # run issues. The lock will be dropped on program exit.
881 if (! -d $config{wikistatedir}) {
882 mkdir($config{wikistatedir});
884 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
885 error ("cannot write to $config{wikistatedir}/lockfile: $!");
886 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
888 debug("wiki seems to be locked, waiting for lock");
889 my $wait=600; # arbitrary, but don't hang forever to
890 # prevent process pileup
892 return if flock($wikilock, 2 | 4);
895 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
904 sub unlockwiki () { #{{{
905 return close($wikilock) if $wikilock;
911 sub commit_hook_enabled () { #{{{
912 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
913 error("cannot write to $config{wikistatedir}/commitlock: $!");
914 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
915 close($commitlock) || error("failed closing commitlock: $!");
918 close($commitlock) || error("failed closing commitlock: $!");
922 sub disable_commit_hook () { #{{{
923 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
924 error("cannot write to $config{wikistatedir}/commitlock: $!");
925 if (! flock($commitlock, 2)) { # LOCK_EX
926 error("failed to get commit lock");
931 sub enable_commit_hook () { #{{{
932 return close($commitlock) if $commitlock;
936 sub loadindex () { #{{{
937 %oldrenderedfiles=%pagectime=();
938 if (! $config{rebuild}) {
939 %pagesources=%pagemtime=%oldlinks=%links=%depends=
940 %destsources=%renderedfiles=%pagecase=%pagestate=();
943 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
944 if (-e "$config{wikistatedir}/index") {
945 system("ikiwiki-transition", "indexdb", $config{srcdir});
946 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
952 my $ret=Storable::fd_retrieve($in);
953 if (! defined $ret) {
957 foreach my $src (keys %index) {
958 my %d=%{$index{$src}};
959 my $page=pagename($src);
960 $pagectime{$page}=$d{ctime};
961 if (! $config{rebuild}) {
962 $pagesources{$page}=$src;
963 $pagemtime{$page}=$d{mtime};
964 $renderedfiles{$page}=$d{dest};
965 if (exists $d{links} && ref $d{links}) {
966 $links{$page}=$d{links};
967 $oldlinks{$page}=[@{$d{links}}];
969 if (exists $d{depends}) {
970 $depends{$page}=$d{depends};
972 if (exists $d{state}) {
973 $pagestate{$page}=$d{state};
976 $oldrenderedfiles{$page}=[@{$d{dest}}];
978 foreach my $page (keys %pagesources) {
979 $pagecase{lc $page}=$page;
981 foreach my $page (keys %renderedfiles) {
982 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
987 sub saveindex () { #{{{
988 run_hooks(savestate => sub { shift->() });
991 foreach my $type (keys %hooks) {
992 $hookids{$_}=1 foreach keys %{$hooks{$type}};
994 my @hookids=keys %hookids;
996 if (! -d $config{wikistatedir}) {
997 mkdir($config{wikistatedir});
999 my $newfile="$config{wikistatedir}/indexdb.new";
1000 my $cleanup = sub { unlink($newfile) };
1001 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1003 foreach my $page (keys %pagemtime) {
1004 next unless $pagemtime{$page};
1005 my $src=$pagesources{$page};
1008 ctime => $pagectime{$page},
1009 mtime => $pagemtime{$page},
1010 dest => $renderedfiles{$page},
1011 links => $links{$page},
1014 if (exists $depends{$page}) {
1015 $index{$src}{depends} = $depends{$page};
1018 if (exists $pagestate{$page}) {
1019 foreach my $id (@hookids) {
1020 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1021 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1026 my $ret=Storable::nstore_fd(\%index, $out);
1027 return if ! defined $ret || ! $ret;
1028 close $out || error("failed saving to $newfile: $!", $cleanup);
1029 rename($newfile, "$config{wikistatedir}/indexdb") ||
1030 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1035 sub template_file ($) { #{{{
1038 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1039 return "$dir/$template" if -e "$dir/$template";
1044 sub template_params (@) { #{{{
1045 my $filename=template_file(shift);
1047 if (! defined $filename) {
1048 return if wantarray;
1054 my $text_ref = shift;
1055 ${$text_ref} = decode_utf8(${$text_ref});
1057 filename => $filename,
1058 loop_context_vars => 1,
1059 die_on_bad_params => 0,
1062 return wantarray ? @ret : {@ret};
1065 sub template ($;@) { #{{{
1066 require HTML::Template;
1067 return HTML::Template->new(template_params(@_));
1070 sub misctemplate ($$;@) { #{{{
1074 my $template=template("misc.tmpl");
1077 indexlink => indexlink(),
1078 wikiname => $config{wikiname},
1079 pagebody => $pagebody,
1080 baseurl => baseurl(),
1083 run_hooks(pagetemplate => sub {
1084 shift->(page => "", destpage => "", template => $template);
1086 return $template->output;
1089 sub hook (@) { # {{{
1092 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1093 error 'hook requires type, call, and id parameters';
1096 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1098 $hooks{$param{type}}{$param{id}}=\%param;
1102 sub run_hooks ($$) { # {{{
1103 # Calls the given sub for each hook of the given type,
1104 # passing it the hook function to call.
1108 if (exists $hooks{$type}) {
1110 foreach my $id (keys %{$hooks{$type}}) {
1111 if ($hooks{$type}{$id}{last}) {
1112 push @deferred, $id;
1115 $sub->($hooks{$type}{$id}{call});
1117 foreach my $id (@deferred) {
1118 $sub->($hooks{$type}{$id}{call});
1125 sub globlist_to_pagespec ($) { #{{{
1126 my @globlist=split(' ', shift);
1129 foreach my $glob (@globlist) {
1130 if ($glob=~/^!(.*)/) {
1138 my $spec=join(' or ', @spec);
1140 my $skip=join(' and ', @skip);
1142 $spec="$skip and ($spec)";
1151 sub is_globlist ($) { #{{{
1153 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1156 sub safequote ($) { #{{{
1162 sub add_depends ($$) { #{{{
1166 return unless pagespec_valid($pagespec);
1168 if (! exists $depends{$page}) {
1169 $depends{$page}=$pagespec;
1172 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1178 sub file_pruned ($$) { #{{{
1180 my $file=File::Spec->canonpath(shift);
1181 my $base=File::Spec->canonpath(shift);
1182 $file =~ s#^\Q$base\E/+##;
1184 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1185 return $file =~ m/$regexp/ && $file ne $base;
1189 # Only use gettext in the rare cases it's needed.
1190 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1191 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1192 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1193 if (! $gettext_obj) {
1194 $gettext_obj=eval q{
1195 use Locale::gettext q{textdomain};
1196 Locale::gettext->domain('ikiwiki')
1204 return $gettext_obj->get(shift);
1211 sub yesno ($) { #{{{
1214 return (defined $val && lc($val) eq gettext("yes"));
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');