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 loadplugin($_) foreach @{$config{plugin}};
156 run_hooks(getopt => sub { shift->() });
157 if (grep /^-/, @ARGV) {
158 print STDERR "Unknown option: $_\n"
159 foreach grep /^-/, @ARGV;
166 sub loadplugin ($) { #{{{
169 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
171 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
172 "$installdir/lib/ikiwiki") {
173 if (defined $dir && -x "$dir/plugins/$plugin") {
174 require IkiWiki::Plugin::external;
175 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
180 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
183 error("Failed to load plugin $mod: $@");
188 sub error ($;$) { #{{{
192 print "Content-type: text/html\n\n";
193 print misctemplate(gettext("Error"),
194 "<p>".gettext("Error").": $message</p>");
196 log_message('err' => $message) if $config{syslog};
197 if (defined $cleaner) {
204 return unless $config{verbose};
205 return log_message(debug => @_);
209 sub log_message ($$) { #{{{
212 if ($config{syslog}) {
215 Sys::Syslog::setlogsock('unix');
216 Sys::Syslog::openlog('ikiwiki', '', 'user');
220 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
223 elsif (! $config{cgi}) {
227 return print STDERR "@_\n";
231 sub possibly_foolish_untaint ($) { #{{{
233 my ($untainted)=$tainted=~/(.*)/s;
237 sub basename ($) { #{{{
244 sub dirname ($) { #{{{
251 sub pagetype ($) { #{{{
254 if ($page =~ /\.([^.]+)$/) {
255 return $1 if exists $hooks{htmlize}{$1};
260 sub isinternal ($) { #{{{
262 return exists $pagesources{$page} &&
263 $pagesources{$page} =~ /\._([^.]+)$/;
266 sub pagename ($) { #{{{
269 my $type=pagetype($file);
271 $page=~s/\Q.$type\E*$// if defined $type;
275 sub targetpage ($$) { #{{{
279 if (! $config{usedirs} || $page =~ /^index$/ ) {
280 return $page.".".$ext;
282 return $page."/index.".$ext;
286 sub htmlpage ($) { #{{{
289 return targetpage($page, $config{htmlext});
292 sub srcfile_stat { #{{{
296 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
297 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
298 return "$dir/$file", stat(_) if -e "$dir/$file";
300 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
304 sub srcfile ($;$) { #{{{
305 return (srcfile_stat(@_))[0];
308 sub add_underlay ($) { #{{{
312 unshift @{$config{underlaydirs}}, $dir;
315 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
321 sub readfile ($;$$) { #{{{
327 error("cannot read a symlink ($file)");
331 open (my $in, "<", $file) || error("failed to read $file: $!");
332 binmode($in) if ($binary);
333 return \*$in if $wantfd;
335 close $in || error("failed to read $file: $!");
339 sub prep_writefile ($$) {
344 while (length $test) {
345 if (-l "$destdir/$test") {
346 error("cannot write to a symlink ($test)");
348 $test=dirname($test);
351 my $dir=dirname("$destdir/$file");
354 foreach my $s (split(m!/+!, $dir)) {
357 mkdir($d) || error("failed to create directory $d: $!");
365 sub writefile ($$$;$$) { #{{{
366 my $file=shift; # can include subdirs
367 my $destdir=shift; # directory to put file in
372 prep_writefile($file, $destdir);
374 my $newfile="$destdir/$file.ikiwiki-new";
376 error("cannot write to a symlink ($newfile)");
379 my $cleanup = sub { unlink($newfile) };
380 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
381 binmode($out) if ($binary);
383 $writer->(\*$out, $cleanup);
386 print $out $content or error("failed writing to $newfile: $!", $cleanup);
388 close $out || error("failed saving $newfile: $!", $cleanup);
389 rename($newfile, "$destdir/$file") ||
390 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
396 sub will_render ($$;$) { #{{{
401 # Important security check.
402 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
403 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
404 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
407 if (! $clear || $cleared{$page}) {
408 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
411 foreach my $old (@{$renderedfiles{$page}}) {
412 delete $destsources{$old};
414 $renderedfiles{$page}=[$dest];
417 $destsources{$dest}=$page;
422 sub bestlink ($$) { #{{{
427 if ($link=~s/^\/+//) {
435 $l.="/" if length $l;
438 if (exists $links{$l}) {
441 elsif (exists $pagecase{lc $l}) {
442 return $pagecase{lc $l};
444 } while $cwd=~s!/?[^/]+$!!;
446 if (length $config{userdir}) {
447 my $l = "$config{userdir}/".lc($link);
448 if (exists $links{$l}) {
451 elsif (exists $pagecase{lc $l}) {
452 return $pagecase{lc $l};
456 #print STDERR "warning: page $page, broken link: $link\n";
460 sub isinlinableimage ($) { #{{{
463 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
466 sub pagetitle ($;$) { #{{{
471 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
474 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
480 sub titlepage ($) { #{{{
482 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
486 sub linkpage ($) { #{{{
488 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
492 sub cgiurl (@) { #{{{
495 return $config{cgiurl}."?".
496 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
499 sub baseurl (;$) { #{{{
502 return "$config{url}/" if ! defined $page;
504 $page=htmlpage($page);
506 $page=~s/[^\/]+\//..\//g;
510 sub abs2rel ($$) { #{{{
511 # Work around very innefficient behavior in File::Spec if abs2rel
512 # is passed two relative paths. It's much faster if paths are
513 # absolute! (Debian bug #376658; fixed in debian unstable now)
518 my $ret=File::Spec->abs2rel($path, $base);
519 $ret=~s/^// if defined $ret;
523 sub displaytime ($;$) { #{{{
526 if (! defined $format) {
527 $format=$config{timeformat};
530 # strftime doesn't know about encodings, so make sure
531 # its output is properly treated as utf8
532 return decode_utf8(POSIX::strftime($format, localtime($time)));
535 sub beautify_url ($) { #{{{
538 if ($config{usedirs}) {
539 $url =~ s!/index.$config{htmlext}$!/!;
542 # Ensure url is not an empty link, and
543 # if it's relative, make that explicit to avoid colon confusion.
551 sub urlto ($$) { #{{{
556 return beautify_url(baseurl($from)."index.$config{htmlext}");
559 if (! $destsources{$to}) {
563 my $link = abs2rel($to, dirname(htmlpage($from)));
565 return beautify_url($link);
568 sub htmllink ($$$;@) { #{{{
569 my $lpage=shift; # the page doing the linking
570 my $page=shift; # the page that will contain the link (different for inline)
577 if (! $opts{forcesubpage}) {
578 $bestlink=bestlink($lpage, $link);
581 $bestlink="$lpage/".lc($link);
585 if (defined $opts{linktext}) {
586 $linktext=$opts{linktext};
589 $linktext=pagetitle(basename($link));
592 return "<span class=\"selflink\">$linktext</span>"
593 if length $bestlink && $page eq $bestlink &&
594 ! defined $opts{anchor};
596 if (! $destsources{$bestlink}) {
597 $bestlink=htmlpage($bestlink);
599 if (! $destsources{$bestlink}) {
600 return $linktext unless length $config{cgiurl};
601 return "<span class=\"createlink\"><a href=\"".
607 "\" rel=\"nofollow\">?</a>$linktext</span>"
611 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
612 $bestlink=beautify_url($bestlink);
614 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
615 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
618 if (defined $opts{anchor}) {
619 $bestlink.="#".$opts{anchor};
623 if (defined $opts{rel}) {
624 push @attrs, ' rel="'.$opts{rel}.'"';
626 if (defined $opts{class}) {
627 push @attrs, ' class="'.$opts{class}.'"';
630 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
633 sub userlink ($) { #{{{
636 my $oiduser=eval { openiduser($user) };
637 if (defined $oiduser) {
638 return "<a href=\"$user\">$oiduser</a>";
641 eval q{use CGI 'escapeHTML'};
644 return htmllink("", "", escapeHTML(
645 length $config{userdir} ? $config{userdir}."/".$user : $user
646 ), noimageinline => 1);
650 sub htmlize ($$$$) { #{{{
656 my $oneline = $content !~ /\n/;
658 if (exists $hooks{htmlize}{$type}) {
659 $content=$hooks{htmlize}{$type}{call}->(
665 error("htmlization of $type not supported");
668 run_hooks(sanitize => sub {
671 destpage => $destpage,
677 # hack to get rid of enclosing junk added by markdown
678 # and other htmlizers
680 $content=~s/<\/p>$//i;
687 sub linkify ($$$) { #{{{
692 run_hooks(linkify => sub {
695 destpage => $destpage,
704 our $preprocess_preview=0;
705 sub preprocess ($$$;$$) { #{{{
706 my $page=shift; # the page the data comes from
707 my $destpage=shift; # the page the data will appear in (different for inline)
712 # Using local because it needs to be set within any nested calls
714 local $preprocess_preview=$preview if defined $preview;
721 if (length $escape) {
722 return "[[$prefix$command $params]]";
724 elsif (exists $hooks{preprocess}{$command}) {
725 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
726 # Note: preserve order of params, some plugins may
727 # consider it significant.
730 (?:([-\w]+)=)? # 1: named parameter key?
732 """(.*?)""" # 2: triple-quoted value
734 "([^"]+)" # 3: single-quoted value
736 (\S+) # 4: unquoted value
738 (?:\s+|$) # delimiter to next param
756 push @params, $key, $val;
759 push @params, $val, '';
762 if ($preprocessing{$page}++ > 3) {
763 # Avoid loops of preprocessed pages preprocessing
764 # other pages that preprocess them, etc.
765 #translators: The first parameter is a
766 #translators: preprocessor directive name,
767 #translators: the second a page name, the
768 #translators: third a number.
769 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
770 $command, $page, $preprocessing{$page}).
775 $ret=$hooks{preprocess}{$command}{call}->(
778 destpage => $destpage,
779 preview => $preprocess_preview,
783 # use void context during scan pass
784 $hooks{preprocess}{$command}{call}->(
787 destpage => $destpage,
788 preview => $preprocess_preview,
792 $preprocessing{$page}--;
796 return "[[$prefix$command $params]]";
801 if ($config{prefix_directives}) {
804 \[\[(!) # directive open; 2: prefix
805 ([-\w]+) # 3: command
806 ( # 4: the parameters..
807 \s+ # Must have space if parameters present
809 (?:[-\w]+=)? # named parameter key?
811 """.*?""" # triple-quoted value
813 "[^"]+" # single-quoted value
815 [^\s\]]+ # unquoted value
817 \s* # whitespace or end
820 *)? # 0 or more parameters
821 \]\] # directive closed
826 \[\[(!?) # directive open; 2: optional prefix
827 ([-\w]+) # 3: command
829 ( # 4: the parameters..
831 (?:[-\w]+=)? # named parameter key?
833 """.*?""" # triple-quoted value
835 "[^"]+" # single-quoted value
837 [^\s\]]+ # unquoted value
839 \s* # whitespace or end
842 *) # 0 or more parameters
843 \]\] # directive closed
847 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
851 sub filter ($$$) { #{{{
856 run_hooks(filter => sub {
857 $content=shift->(page => $page, destpage => $destpage,
858 content => $content);
864 sub indexlink () { #{{{
865 return "<a href=\"$config{url}\">$config{wikiname}</a>";
870 sub lockwiki (;$) { #{{{
871 my $wait=@_ ? shift : 1;
872 # Take an exclusive lock on the wiki to prevent multiple concurrent
873 # run issues. The lock will be dropped on program exit.
874 if (! -d $config{wikistatedir}) {
875 mkdir($config{wikistatedir});
877 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
878 error ("cannot write to $config{wikistatedir}/lockfile: $!");
879 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
881 debug("wiki seems to be locked, waiting for lock");
882 my $wait=600; # arbitrary, but don't hang forever to
883 # prevent process pileup
885 return if flock($wikilock, 2 | 4);
888 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
897 sub unlockwiki () { #{{{
898 return close($wikilock) if $wikilock;
904 sub commit_hook_enabled () { #{{{
905 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
906 error("cannot write to $config{wikistatedir}/commitlock: $!");
907 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
908 close($commitlock) || error("failed closing commitlock: $!");
911 close($commitlock) || error("failed closing commitlock: $!");
915 sub disable_commit_hook () { #{{{
916 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
917 error("cannot write to $config{wikistatedir}/commitlock: $!");
918 if (! flock($commitlock, 2)) { # LOCK_EX
919 error("failed to get commit lock");
924 sub enable_commit_hook () { #{{{
925 return close($commitlock) if $commitlock;
929 sub loadindex () { #{{{
930 %oldrenderedfiles=%pagectime=();
931 if (! $config{rebuild}) {
932 %pagesources=%pagemtime=%oldlinks=%links=%depends=
933 %destsources=%renderedfiles=%pagecase=%pagestate=();
936 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
937 if (-e "$config{wikistatedir}/index") {
938 system("ikiwiki-transition", "indexdb", $config{srcdir});
939 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
945 my $ret=Storable::fd_retrieve($in);
946 if (! defined $ret) {
950 foreach my $src (keys %index) {
951 my %d=%{$index{$src}};
952 my $page=pagename($src);
953 $pagectime{$page}=$d{ctime};
954 if (! $config{rebuild}) {
955 $pagesources{$page}=$src;
956 $pagemtime{$page}=$d{mtime};
957 $renderedfiles{$page}=$d{dest};
958 if (exists $d{links} && ref $d{links}) {
959 $links{$page}=$d{links};
960 $oldlinks{$page}=[@{$d{links}}];
962 if (exists $d{depends}) {
963 $depends{$page}=$d{depends};
965 if (exists $d{state}) {
966 $pagestate{$page}=$d{state};
969 $oldrenderedfiles{$page}=[@{$d{dest}}];
971 foreach my $page (keys %pagesources) {
972 $pagecase{lc $page}=$page;
974 foreach my $page (keys %renderedfiles) {
975 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
980 sub saveindex () { #{{{
981 run_hooks(savestate => sub { shift->() });
984 foreach my $type (keys %hooks) {
985 $hookids{$_}=1 foreach keys %{$hooks{$type}};
987 my @hookids=keys %hookids;
989 if (! -d $config{wikistatedir}) {
990 mkdir($config{wikistatedir});
992 my $newfile="$config{wikistatedir}/indexdb.new";
993 my $cleanup = sub { unlink($newfile) };
994 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
996 foreach my $page (keys %pagemtime) {
997 next unless $pagemtime{$page};
998 my $src=$pagesources{$page};
1001 ctime => $pagectime{$page},
1002 mtime => $pagemtime{$page},
1003 dest => $renderedfiles{$page},
1004 links => $links{$page},
1007 if (exists $depends{$page}) {
1008 $index{$src}{depends} = $depends{$page};
1011 if (exists $pagestate{$page}) {
1012 foreach my $id (@hookids) {
1013 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1014 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1019 my $ret=Storable::nstore_fd(\%index, $out);
1020 return if ! defined $ret || ! $ret;
1021 close $out || error("failed saving to $newfile: $!", $cleanup);
1022 rename($newfile, "$config{wikistatedir}/indexdb") ||
1023 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1028 sub template_file ($) { #{{{
1031 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1032 return "$dir/$template" if -e "$dir/$template";
1037 sub template_params (@) { #{{{
1038 my $filename=template_file(shift);
1040 if (! defined $filename) {
1041 return if wantarray;
1047 my $text_ref = shift;
1048 ${$text_ref} = decode_utf8(${$text_ref});
1050 filename => $filename,
1051 loop_context_vars => 1,
1052 die_on_bad_params => 0,
1055 return wantarray ? @ret : {@ret};
1058 sub template ($;@) { #{{{
1059 require HTML::Template;
1060 return HTML::Template->new(template_params(@_));
1063 sub misctemplate ($$;@) { #{{{
1067 my $template=template("misc.tmpl");
1070 indexlink => indexlink(),
1071 wikiname => $config{wikiname},
1072 pagebody => $pagebody,
1073 baseurl => baseurl(),
1076 run_hooks(pagetemplate => sub {
1077 shift->(page => "", destpage => "", template => $template);
1079 return $template->output;
1082 sub hook (@) { # {{{
1085 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1086 error 'hook requires type, call, and id parameters';
1089 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1091 $hooks{$param{type}}{$param{id}}=\%param;
1095 sub run_hooks ($$) { # {{{
1096 # Calls the given sub for each hook of the given type,
1097 # passing it the hook function to call.
1101 if (exists $hooks{$type}) {
1103 foreach my $id (keys %{$hooks{$type}}) {
1104 if ($hooks{$type}{$id}{last}) {
1105 push @deferred, $id;
1108 $sub->($hooks{$type}{$id}{call});
1110 foreach my $id (@deferred) {
1111 $sub->($hooks{$type}{$id}{call});
1118 sub globlist_to_pagespec ($) { #{{{
1119 my @globlist=split(' ', shift);
1122 foreach my $glob (@globlist) {
1123 if ($glob=~/^!(.*)/) {
1131 my $spec=join(' or ', @spec);
1133 my $skip=join(' and ', @skip);
1135 $spec="$skip and ($spec)";
1144 sub is_globlist ($) { #{{{
1146 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1149 sub safequote ($) { #{{{
1155 sub add_depends ($$) { #{{{
1159 return unless pagespec_valid($pagespec);
1161 if (! exists $depends{$page}) {
1162 $depends{$page}=$pagespec;
1165 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1171 sub file_pruned ($$) { #{{{
1173 my $file=File::Spec->canonpath(shift);
1174 my $base=File::Spec->canonpath(shift);
1175 $file =~ s#^\Q$base\E/+##;
1177 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1178 return $file =~ m/$regexp/ && $file ne $base;
1182 # Only use gettext in the rare cases it's needed.
1183 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1184 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1185 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1186 if (! $gettext_obj) {
1187 $gettext_obj=eval q{
1188 use Locale::gettext q{textdomain};
1189 Locale::gettext->domain('ikiwiki')
1197 return $gettext_obj->get(shift);
1204 sub pagespec_merge ($$) { #{{{
1208 return $a if $a eq $b;
1210 # Support for old-style GlobLists.
1211 if (is_globlist($a)) {
1212 $a=globlist_to_pagespec($a);
1214 if (is_globlist($b)) {
1215 $b=globlist_to_pagespec($b);
1218 return "($a) or ($b)";
1221 sub pagespec_translate ($) { #{{{
1224 # Support for old-style GlobLists.
1225 if (is_globlist($spec)) {
1226 $spec=globlist_to_pagespec($spec);
1229 # Convert spec to perl code.
1232 \s* # ignore whitespace
1233 ( # 1: match a single word
1240 \w+\([^\)]*\) # command(params)
1242 [^\s()]+ # any other text
1244 \s* # ignore whitespace
1247 if (lc $word eq 'and') {
1250 elsif (lc $word eq 'or') {
1253 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1256 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1257 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1258 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1265 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1269 if (! length $code) {
1274 return eval 'sub { my $page=shift; '.$code.' }';
1277 sub pagespec_match ($$;@) { #{{{
1282 # Backwards compatability with old calling convention.
1284 unshift @params, 'location';
1287 my $sub=pagespec_translate($spec);
1288 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1289 return $sub->($page, @params);
1292 sub pagespec_valid ($) { #{{{
1295 my $sub=pagespec_translate($spec);
1299 sub glob2re ($) { #{{{
1300 my $re=quotemeta(shift);
1306 package IkiWiki::FailReason;
1309 '""' => sub { ${$_[0]} },
1311 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1318 return bless \$value, $class;
1321 package IkiWiki::SuccessReason;
1324 '""' => sub { ${$_[0]} },
1326 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1333 return bless \$value, $class;
1336 package IkiWiki::PageSpec;
1338 sub match_glob ($$;@) { #{{{
1343 my $from=exists $params{location} ? $params{location} : '';
1346 if ($glob =~ m!^\./!) {
1347 $from=~s#/?[^/]+$##;
1349 $glob="$from/$glob" if length $from;
1352 my $regexp=IkiWiki::glob2re($glob);
1353 if ($page=~/^$regexp$/i) {
1354 if (! IkiWiki::isinternal($page) || $params{internal}) {
1355 return IkiWiki::SuccessReason->new("$glob matches $page");
1358 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1362 return IkiWiki::FailReason->new("$glob does not match $page");
1366 sub match_internal ($$;@) { #{{{
1367 return match_glob($_[0], $_[1], @_, internal => 1)
1370 sub match_link ($$;@) { #{{{
1375 my $from=exists $params{location} ? $params{location} : '';
1378 if ($link =~ m!^\.! && defined $from) {
1379 $from=~s#/?[^/]+$##;
1381 $link="$from/$link" if length $from;
1384 my $links = $IkiWiki::links{$page};
1385 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1386 my $bestlink = IkiWiki::bestlink($from, $link);
1387 foreach my $p (@{$links}) {
1388 if (length $bestlink) {
1389 return IkiWiki::SuccessReason->new("$page links to $link")
1390 if $bestlink eq IkiWiki::bestlink($page, $p);
1393 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1394 if match_glob($p, $link, %params);
1397 return IkiWiki::FailReason->new("$page does not link to $link");
1400 sub match_backlink ($$;@) { #{{{
1401 return match_link($_[1], $_[0], @_);
1404 sub match_created_before ($$;@) { #{{{
1408 if (exists $IkiWiki::pagectime{$testpage}) {
1409 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1410 return IkiWiki::SuccessReason->new("$page created before $testpage");
1413 return IkiWiki::FailReason->new("$page not created before $testpage");
1417 return IkiWiki::FailReason->new("$testpage has no ctime");
1421 sub match_created_after ($$;@) { #{{{
1425 if (exists $IkiWiki::pagectime{$testpage}) {
1426 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1427 return IkiWiki::SuccessReason->new("$page created after $testpage");
1430 return IkiWiki::FailReason->new("$page not created after $testpage");
1434 return IkiWiki::FailReason->new("$testpage has no ctime");
1438 sub match_creation_day ($$;@) { #{{{
1439 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1440 return IkiWiki::SuccessReason->new('creation_day matched');
1443 return IkiWiki::FailReason->new('creation_day did not match');
1447 sub match_creation_month ($$;@) { #{{{
1448 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1449 return IkiWiki::SuccessReason->new('creation_month matched');
1452 return IkiWiki::FailReason->new('creation_month did not match');
1456 sub match_creation_year ($$;@) { #{{{
1457 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1458 return IkiWiki::SuccessReason->new('creation_year matched');
1461 return IkiWiki::FailReason->new('creation_year did not match');