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);
782 sub commit_hook_enabled () { #{{{
783 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
784 error("cannot write to $config{wikistatedir}/commitlock: $!");
785 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
786 close($commitlock) || error("failed closing commitlock: $!");
789 close($commitlock) || error("failed closing commitlock: $!");
793 sub disable_commit_hook () { #{{{
794 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
795 error("cannot write to $config{wikistatedir}/commitlock: $!");
796 if (! flock($commitlock, 2)) { # LOCK_EX
797 error("failed to get commit lock");
802 sub enable_commit_hook () { #{{{
803 return close($commitlock);
806 sub loadindex () { #{{{
807 open (my $in, "<", "$config{wikistatedir}/index") || return;
809 $_=possibly_foolish_untaint($_);
814 foreach my $i (split(/ /, $_)) {
815 my ($item, $val)=split(/=/, $i, 2);
816 push @{$items{$item}}, decode_entities($val);
819 next unless exists $items{src}; # skip bad lines for now
821 my $page=pagename($items{src}[0]);
822 if (! $config{rebuild}) {
823 $pagesources{$page}=$items{src}[0];
824 $pagemtime{$page}=$items{mtime}[0];
825 $oldlinks{$page}=[@{$items{link}}];
826 $links{$page}=[@{$items{link}}];
827 $depends{$page}=$items{depends}[0] if exists $items{depends};
828 $destsources{$_}=$page foreach @{$items{dest}};
829 $renderedfiles{$page}=[@{$items{dest}}];
830 $pagecase{lc $page}=$page;
832 $oldrenderedfiles{$page}=[@{$items{dest}}];
833 $pagectime{$page}=$items{ctime}[0];
838 sub saveindex () { #{{{
839 run_hooks(savestate => sub { shift->() });
841 if (! -d $config{wikistatedir}) {
842 mkdir($config{wikistatedir});
844 my $newfile="$config{wikistatedir}/index.new";
845 my $cleanup = sub { unlink($newfile) };
846 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
847 foreach my $page (keys %pagemtime) {
848 next unless $pagemtime{$page};
849 my $line="mtime=$pagemtime{$page} ".
850 "ctime=$pagectime{$page} ".
851 "src=$pagesources{$page}";
852 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
854 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
855 if (exists $depends{$page}) {
856 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
858 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
860 close $out || error("failed saving to $newfile: $!", $cleanup);
861 rename($newfile, "$config{wikistatedir}/index") ||
862 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
867 sub template_file ($) { #{{{
870 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
871 return "$dir/$template" if -e "$dir/$template";
876 sub template_params (@) { #{{{
877 my $filename=template_file(shift);
879 if (! defined $filename) {
886 my $text_ref = shift;
887 ${$text_ref} = Encode::decode_utf8(${$text_ref});
889 filename => $filename,
890 loop_context_vars => 1,
891 die_on_bad_params => 0,
894 return wantarray ? @ret : {@ret};
897 sub template ($;@) { #{{{
898 require HTML::Template;
899 return HTML::Template->new(template_params(@_));
902 sub misctemplate ($$;@) { #{{{
906 my $template=template("misc.tmpl");
909 indexlink => indexlink(),
910 wikiname => $config{wikiname},
911 pagebody => $pagebody,
912 baseurl => baseurl(),
915 run_hooks(pagetemplate => sub {
916 shift->(page => "", destpage => "", template => $template);
918 return $template->output;
924 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
925 error 'hook requires type, call, and id parameters';
928 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
930 $hooks{$param{type}}{$param{id}}=\%param;
934 sub run_hooks ($$) { # {{{
935 # Calls the given sub for each hook of the given type,
936 # passing it the hook function to call.
940 if (exists $hooks{$type}) {
942 foreach my $id (keys %{$hooks{$type}}) {
943 if ($hooks{$type}{$id}{last}) {
947 $sub->($hooks{$type}{$id}{call});
949 foreach my $id (@deferred) {
950 $sub->($hooks{$type}{$id}{call});
957 sub globlist_to_pagespec ($) { #{{{
958 my @globlist=split(' ', shift);
961 foreach my $glob (@globlist) {
962 if ($glob=~/^!(.*)/) {
970 my $spec=join(' or ', @spec);
972 my $skip=join(' and ', @skip);
974 $spec="$skip and ($spec)";
983 sub is_globlist ($) { #{{{
985 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
988 sub safequote ($) { #{{{
994 sub add_depends ($$) { #{{{
998 if (! exists $depends{$page}) {
999 $depends{$page}=$pagespec;
1002 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1008 sub file_pruned ($$) { #{{{
1010 my $file=File::Spec->canonpath(shift);
1011 my $base=File::Spec->canonpath(shift);
1012 $file =~ s#^\Q$base\E/*##;
1014 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1015 return $file =~ m/$regexp/;
1019 # Only use gettext in the rare cases it's needed.
1020 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1021 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1022 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1023 if (! $gettext_obj) {
1024 $gettext_obj=eval q{
1025 use Locale::gettext q{textdomain};
1026 Locale::gettext->domain('ikiwiki')
1034 return $gettext_obj->get(shift);
1041 sub pagespec_merge ($$) { #{{{
1045 return $a if $a eq $b;
1047 # Support for old-style GlobLists.
1048 if (is_globlist($a)) {
1049 $a=globlist_to_pagespec($a);
1051 if (is_globlist($b)) {
1052 $b=globlist_to_pagespec($b);
1055 return "($a) or ($b)";
1058 sub pagespec_translate ($) { #{{{
1059 # This assumes that $page is in scope in the function
1060 # that evalulates the translated pagespec code.
1063 # Support for old-style GlobLists.
1064 if (is_globlist($spec)) {
1065 $spec=globlist_to_pagespec($spec);
1068 # Convert spec to perl code.
1071 \s* # ignore whitespace
1072 ( # 1: match a single word
1079 \w+\([^\)]*\) # command(params)
1081 [^\s()]+ # any other text
1083 \s* # ignore whitespace
1086 if (lc $word eq 'and') {
1089 elsif (lc $word eq 'or') {
1092 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1095 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1096 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1097 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1104 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1111 sub pagespec_match ($$;@) { #{{{
1116 # Backwards compatability with old calling convention.
1118 unshift @params, 'location';
1121 my $ret=eval pagespec_translate($spec);
1122 return IkiWiki::FailReason->new('syntax error') if $@;
1126 package IkiWiki::FailReason;
1129 '""' => sub { ${$_[0]} },
1131 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1136 return bless \$_[1], $_[0];
1139 package IkiWiki::SuccessReason;
1142 '""' => sub { ${$_[0]} },
1144 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1149 return bless \$_[1], $_[0];
1152 package IkiWiki::PageSpec;
1154 sub match_glob ($$;@) { #{{{
1159 my $from=exists $params{location} ? $params{location} : '';
1162 if ($glob =~ m!^\./!) {
1163 $from=~s#/?[^/]+$##;
1165 $glob="$from/$glob" if length $from;
1168 # turn glob into safe regexp
1169 $glob=quotemeta($glob);
1173 if ($page=~/^$glob$/i) {
1174 return IkiWiki::SuccessReason->new("$glob matches $page");
1177 return IkiWiki::FailReason->new("$glob does not match $page");
1181 sub match_link ($$;@) { #{{{
1186 my $from=exists $params{location} ? $params{location} : '';
1189 if ($link =~ m!^\.! && defined $from) {
1190 $from=~s#/?[^/]+$##;
1192 $link="$from/$link" if length $from;
1195 my $links = $IkiWiki::links{$page};
1196 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1197 my $bestlink = IkiWiki::bestlink($from, $link);
1198 foreach my $p (@{$links}) {
1199 if (length $bestlink) {
1200 return IkiWiki::SuccessReason->new("$page links to $link")
1201 if $bestlink eq IkiWiki::bestlink($page, $p);
1204 return IkiWiki::SuccessReason->new("$page links to page matching $link")
1205 if match_glob($p, $link, %params);
1208 return IkiWiki::FailReason->new("$page does not link to $link");
1211 sub match_backlink ($$;@) { #{{{
1212 return match_link($_[1], $_[0], @_);
1215 sub match_created_before ($$;@) { #{{{
1219 if (exists $IkiWiki::pagectime{$testpage}) {
1220 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1221 return IkiWiki::SuccessReason->new("$page created before $testpage");
1224 return IkiWiki::FailReason->new("$page not created before $testpage");
1228 return IkiWiki::FailReason->new("$testpage has no ctime");
1232 sub match_created_after ($$;@) { #{{{
1236 if (exists $IkiWiki::pagectime{$testpage}) {
1237 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1238 return IkiWiki::SuccessReason->new("$page created after $testpage");
1241 return IkiWiki::FailReason->new("$page not created after $testpage");
1245 return IkiWiki::FailReason->new("$testpage has no ctime");
1249 sub match_creation_day ($$;@) { #{{{
1250 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1251 return IkiWiki::SuccessReason->new('creation_day matched');
1254 return IkiWiki::FailReason->new('creation_day did not match');
1258 sub match_creation_month ($$;@) { #{{{
1259 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1260 return IkiWiki::SuccessReason->new('creation_month matched');
1263 return IkiWiki::FailReason->new('creation_month did not match');
1267 sub match_creation_year ($$;@) { #{{{
1268 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1269 return IkiWiki::SuccessReason->new('creation_year matched');
1272 return IkiWiki::FailReason->new('creation_year did not match');
1276 sub match_user ($$;@) { #{{{
1281 return IkiWiki::FailReason->new('cannot match user')
1282 unless exists $params{user};
1283 if ($user eq $params{user}) {
1284 return IkiWiki::SuccessReason->new("user is $user")
1287 return IkiWiki::FailReason->new("user is not $user");