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 close $in || error("failed to read $file: $!");
341 sub prep_writefile ($$) {
346 while (length $test) {
347 if (-l "$destdir/$test") {
348 error("cannot write to a symlink ($test)");
350 $test=dirname($test);
353 my $dir=dirname("$destdir/$file");
356 foreach my $s (split(m!/+!, $dir)) {
359 mkdir($d) || error("failed to create directory $d: $!");
367 sub writefile ($$$;$$) { #{{{
368 my $file=shift; # can include subdirs
369 my $destdir=shift; # directory to put file in
374 prep_writefile($file, $destdir);
376 my $newfile="$destdir/$file.ikiwiki-new";
378 error("cannot write to a symlink ($newfile)");
381 my $cleanup = sub { unlink($newfile) };
382 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
383 binmode($out) if ($binary);
385 $writer->(\*$out, $cleanup);
388 print $out $content or error("failed writing to $newfile: $!", $cleanup);
390 close $out || error("failed saving $newfile: $!", $cleanup);
391 rename($newfile, "$destdir/$file") ||
392 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
398 sub will_render ($$;$) { #{{{
403 # Important security check.
404 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
405 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
406 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
409 if (! $clear || $cleared{$page}) {
410 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
413 foreach my $old (@{$renderedfiles{$page}}) {
414 delete $destsources{$old};
416 $renderedfiles{$page}=[$dest];
419 $destsources{$dest}=$page;
424 sub bestlink ($$) { #{{{
429 if ($link=~s/^\/+//) {
437 $l.="/" if length $l;
440 if (exists $links{$l}) {
443 elsif (exists $pagecase{lc $l}) {
444 return $pagecase{lc $l};
446 } while $cwd=~s!/?[^/]+$!!;
448 if (length $config{userdir}) {
449 my $l = "$config{userdir}/".lc($link);
450 if (exists $links{$l}) {
453 elsif (exists $pagecase{lc $l}) {
454 return $pagecase{lc $l};
458 #print STDERR "warning: page $page, broken link: $link\n";
462 sub isinlinableimage ($) { #{{{
465 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
468 sub pagetitle ($;$) { #{{{
473 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
476 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
482 sub titlepage ($) { #{{{
484 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
488 sub linkpage ($) { #{{{
490 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
494 sub cgiurl (@) { #{{{
497 return $config{cgiurl}."?".
498 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
501 sub baseurl (;$) { #{{{
504 return "$config{url}/" if ! defined $page;
506 $page=htmlpage($page);
508 $page=~s/[^\/]+\//..\//g;
512 sub abs2rel ($$) { #{{{
513 # Work around very innefficient behavior in File::Spec if abs2rel
514 # is passed two relative paths. It's much faster if paths are
515 # absolute! (Debian bug #376658; fixed in debian unstable now)
520 my $ret=File::Spec->abs2rel($path, $base);
521 $ret=~s/^// if defined $ret;
525 sub displaytime ($;$) { #{{{
528 if (! defined $format) {
529 $format=$config{timeformat};
532 # strftime doesn't know about encodings, so make sure
533 # its output is properly treated as utf8
534 return decode_utf8(POSIX::strftime($format, localtime($time)));
537 sub beautify_url ($) { #{{{
540 if ($config{usedirs}) {
541 $url =~ s!/index.$config{htmlext}$!/!;
544 # Ensure url is not an empty link, and
545 # if it's relative, make that explicit to avoid colon confusion.
553 sub urlto ($$;$) { #{{{
559 return beautify_url(baseurl($from)."index.$config{htmlext}");
562 if (! $destsources{$to}) {
567 return $config{url}.beautify_urlpath("/".$to);
570 my $link = abs2rel($to, dirname(htmlpage($from)));
572 return beautify_url($link);
575 sub htmllink ($$$;@) { #{{{
576 my $lpage=shift; # the page doing the linking
577 my $page=shift; # the page that will contain the link (different for inline)
584 if (! $opts{forcesubpage}) {
585 $bestlink=bestlink($lpage, $link);
588 $bestlink="$lpage/".lc($link);
592 if (defined $opts{linktext}) {
593 $linktext=$opts{linktext};
596 $linktext=pagetitle(basename($link));
599 return "<span class=\"selflink\">$linktext</span>"
600 if length $bestlink && $page eq $bestlink &&
601 ! defined $opts{anchor};
603 if (! $destsources{$bestlink}) {
604 $bestlink=htmlpage($bestlink);
606 if (! $destsources{$bestlink}) {
607 return $linktext unless length $config{cgiurl};
608 return "<span class=\"createlink\"><a href=\"".
614 "\" rel=\"nofollow\">?</a>$linktext</span>"
618 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
619 $bestlink=beautify_url($bestlink);
621 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
622 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
625 if (defined $opts{anchor}) {
626 $bestlink.="#".$opts{anchor};
630 if (defined $opts{rel}) {
631 push @attrs, ' rel="'.$opts{rel}.'"';
633 if (defined $opts{class}) {
634 push @attrs, ' class="'.$opts{class}.'"';
637 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
640 sub userlink ($) { #{{{
643 my $oiduser=eval { openiduser($user) };
644 if (defined $oiduser) {
645 return "<a href=\"$user\">$oiduser</a>";
648 eval q{use CGI 'escapeHTML'};
651 return htmllink("", "", escapeHTML(
652 length $config{userdir} ? $config{userdir}."/".$user : $user
653 ), noimageinline => 1);
657 sub htmlize ($$$$) { #{{{
663 my $oneline = $content !~ /\n/;
665 if (exists $hooks{htmlize}{$type}) {
666 $content=$hooks{htmlize}{$type}{call}->(
672 error("htmlization of $type not supported");
675 run_hooks(sanitize => sub {
678 destpage => $destpage,
684 # hack to get rid of enclosing junk added by markdown
685 # and other htmlizers
687 $content=~s/<\/p>$//i;
694 sub linkify ($$$) { #{{{
699 run_hooks(linkify => sub {
702 destpage => $destpage,
711 our $preprocess_preview=0;
712 sub preprocess ($$$;$$) { #{{{
713 my $page=shift; # the page the data comes from
714 my $destpage=shift; # the page the data will appear in (different for inline)
719 # Using local because it needs to be set within any nested calls
721 local $preprocess_preview=$preview if defined $preview;
728 $params="" if ! defined $params;
731 return "[[$prefix$command $params]]";
733 elsif (exists $hooks{preprocess}{$command}) {
734 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
735 # Note: preserve order of params, some plugins may
736 # consider it significant.
739 (?:([-\w]+)=)? # 1: named parameter key?
741 """(.*?)""" # 2: triple-quoted value
743 "([^"]+)" # 3: single-quoted value
745 (\S+) # 4: unquoted value
747 (?:\s+|$) # delimiter to next param
765 push @params, $key, $val;
768 push @params, $val, '';
771 if ($preprocessing{$page}++ > 3) {
772 # Avoid loops of preprocessed pages preprocessing
773 # other pages that preprocess them, etc.
774 #translators: The first parameter is a
775 #translators: preprocessor directive name,
776 #translators: the second a page name, the
777 #translators: third a number.
778 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
779 $command, $page, $preprocessing{$page}).
784 $ret=$hooks{preprocess}{$command}{call}->(
787 destpage => $destpage,
788 preview => $preprocess_preview,
792 # use void context during scan pass
793 $hooks{preprocess}{$command}{call}->(
796 destpage => $destpage,
797 preview => $preprocess_preview,
801 $preprocessing{$page}--;
805 return "[[$prefix$command $params]]";
810 if ($config{prefix_directives}) {
813 \[\[(!) # directive open; 2: prefix
814 ([-\w]+) # 3: command
815 ( # 4: the parameters..
816 \s+ # Must have space if parameters present
818 (?:[-\w]+=)? # named parameter key?
820 """.*?""" # triple-quoted value
822 "[^"]+" # single-quoted value
824 [^\s\]]+ # unquoted value
826 \s* # whitespace or end
829 *)? # 0 or more parameters
830 \]\] # directive closed
835 \[\[(!?) # directive open; 2: optional prefix
836 ([-\w]+) # 3: command
838 ( # 4: the parameters..
840 (?:[-\w]+=)? # named parameter key?
842 """.*?""" # triple-quoted value
844 "[^"]+" # single-quoted value
846 [^\s\]]+ # unquoted value
848 \s* # whitespace or end
851 *) # 0 or more parameters
852 \]\] # directive closed
856 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
860 sub filter ($$$) { #{{{
865 run_hooks(filter => sub {
866 $content=shift->(page => $page, destpage => $destpage,
867 content => $content);
873 sub indexlink () { #{{{
874 return "<a href=\"$config{url}\">$config{wikiname}</a>";
879 sub lockwiki (;$) { #{{{
880 my $wait=@_ ? shift : 1;
881 # Take an exclusive lock on the wiki to prevent multiple concurrent
882 # run issues. The lock will be dropped on program exit.
883 if (! -d $config{wikistatedir}) {
884 mkdir($config{wikistatedir});
886 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
887 error ("cannot write to $config{wikistatedir}/lockfile: $!");
888 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
890 debug("wiki seems to be locked, waiting for lock");
891 my $wait=600; # arbitrary, but don't hang forever to
892 # prevent process pileup
894 return if flock($wikilock, 2 | 4);
897 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
906 sub unlockwiki () { #{{{
907 return close($wikilock) if $wikilock;
913 sub commit_hook_enabled () { #{{{
914 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
915 error("cannot write to $config{wikistatedir}/commitlock: $!");
916 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
917 close($commitlock) || error("failed closing commitlock: $!");
920 close($commitlock) || error("failed closing commitlock: $!");
924 sub disable_commit_hook () { #{{{
925 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
926 error("cannot write to $config{wikistatedir}/commitlock: $!");
927 if (! flock($commitlock, 2)) { # LOCK_EX
928 error("failed to get commit lock");
933 sub enable_commit_hook () { #{{{
934 return close($commitlock) if $commitlock;
938 sub loadindex () { #{{{
939 %oldrenderedfiles=%pagectime=();
940 if (! $config{rebuild}) {
941 %pagesources=%pagemtime=%oldlinks=%links=%depends=
942 %destsources=%renderedfiles=%pagecase=%pagestate=();
945 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
946 if (-e "$config{wikistatedir}/index") {
947 system("ikiwiki-transition", "indexdb", $config{srcdir});
948 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
954 my $ret=Storable::fd_retrieve($in);
955 if (! defined $ret) {
959 foreach my $src (keys %index) {
960 my %d=%{$index{$src}};
961 my $page=pagename($src);
962 $pagectime{$page}=$d{ctime};
963 if (! $config{rebuild}) {
964 $pagesources{$page}=$src;
965 $pagemtime{$page}=$d{mtime};
966 $renderedfiles{$page}=$d{dest};
967 if (exists $d{links} && ref $d{links}) {
968 $links{$page}=$d{links};
969 $oldlinks{$page}=[@{$d{links}}];
971 if (exists $d{depends}) {
972 $depends{$page}=$d{depends};
974 if (exists $d{state}) {
975 $pagestate{$page}=$d{state};
978 $oldrenderedfiles{$page}=[@{$d{dest}}];
980 foreach my $page (keys %pagesources) {
981 $pagecase{lc $page}=$page;
983 foreach my $page (keys %renderedfiles) {
984 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
989 sub saveindex () { #{{{
990 run_hooks(savestate => sub { shift->() });
993 foreach my $type (keys %hooks) {
994 $hookids{$_}=1 foreach keys %{$hooks{$type}};
996 my @hookids=keys %hookids;
998 if (! -d $config{wikistatedir}) {
999 mkdir($config{wikistatedir});
1001 my $newfile="$config{wikistatedir}/indexdb.new";
1002 my $cleanup = sub { unlink($newfile) };
1003 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1005 foreach my $page (keys %pagemtime) {
1006 next unless $pagemtime{$page};
1007 my $src=$pagesources{$page};
1010 ctime => $pagectime{$page},
1011 mtime => $pagemtime{$page},
1012 dest => $renderedfiles{$page},
1013 links => $links{$page},
1016 if (exists $depends{$page}) {
1017 $index{$src}{depends} = $depends{$page};
1020 if (exists $pagestate{$page}) {
1021 foreach my $id (@hookids) {
1022 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1023 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1028 my $ret=Storable::nstore_fd(\%index, $out);
1029 return if ! defined $ret || ! $ret;
1030 close $out || error("failed saving to $newfile: $!", $cleanup);
1031 rename($newfile, "$config{wikistatedir}/indexdb") ||
1032 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1037 sub template_file ($) { #{{{
1040 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1041 return "$dir/$template" if -e "$dir/$template";
1046 sub template_params (@) { #{{{
1047 my $filename=template_file(shift);
1049 if (! defined $filename) {
1050 return if wantarray;
1056 my $text_ref = shift;
1057 ${$text_ref} = decode_utf8(${$text_ref});
1059 filename => $filename,
1060 loop_context_vars => 1,
1061 die_on_bad_params => 0,
1064 return wantarray ? @ret : {@ret};
1067 sub template ($;@) { #{{{
1068 require HTML::Template;
1069 return HTML::Template->new(template_params(@_));
1072 sub misctemplate ($$;@) { #{{{
1076 my $template=template("misc.tmpl");
1079 indexlink => indexlink(),
1080 wikiname => $config{wikiname},
1081 pagebody => $pagebody,
1082 baseurl => baseurl(),
1085 run_hooks(pagetemplate => sub {
1086 shift->(page => "", destpage => "", template => $template);
1088 return $template->output;
1091 sub hook (@) { # {{{
1094 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1095 error 'hook requires type, call, and id parameters';
1098 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1100 $hooks{$param{type}}{$param{id}}=\%param;
1104 sub run_hooks ($$) { # {{{
1105 # Calls the given sub for each hook of the given type,
1106 # passing it the hook function to call.
1110 if (exists $hooks{$type}) {
1112 foreach my $id (keys %{$hooks{$type}}) {
1113 if ($hooks{$type}{$id}{last}) {
1114 push @deferred, $id;
1117 $sub->($hooks{$type}{$id}{call});
1119 foreach my $id (@deferred) {
1120 $sub->($hooks{$type}{$id}{call});
1127 sub globlist_to_pagespec ($) { #{{{
1128 my @globlist=split(' ', shift);
1131 foreach my $glob (@globlist) {
1132 if ($glob=~/^!(.*)/) {
1140 my $spec=join(' or ', @spec);
1142 my $skip=join(' and ', @skip);
1144 $spec="$skip and ($spec)";
1153 sub is_globlist ($) { #{{{
1155 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1158 sub safequote ($) { #{{{
1164 sub add_depends ($$) { #{{{
1168 return unless pagespec_valid($pagespec);
1170 if (! exists $depends{$page}) {
1171 $depends{$page}=$pagespec;
1174 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1180 sub file_pruned ($$) { #{{{
1182 my $file=File::Spec->canonpath(shift);
1183 my $base=File::Spec->canonpath(shift);
1184 $file =~ s#^\Q$base\E/+##;
1186 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1187 return $file =~ m/$regexp/ && $file ne $base;
1191 # Only use gettext in the rare cases it's needed.
1192 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1193 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1194 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1195 if (! $gettext_obj) {
1196 $gettext_obj=eval q{
1197 use Locale::gettext q{textdomain};
1198 Locale::gettext->domain('ikiwiki')
1206 return $gettext_obj->get(shift);
1213 sub pagespec_merge ($$) { #{{{
1217 return $a if $a eq $b;
1219 # Support for old-style GlobLists.
1220 if (is_globlist($a)) {
1221 $a=globlist_to_pagespec($a);
1223 if (is_globlist($b)) {
1224 $b=globlist_to_pagespec($b);
1227 return "($a) or ($b)";
1230 sub pagespec_translate ($) { #{{{
1233 # Support for old-style GlobLists.
1234 if (is_globlist($spec)) {
1235 $spec=globlist_to_pagespec($spec);
1238 # Convert spec to perl code.
1241 \s* # ignore whitespace
1242 ( # 1: match a single word
1249 \w+\([^\)]*\) # command(params)
1251 [^\s()]+ # any other text
1253 \s* # ignore whitespace
1256 if (lc $word eq 'and') {
1259 elsif (lc $word eq 'or') {
1262 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1265 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1266 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1267 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1274 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1278 if (! length $code) {
1283 return eval 'sub { my $page=shift; '.$code.' }';
1286 sub pagespec_match ($$;@) { #{{{
1291 # Backwards compatability with old calling convention.
1293 unshift @params, 'location';
1296 my $sub=pagespec_translate($spec);
1297 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1298 return $sub->($page, @params);
1301 sub pagespec_valid ($) { #{{{
1304 my $sub=pagespec_translate($spec);
1308 sub glob2re ($) { #{{{
1309 my $re=quotemeta(shift);
1315 package IkiWiki::FailReason;
1318 '""' => sub { ${$_[0]} },
1320 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1327 return bless \$value, $class;
1330 package IkiWiki::SuccessReason;
1333 '""' => sub { ${$_[0]} },
1335 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1342 return bless \$value, $class;
1345 package IkiWiki::PageSpec;
1347 sub match_glob ($$;@) { #{{{
1352 my $from=exists $params{location} ? $params{location} : '';
1355 if ($glob =~ m!^\./!) {
1356 $from=~s#/?[^/]+$##;
1358 $glob="$from/$glob" if length $from;
1361 my $regexp=IkiWiki::glob2re($glob);
1362 if ($page=~/^$regexp$/i) {
1363 if (! IkiWiki::isinternal($page) || $params{internal}) {
1364 return IkiWiki::SuccessReason->new("$glob matches $page");
1367 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1371 return IkiWiki::FailReason->new("$glob does not match $page");
1375 sub match_internal ($$;@) { #{{{
1376 return match_glob($_[0], $_[1], @_, internal => 1)
1379 sub match_link ($$;@) { #{{{
1384 my $from=exists $params{location} ? $params{location} : '';
1387 if ($link =~ m!^\.! && defined $from) {
1388 $from=~s#/?[^/]+$##;
1390 $link="$from/$link" if length $from;
1393 my $links = $IkiWiki::links{$page};
1394 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1395 my $bestlink = IkiWiki::bestlink($from, $link);
1396 foreach my $p (@{$links}) {
1397 if (length $bestlink) {
1398 return IkiWiki::SuccessReason->new("$page links to $link")
1399 if $bestlink eq IkiWiki::bestlink($page, $p);
1402 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1403 if match_glob($p, $link, %params);
1406 return IkiWiki::FailReason->new("$page does not link to $link");
1409 sub match_backlink ($$;@) { #{{{
1410 return match_link($_[1], $_[0], @_);
1413 sub match_created_before ($$;@) { #{{{
1417 if (exists $IkiWiki::pagectime{$testpage}) {
1418 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1419 return IkiWiki::SuccessReason->new("$page created before $testpage");
1422 return IkiWiki::FailReason->new("$page not created before $testpage");
1426 return IkiWiki::FailReason->new("$testpage has no ctime");
1430 sub match_created_after ($$;@) { #{{{
1434 if (exists $IkiWiki::pagectime{$testpage}) {
1435 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1436 return IkiWiki::SuccessReason->new("$page created after $testpage");
1439 return IkiWiki::FailReason->new("$page not created after $testpage");
1443 return IkiWiki::FailReason->new("$testpage has no ctime");
1447 sub match_creation_day ($$;@) { #{{{
1448 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1449 return IkiWiki::SuccessReason->new('creation_day matched');
1452 return IkiWiki::FailReason->new('creation_day did not match');
1456 sub match_creation_month ($$;@) { #{{{
1457 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1458 return IkiWiki::SuccessReason->new('creation_month matched');
1461 return IkiWiki::FailReason->new('creation_month did not match');
1465 sub match_creation_year ($$;@) { #{{{
1466 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1467 return IkiWiki::SuccessReason->new('creation_year matched');
1470 return IkiWiki::FailReason->new('creation_year did not match');