8 use URI::Escape q{uri_escape_utf8};
10 use open qw{:utf8 :std};
12 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
13 %renderedfiles %oldrenderedfiles %pagesources %destsources
14 %depends %hooks %forcerebuild $gettext_obj};
16 use Exporter q{import};
17 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
18 bestlink htmllink readfile writefile pagetype srcfile pagename
19 displaytime will_render gettext urlto targetpage
20 %config %links %renderedfiles %pagesources %destsources);
21 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
22 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
23 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
28 memoize("pagespec_translate");
29 memoize("file_pruned");
31 sub defaultconfig () { #{{{
33 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
34 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
35 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
38 wiki_link_regexp => qr{
39 \[\[ # beginning of link
41 ([^\]\|]+) # 1: link text
45 ([^\s\]#]+) # 2: page to link to
47 \# # '#', beginning of anchor
48 ([^\s\]]+) # 3: anchor text
53 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
54 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
58 default_pageext => "mdwn",
79 gitorigin_branch => "origin",
80 gitmaster_branch => "master",
84 templatedir => "$installdir/share/ikiwiki/templates",
85 underlaydir => "$installdir/share/ikiwiki/basewiki",
89 plugin => [qw{mdwn inline htmlscrubber passwordauth openid signinedit
90 lockedit conditional}],
99 account_creation_password => "",
102 sub checkconfig () { #{{{
103 # locale stuff; avoid LC_ALL since it overrides everything
104 if (defined $ENV{LC_ALL}) {
105 $ENV{LANG} = $ENV{LC_ALL};
108 if (defined $config{locale}) {
109 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
110 $ENV{LANG}=$config{locale};
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 run_hooks(checkconfig => sub { shift->() });
147 sub loadplugins () { #{{{
148 if (defined $config{libdir}) {
149 unshift @INC, possibly_foolish_untaint($config{libdir});
152 loadplugin($_) foreach @{$config{plugin}};
154 run_hooks(getopt => sub { shift->() });
155 if (grep /^-/, @ARGV) {
156 print STDERR "Unknown option: $_\n"
157 foreach grep /^-/, @ARGV;
164 sub loadplugin ($) { #{{{
167 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
169 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
170 "$installdir/lib/ikiwiki") {
171 if (defined $dir && -x "$dir/plugins/$plugin") {
172 require IkiWiki::Plugin::external;
173 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
178 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
181 error("Failed to load plugin $mod: $@");
186 sub error ($;$) { #{{{
190 print "Content-type: text/html\n\n";
191 print misctemplate(gettext("Error"),
192 "<p>".gettext("Error").": $message</p>");
194 log_message('err' => $message) if $config{syslog};
195 if (defined $cleaner) {
202 return unless $config{verbose};
203 return log_message(debug => @_);
207 sub log_message ($$) { #{{{
210 if ($config{syslog}) {
213 Sys::Syslog::setlogsock('unix');
214 Sys::Syslog::openlog('ikiwiki', '', 'user');
218 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
221 elsif (! $config{cgi}) {
225 return print STDERR "@_\n";
229 sub possibly_foolish_untaint ($) { #{{{
231 my ($untainted)=$tainted=~/(.*)/s;
235 sub basename ($) { #{{{
242 sub dirname ($) { #{{{
249 sub pagetype ($) { #{{{
252 if ($page =~ /\.([^.]+)$/) {
253 return $1 if exists $hooks{htmlize}{$1};
258 sub pagename ($) { #{{{
261 my $type=pagetype($file);
263 $page=~s/\Q.$type\E*$// if defined $type;
267 sub targetpage ($$) { #{{{
271 if (! $config{usedirs} || $page =~ /^index$/ ) {
272 return $page.".".$ext;
274 return $page."/index.".$ext;
278 sub htmlpage ($) { #{{{
281 return targetpage($page, $config{htmlext});
284 sub srcfile ($) { #{{{
287 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
288 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
289 error("internal error: $file cannot be found in $config{srcdir} or $config{underlaydir}");
293 sub readfile ($;$$) { #{{{
299 error("cannot read a symlink ($file)");
303 open (my $in, "<", $file) || error("failed to read $file: $!");
304 binmode($in) if ($binary);
305 return \*$in if $wantfd;
307 close $in || error("failed to read $file: $!");
311 sub writefile ($$$;$$) { #{{{
312 my $file=shift; # can include subdirs
313 my $destdir=shift; # directory to put file in
319 while (length $test) {
320 if (-l "$destdir/$test") {
321 error("cannot write to a symlink ($test)");
323 $test=dirname($test);
325 my $newfile="$destdir/$file.ikiwiki-new";
327 error("cannot write to a symlink ($newfile)");
330 my $dir=dirname($newfile);
333 foreach my $s (split(m!/+!, $dir)) {
336 mkdir($d) || error("failed to create directory $d: $!");
341 my $cleanup = sub { unlink($newfile) };
342 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
343 binmode($out) if ($binary);
345 $writer->(\*$out, $cleanup);
348 print $out $content or error("failed writing to $newfile: $!", $cleanup);
350 close $out || error("failed saving $newfile: $!", $cleanup);
351 rename($newfile, "$destdir/$file") ||
352 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
358 sub will_render ($$;$) { #{{{
363 # Important security check.
364 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
365 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
366 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
369 if (! $clear || $cleared{$page}) {
370 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
373 foreach my $old (@{$renderedfiles{$page}}) {
374 delete $destsources{$old};
376 $renderedfiles{$page}=[$dest];
379 $destsources{$dest}=$page;
384 sub bestlink ($$) { #{{{
389 if ($link=~s/^\/+//) {
396 $l.="/" if length $l;
399 if (exists $links{$l}) {
402 elsif (exists $pagecase{lc $l}) {
403 return $pagecase{lc $l};
405 } while $cwd=~s!/?[^/]+$!!;
407 if (length $config{userdir}) {
408 my $l = "$config{userdir}/".lc($link);
409 if (exists $links{$l}) {
412 elsif (exists $pagecase{lc $l}) {
413 return $pagecase{lc $l};
417 #print STDERR "warning: page $page, broken link: $link\n";
421 sub isinlinableimage ($) { #{{{
424 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
427 sub pagetitle ($;$) { #{{{
432 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
435 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
441 sub titlepage ($) { #{{{
443 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
447 sub linkpage ($) { #{{{
449 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
453 sub cgiurl (@) { #{{{
456 return $config{cgiurl}."?".
457 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
460 sub baseurl (;$) { #{{{
463 return "$config{url}/" if ! defined $page;
465 $page=htmlpage($page);
467 $page=~s/[^\/]+\//..\//g;
471 sub abs2rel ($$) { #{{{
472 # Work around very innefficient behavior in File::Spec if abs2rel
473 # is passed two relative paths. It's much faster if paths are
474 # absolute! (Debian bug #376658; fixed in debian unstable now)
479 my $ret=File::Spec->abs2rel($path, $base);
480 $ret=~s/^// if defined $ret;
484 sub displaytime ($) { #{{{
487 # strftime doesn't know about encodings, so make sure
488 # its output is properly treated as utf8
489 return decode_utf8(POSIX::strftime(
490 $config{timeformat}, localtime($time)));
493 sub beautify_url ($) { #{{{
496 $url =~ s!/index.$config{htmlext}$!/!;
497 $url =~ s!^$!./!; # Browsers don't like empty links...
502 sub urlto ($$) { #{{{
507 return beautify_url(baseurl($from));
510 if (! $destsources{$to}) {
514 my $link = abs2rel($to, dirname(htmlpage($from)));
516 return beautify_url($link);
519 sub htmllink ($$$;@) { #{{{
520 my $lpage=shift; # the page doing the linking
521 my $page=shift; # the page that will contain the link (different for inline)
526 if (! $opts{forcesubpage}) {
527 $bestlink=bestlink($lpage, $link);
530 $bestlink="$lpage/".lc($link);
534 if (defined $opts{linktext}) {
535 $linktext=$opts{linktext};
538 $linktext=pagetitle(basename($link));
541 return "<span class=\"selflink\">$linktext</span>"
542 if length $bestlink && $page eq $bestlink;
544 if (! $destsources{$bestlink}) {
545 $bestlink=htmlpage($bestlink);
547 if (! $destsources{$bestlink}) {
548 return $linktext unless length $config{cgiurl};
549 return "<span><a href=\"".
552 page => pagetitle(lc($link), 1),
555 "\">?</a>$linktext</span>"
559 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
560 $bestlink=beautify_url($bestlink);
562 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
563 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
566 if (defined $opts{anchor}) {
567 $bestlink.="#".$opts{anchor};
571 if (defined $opts{rel}) {
572 push @attrs, ' rel="'.$opts{rel}.'"';
575 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
578 sub htmlize ($$$) { #{{{
583 if (exists $hooks{htmlize}{$type}) {
584 $content=$hooks{htmlize}{$type}{call}->(
590 error("htmlization of $type not supported");
593 run_hooks(sanitize => sub {
603 sub linkify ($$$) { #{{{
604 my $lpage=shift; # the page containing the links
605 my $page=shift; # the page the link will end up on (different for inline)
608 $content =~ s{(\\?)$config{wiki_link_regexp}}{
611 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
612 : htmllink($lpage, $page, linkpage($3),
613 anchor => $4, linktext => pagetitle($2)))
615 ? "[[$3".($4 ? "#$4" : "")."]]"
616 : htmllink($lpage, $page, linkpage($3),
624 our $preprocess_preview=0;
625 sub preprocess ($$$;$$) { #{{{
626 my $page=shift; # the page the data comes from
627 my $destpage=shift; # the page the data will appear in (different for inline)
632 # Using local because it needs to be set within any nested calls
634 local $preprocess_preview=$preview if defined $preview;
640 if (length $escape) {
641 return "[[$command $params]]";
643 elsif (exists $hooks{preprocess}{$command}) {
644 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
645 # Note: preserve order of params, some plugins may
646 # consider it significant.
649 (?:(\w+)=)? # 1: named parameter key?
651 """(.*?)""" # 2: triple-quoted value
653 "([^"]+)" # 3: single-quoted value
655 (\S+) # 4: unquoted value
657 (?:\s+|$) # delimiter to next param
675 push @params, $key, $val;
678 push @params, $val, '';
681 if ($preprocessing{$page}++ > 3) {
682 # Avoid loops of preprocessed pages preprocessing
683 # other pages that preprocess them, etc.
684 #translators: The first parameter is a
685 #translators: preprocessor directive name,
686 #translators: the second a page name, the
687 #translators: third a number.
688 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
689 $command, $page, $preprocessing{$page}).
692 my $ret=$hooks{preprocess}{$command}{call}->(
695 destpage => $destpage,
696 preview => $preprocess_preview,
698 $preprocessing{$page}--;
702 return "[[$command $params]]";
708 \[\[ # directive open
711 ( # 3: the parameters..
713 (?:\w+=)? # named parameter key?
715 """.*?""" # triple-quoted value
717 "[^"]+" # single-quoted value
719 [^\s\]]+ # unquoted value
721 \s* # whitespace or end
724 *) # 0 or more parameters
725 \]\] # directive closed
726 }{$handle->($1, $2, $3)}sexg;
730 sub filter ($$$) { #{{{
735 run_hooks(filter => sub {
736 $content=shift->(page => $page, destpage => $destpage,
737 content => $content);
743 sub indexlink () { #{{{
744 return "<a href=\"$config{url}\">$config{wikiname}</a>";
749 sub lockwiki (;$) { #{{{
750 my $wait=@_ ? shift : 1;
751 # Take an exclusive lock on the wiki to prevent multiple concurrent
752 # run issues. The lock will be dropped on program exit.
753 if (! -d $config{wikistatedir}) {
754 mkdir($config{wikistatedir});
756 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
757 error ("cannot write to $config{wikistatedir}/lockfile: $!");
758 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
760 debug("wiki seems to be locked, waiting for lock");
761 my $wait=600; # arbitrary, but don't hang forever to
762 # prevent process pileup
764 return if flock($wikilock, 2 | 4);
767 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
776 sub unlockwiki () { #{{{
777 return close($wikilock) if $wikilock;
783 sub commit_hook_enabled () { #{{{
784 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
785 error("cannot write to $config{wikistatedir}/commitlock: $!");
786 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
787 close($commitlock) || error("failed closing commitlock: $!");
790 close($commitlock) || error("failed closing commitlock: $!");
794 sub disable_commit_hook () { #{{{
795 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
796 error("cannot write to $config{wikistatedir}/commitlock: $!");
797 if (! flock($commitlock, 2)) { # LOCK_EX
798 error("failed to get commit lock");
803 sub enable_commit_hook () { #{{{
804 return close($commitlock) if $commitlock;
808 sub loadindex () { #{{{
809 open (my $in, "<", "$config{wikistatedir}/index") || return;
811 $_=possibly_foolish_untaint($_);
816 foreach my $i (split(/ /, $_)) {
817 my ($item, $val)=split(/=/, $i, 2);
818 push @{$items{$item}}, decode_entities($val);
821 next unless exists $items{src}; # skip bad lines for now
823 my $page=pagename($items{src}[0]);
824 if (! $config{rebuild}) {
825 $pagesources{$page}=$items{src}[0];
826 $pagemtime{$page}=$items{mtime}[0];
827 $oldlinks{$page}=[@{$items{link}}];
828 $links{$page}=[@{$items{link}}];
829 $depends{$page}=$items{depends}[0] if exists $items{depends};
830 $destsources{$_}=$page foreach @{$items{dest}};
831 $renderedfiles{$page}=[@{$items{dest}}];
832 $pagecase{lc $page}=$page;
834 $oldrenderedfiles{$page}=[@{$items{dest}}];
835 $pagectime{$page}=$items{ctime}[0];
840 sub saveindex () { #{{{
841 run_hooks(savestate => sub { shift->() });
843 if (! -d $config{wikistatedir}) {
844 mkdir($config{wikistatedir});
846 my $newfile="$config{wikistatedir}/index.new";
847 my $cleanup = sub { unlink($newfile) };
848 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
849 foreach my $page (keys %pagemtime) {
850 next unless $pagemtime{$page};
851 my $line="mtime=$pagemtime{$page} ".
852 "ctime=$pagectime{$page} ".
853 "src=$pagesources{$page}";
854 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
856 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
857 if (exists $depends{$page}) {
858 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
860 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
862 close $out || error("failed saving to $newfile: $!", $cleanup);
863 rename($newfile, "$config{wikistatedir}/index") ||
864 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
869 sub template_file ($) { #{{{
872 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
873 return "$dir/$template" if -e "$dir/$template";
878 sub template_params (@) { #{{{
879 my $filename=template_file(shift);
881 if (! defined $filename) {
888 my $text_ref = shift;
889 ${$text_ref} = Encode::decode_utf8(${$text_ref});
891 filename => $filename,
892 loop_context_vars => 1,
893 die_on_bad_params => 0,
896 return wantarray ? @ret : {@ret};
899 sub template ($;@) { #{{{
900 require HTML::Template;
901 return HTML::Template->new(template_params(@_));
904 sub misctemplate ($$;@) { #{{{
908 my $template=template("misc.tmpl");
911 indexlink => indexlink(),
912 wikiname => $config{wikiname},
913 pagebody => $pagebody,
914 baseurl => baseurl(),
917 run_hooks(pagetemplate => sub {
918 shift->(page => "", destpage => "", template => $template);
920 return $template->output;
926 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
927 error 'hook requires type, call, and id parameters';
930 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
932 $hooks{$param{type}}{$param{id}}=\%param;
936 sub run_hooks ($$) { # {{{
937 # Calls the given sub for each hook of the given type,
938 # passing it the hook function to call.
942 if (exists $hooks{$type}) {
944 foreach my $id (keys %{$hooks{$type}}) {
945 if ($hooks{$type}{$id}{last}) {
949 $sub->($hooks{$type}{$id}{call});
951 foreach my $id (@deferred) {
952 $sub->($hooks{$type}{$id}{call});
959 sub globlist_to_pagespec ($) { #{{{
960 my @globlist=split(' ', shift);
963 foreach my $glob (@globlist) {
964 if ($glob=~/^!(.*)/) {
972 my $spec=join(' or ', @spec);
974 my $skip=join(' and ', @skip);
976 $spec="$skip and ($spec)";
985 sub is_globlist ($) { #{{{
987 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
990 sub safequote ($) { #{{{
996 sub add_depends ($$) { #{{{
1000 if (! exists $depends{$page}) {
1001 $depends{$page}=$pagespec;
1004 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1010 sub file_pruned ($$) { #{{{
1012 my $file=File::Spec->canonpath(shift);
1013 my $base=File::Spec->canonpath(shift);
1014 $file =~ s#^\Q$base\E/*##;
1016 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1017 return $file =~ m/$regexp/;
1021 # Only use gettext in the rare cases it's needed.
1022 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1023 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1024 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1025 if (! $gettext_obj) {
1026 $gettext_obj=eval q{
1027 use Locale::gettext q{textdomain};
1028 Locale::gettext->domain('ikiwiki')
1036 return $gettext_obj->get(shift);
1043 sub pagespec_merge ($$) { #{{{
1047 return $a if $a eq $b;
1049 # Support for old-style GlobLists.
1050 if (is_globlist($a)) {
1051 $a=globlist_to_pagespec($a);
1053 if (is_globlist($b)) {
1054 $b=globlist_to_pagespec($b);
1057 return "($a) or ($b)";
1060 sub pagespec_translate ($) { #{{{
1061 # This assumes that $page is in scope in the function
1062 # that evalulates the translated pagespec code.
1065 # Support for old-style GlobLists.
1066 if (is_globlist($spec)) {
1067 $spec=globlist_to_pagespec($spec);
1070 # Convert spec to perl code.
1073 \s* # ignore whitespace
1074 ( # 1: match a single word
1081 \w+\([^\)]*\) # command(params)
1083 [^\s()]+ # any other text
1085 \s* # ignore whitespace
1088 if (lc $word eq 'and') {
1091 elsif (lc $word eq 'or') {
1094 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1097 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1098 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1099 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1106 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1113 sub pagespec_match ($$;@) { #{{{
1118 # Backwards compatability with old calling convention.
1120 unshift @params, 'location';
1123 my $ret=eval pagespec_translate($spec);
1124 return IkiWiki::FailReason->new('syntax error') if $@;
1128 package IkiWiki::FailReason;
1131 '""' => sub { ${$_[0]} },
1133 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1138 return bless \$_[1], $_[0];
1141 package IkiWiki::SuccessReason;
1144 '""' => sub { ${$_[0]} },
1146 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1151 return bless \$_[1], $_[0];
1154 package IkiWiki::PageSpec;
1156 sub match_glob ($$;@) { #{{{
1161 my $from=exists $params{location} ? $params{location} : '';
1164 if ($glob =~ m!^\./!) {
1165 $from=~s#/?[^/]+$##;
1167 $glob="$from/$glob" if length $from;
1170 # turn glob into safe regexp
1171 $glob=quotemeta($glob);
1175 if ($page=~/^$glob$/i) {
1176 return IkiWiki::SuccessReason->new("$glob matches $page");
1179 return IkiWiki::FailReason->new("$glob does not match $page");
1183 sub match_link ($$;@) { #{{{
1188 my $from=exists $params{location} ? $params{location} : '';
1191 if ($link =~ m!^\.! && defined $from) {
1192 $from=~s#/?[^/]+$##;
1194 $link="$from/$link" if length $from;
1197 my $links = $IkiWiki::links{$page};
1198 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1199 my $bestlink = IkiWiki::bestlink($from, $link);
1200 foreach my $p (@{$links}) {
1201 if (length $bestlink) {
1202 return IkiWiki::SuccessReason->new("$page links to $link")
1203 if $bestlink eq IkiWiki::bestlink($page, $p);
1206 return IkiWiki::SuccessReason->new("$page links to page matching $link")
1207 if match_glob($p, $link, %params);
1210 return IkiWiki::FailReason->new("$page does not link to $link");
1213 sub match_backlink ($$;@) { #{{{
1214 return match_link($_[1], $_[0], @_);
1217 sub match_created_before ($$;@) { #{{{
1221 if (exists $IkiWiki::pagectime{$testpage}) {
1222 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1223 return IkiWiki::SuccessReason->new("$page created before $testpage");
1226 return IkiWiki::FailReason->new("$page not created before $testpage");
1230 return IkiWiki::FailReason->new("$testpage has no ctime");
1234 sub match_created_after ($$;@) { #{{{
1238 if (exists $IkiWiki::pagectime{$testpage}) {
1239 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1240 return IkiWiki::SuccessReason->new("$page created after $testpage");
1243 return IkiWiki::FailReason->new("$page not created after $testpage");
1247 return IkiWiki::FailReason->new("$testpage has no ctime");
1251 sub match_creation_day ($$;@) { #{{{
1252 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1253 return IkiWiki::SuccessReason->new('creation_day matched');
1256 return IkiWiki::FailReason->new('creation_day did not match');
1260 sub match_creation_month ($$;@) { #{{{
1261 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1262 return IkiWiki::SuccessReason->new('creation_month matched');
1265 return IkiWiki::FailReason->new('creation_month did not match');
1269 sub match_creation_year ($$;@) { #{{{
1270 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1271 return IkiWiki::SuccessReason->new('creation_year matched');
1274 return IkiWiki::FailReason->new('creation_year did not match');
1278 sub match_user ($$;@) { #{{{
1283 return IkiWiki::FailReason->new('cannot match user')
1284 unless exists $params{user};
1285 if ($user eq $params{user}) {
1286 return IkiWiki::SuccessReason->new("user is $user")
1289 return IkiWiki::FailReason->new("user is not $user");