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
21 %config %links %renderedfiles %pagesources %destsources);
22 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
23 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
24 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
29 memoize("pagespec_translate");
30 memoize("file_pruned");
32 sub defaultconfig () { #{{{
34 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
35 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
36 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
39 wiki_link_regexp => qr{
40 \[\[ # beginning of link
42 ([^\]\|\n\s]+) # 1: link text
46 ([^\s\]#]+) # 2: page to link to
48 \# # '#', beginning of anchor
49 ([^\s\]]+) # 3: anchor text
54 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
55 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
59 default_pageext => "mdwn",
80 gitorigin_branch => "origin",
81 gitmaster_branch => "master",
85 templatedir => "$installdir/share/ikiwiki/templates",
86 underlaydir => "$installdir/share/ikiwiki/basewiki",
91 plugin => [qw{mdwn inline htmlscrubber passwordauth openid signinedit
92 lockedit conditional}],
101 account_creation_password => "",
104 sub checkconfig () { #{{{
105 # locale stuff; avoid LC_ALL since it overrides everything
106 if (defined $ENV{LC_ALL}) {
107 $ENV{LANG} = $ENV{LC_ALL};
110 if (defined $config{locale}) {
111 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
112 $ENV{LANG}=$config{locale};
117 if ($config{w3mmode}) {
118 eval q{use Cwd q{abs_path}};
120 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
121 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
122 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
123 unless $config{cgiurl} =~ m!file:///!;
124 $config{url}="file://".$config{destdir};
127 if ($config{cgi} && ! length $config{url}) {
128 error(gettext("Must specify url to wiki with --url when using --cgi"));
131 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
132 unless exists $config{wikistatedir};
135 eval qq{use IkiWiki::Rcs::$config{rcs}};
137 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
141 require IkiWiki::Rcs::Stub;
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 pagename ($) { #{{{
263 my $type=pagetype($file);
265 $page=~s/\Q.$type\E*$// if defined $type;
269 sub targetpage ($$) { #{{{
273 if (! $config{usedirs} || $page =~ /^index$/ ) {
274 return $page.".".$ext;
276 return $page."/index.".$ext;
280 sub htmlpage ($) { #{{{
283 return targetpage($page, $config{htmlext});
286 sub srcfile ($) { #{{{
289 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
290 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
291 return "$dir/$file" if -e "$dir/$file";
293 error("internal error: $file cannot be found in $config{srcdir} or underlay");
297 sub add_underlay ($) { #{{{
301 unshift @{$config{underlaydirs}}, $dir;
304 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
310 sub readfile ($;$$) { #{{{
316 error("cannot read a symlink ($file)");
320 open (my $in, "<", $file) || error("failed to read $file: $!");
321 binmode($in) if ($binary);
322 return \*$in if $wantfd;
324 close $in || error("failed to read $file: $!");
328 sub writefile ($$$;$$) { #{{{
329 my $file=shift; # can include subdirs
330 my $destdir=shift; # directory to put file in
336 while (length $test) {
337 if (-l "$destdir/$test") {
338 error("cannot write to a symlink ($test)");
340 $test=dirname($test);
342 my $newfile="$destdir/$file.ikiwiki-new";
344 error("cannot write to a symlink ($newfile)");
347 my $dir=dirname($newfile);
350 foreach my $s (split(m!/+!, $dir)) {
353 mkdir($d) || error("failed to create directory $d: $!");
358 my $cleanup = sub { unlink($newfile) };
359 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
360 binmode($out) if ($binary);
362 $writer->(\*$out, $cleanup);
365 print $out $content or error("failed writing to $newfile: $!", $cleanup);
367 close $out || error("failed saving $newfile: $!", $cleanup);
368 rename($newfile, "$destdir/$file") ||
369 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
375 sub will_render ($$;$) { #{{{
380 # Important security check.
381 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
382 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
383 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
386 if (! $clear || $cleared{$page}) {
387 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
390 foreach my $old (@{$renderedfiles{$page}}) {
391 delete $destsources{$old};
393 $renderedfiles{$page}=[$dest];
396 $destsources{$dest}=$page;
401 sub bestlink ($$) { #{{{
406 if ($link=~s/^\/+//) {
413 $l.="/" if length $l;
416 if (exists $links{$l}) {
419 elsif (exists $pagecase{lc $l}) {
420 return $pagecase{lc $l};
422 } while $cwd=~s!/?[^/]+$!!;
424 if (length $config{userdir}) {
425 my $l = "$config{userdir}/".lc($link);
426 if (exists $links{$l}) {
429 elsif (exists $pagecase{lc $l}) {
430 return $pagecase{lc $l};
434 #print STDERR "warning: page $page, broken link: $link\n";
438 sub isinlinableimage ($) { #{{{
441 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
444 sub pagetitle ($;$) { #{{{
449 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
452 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
458 sub titlepage ($) { #{{{
460 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
464 sub linkpage ($) { #{{{
466 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
470 sub cgiurl (@) { #{{{
473 return $config{cgiurl}."?".
474 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
477 sub baseurl (;$) { #{{{
480 return "$config{url}/" if ! defined $page;
482 $page=htmlpage($page);
484 $page=~s/[^\/]+\//..\//g;
488 sub abs2rel ($$) { #{{{
489 # Work around very innefficient behavior in File::Spec if abs2rel
490 # is passed two relative paths. It's much faster if paths are
491 # absolute! (Debian bug #376658; fixed in debian unstable now)
496 my $ret=File::Spec->abs2rel($path, $base);
497 $ret=~s/^// if defined $ret;
501 sub displaytime ($;$) { #{{{
504 if (! defined $format) {
505 $format=$config{timeformat};
508 # strftime doesn't know about encodings, so make sure
509 # its output is properly treated as utf8
510 return decode_utf8(POSIX::strftime($format, localtime($time)));
513 sub beautify_url ($) { #{{{
516 $url =~ s!/index.$config{htmlext}$!/!;
517 $url =~ s!^$!./!; # Browsers don't like empty links...
522 sub urlto ($$) { #{{{
527 return beautify_url(baseurl($from));
530 if (! $destsources{$to}) {
534 my $link = abs2rel($to, dirname(htmlpage($from)));
536 return beautify_url($link);
539 sub htmllink ($$$;@) { #{{{
540 my $lpage=shift; # the page doing the linking
541 my $page=shift; # the page that will contain the link (different for inline)
546 if (! $opts{forcesubpage}) {
547 $bestlink=bestlink($lpage, $link);
550 $bestlink="$lpage/".lc($link);
554 if (defined $opts{linktext}) {
555 $linktext=$opts{linktext};
558 $linktext=pagetitle(basename($link));
561 return "<span class=\"selflink\">$linktext</span>"
562 if length $bestlink && $page eq $bestlink;
564 if (! $destsources{$bestlink}) {
565 $bestlink=htmlpage($bestlink);
567 if (! $destsources{$bestlink}) {
568 return $linktext unless length $config{cgiurl};
569 return "<span class=\"createlink\"><a href=\"".
572 page => pagetitle(lc($link), 1),
575 "\">?</a>$linktext</span>"
579 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
580 $bestlink=beautify_url($bestlink);
582 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
583 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
586 if (defined $opts{anchor}) {
587 $bestlink.="#".$opts{anchor};
591 if (defined $opts{rel}) {
592 push @attrs, ' rel="'.$opts{rel}.'"';
594 if (defined $opts{class}) {
595 push @attrs, ' class="'.$opts{class}.'"';
598 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
601 sub htmlize ($$$) { #{{{
606 if (exists $hooks{htmlize}{$type}) {
607 $content=$hooks{htmlize}{$type}{call}->(
613 error("htmlization of $type not supported");
616 run_hooks(sanitize => sub {
626 sub linkify ($$$) { #{{{
627 my $lpage=shift; # the page containing the links
628 my $page=shift; # the page the link will end up on (different for inline)
631 $content =~ s{(\\?)$config{wiki_link_regexp}}{
634 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
635 : htmllink($lpage, $page, linkpage($3),
636 anchor => $4, linktext => pagetitle($2)))
638 ? "[[$3".($4 ? "#$4" : "")."]]"
639 : htmllink($lpage, $page, linkpage($3),
647 our $preprocess_preview=0;
648 sub preprocess ($$$;$$) { #{{{
649 my $page=shift; # the page the data comes from
650 my $destpage=shift; # the page the data will appear in (different for inline)
655 # Using local because it needs to be set within any nested calls
657 local $preprocess_preview=$preview if defined $preview;
663 if (length $escape) {
664 return "[[$command $params]]";
666 elsif (exists $hooks{preprocess}{$command}) {
667 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
668 # Note: preserve order of params, some plugins may
669 # consider it significant.
672 (?:(\w+)=)? # 1: named parameter key?
674 """(.*?)""" # 2: triple-quoted value
676 "([^"]+)" # 3: single-quoted value
678 (\S+) # 4: unquoted value
680 (?:\s+|$) # delimiter to next param
698 push @params, $key, $val;
701 push @params, $val, '';
704 if ($preprocessing{$page}++ > 3) {
705 # Avoid loops of preprocessed pages preprocessing
706 # other pages that preprocess them, etc.
707 #translators: The first parameter is a
708 #translators: preprocessor directive name,
709 #translators: the second a page name, the
710 #translators: third a number.
711 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
712 $command, $page, $preprocessing{$page}).
715 my $ret=$hooks{preprocess}{$command}{call}->(
718 destpage => $destpage,
719 preview => $preprocess_preview,
721 $preprocessing{$page}--;
725 return "[[$command $params]]";
731 \[\[ # directive open
734 ( # 3: the parameters..
736 (?:\w+=)? # named parameter key?
738 """.*?""" # triple-quoted value
740 "[^"]+" # single-quoted value
742 [^\s\]]+ # unquoted value
744 \s* # whitespace or end
747 *) # 0 or more parameters
748 \]\] # directive closed
749 }{$handle->($1, $2, $3)}sexg;
753 sub filter ($$$) { #{{{
758 run_hooks(filter => sub {
759 $content=shift->(page => $page, destpage => $destpage,
760 content => $content);
766 sub indexlink () { #{{{
767 return "<a href=\"$config{url}\">$config{wikiname}</a>";
772 sub lockwiki (;$) { #{{{
773 my $wait=@_ ? shift : 1;
774 # Take an exclusive lock on the wiki to prevent multiple concurrent
775 # run issues. The lock will be dropped on program exit.
776 if (! -d $config{wikistatedir}) {
777 mkdir($config{wikistatedir});
779 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
780 error ("cannot write to $config{wikistatedir}/lockfile: $!");
781 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
783 debug("wiki seems to be locked, waiting for lock");
784 my $wait=600; # arbitrary, but don't hang forever to
785 # prevent process pileup
787 return if flock($wikilock, 2 | 4);
790 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
799 sub unlockwiki () { #{{{
800 return close($wikilock) if $wikilock;
806 sub commit_hook_enabled () { #{{{
807 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
808 error("cannot write to $config{wikistatedir}/commitlock: $!");
809 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
810 close($commitlock) || error("failed closing commitlock: $!");
813 close($commitlock) || error("failed closing commitlock: $!");
817 sub disable_commit_hook () { #{{{
818 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
819 error("cannot write to $config{wikistatedir}/commitlock: $!");
820 if (! flock($commitlock, 2)) { # LOCK_EX
821 error("failed to get commit lock");
826 sub enable_commit_hook () { #{{{
827 return close($commitlock) if $commitlock;
831 sub loadindex () { #{{{
832 %oldrenderedfiles=%pagectime=();
833 if (! $config{rebuild}) {
834 %pagesources=%pagemtime=%oldlinks=%links=%depends=
835 %destsources=%renderedfiles=%pagecase=();
837 open (my $in, "<", "$config{wikistatedir}/index") || return;
839 $_=possibly_foolish_untaint($_);
844 foreach my $i (split(/ /, $_)) {
845 my ($item, $val)=split(/=/, $i, 2);
846 push @{$items{$item}}, decode_entities($val);
849 next unless exists $items{src}; # skip bad lines for now
851 my $page=pagename($items{src}[0]);
852 if (! $config{rebuild}) {
853 $pagesources{$page}=$items{src}[0];
854 $pagemtime{$page}=$items{mtime}[0];
855 $oldlinks{$page}=[@{$items{link}}];
856 $links{$page}=[@{$items{link}}];
857 $depends{$page}=$items{depends}[0] if exists $items{depends};
858 $destsources{$_}=$page foreach @{$items{dest}};
859 $renderedfiles{$page}=[@{$items{dest}}];
860 $pagecase{lc $page}=$page;
862 $oldrenderedfiles{$page}=[@{$items{dest}}];
863 $pagectime{$page}=$items{ctime}[0];
868 sub saveindex () { #{{{
869 run_hooks(savestate => sub { shift->() });
871 if (! -d $config{wikistatedir}) {
872 mkdir($config{wikistatedir});
874 my $newfile="$config{wikistatedir}/index.new";
875 my $cleanup = sub { unlink($newfile) };
876 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
877 foreach my $page (keys %pagemtime) {
878 next unless $pagemtime{$page};
879 my $line="mtime=$pagemtime{$page} ".
880 "ctime=$pagectime{$page} ".
881 "src=$pagesources{$page}";
882 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
884 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
885 if (exists $depends{$page}) {
886 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
888 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
890 close $out || error("failed saving to $newfile: $!", $cleanup);
891 rename($newfile, "$config{wikistatedir}/index") ||
892 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
897 sub template_file ($) { #{{{
900 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
901 return "$dir/$template" if -e "$dir/$template";
906 sub template_params (@) { #{{{
907 my $filename=template_file(shift);
909 if (! defined $filename) {
916 my $text_ref = shift;
917 ${$text_ref} = decode_utf8(${$text_ref});
919 filename => $filename,
920 loop_context_vars => 1,
921 die_on_bad_params => 0,
924 return wantarray ? @ret : {@ret};
927 sub template ($;@) { #{{{
928 require HTML::Template;
929 return HTML::Template->new(template_params(@_));
932 sub misctemplate ($$;@) { #{{{
936 my $template=template("misc.tmpl");
939 indexlink => indexlink(),
940 wikiname => $config{wikiname},
941 pagebody => $pagebody,
942 baseurl => baseurl(),
945 run_hooks(pagetemplate => sub {
946 shift->(page => "", destpage => "", template => $template);
948 return $template->output;
954 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
955 error 'hook requires type, call, and id parameters';
958 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
960 $hooks{$param{type}}{$param{id}}=\%param;
964 sub run_hooks ($$) { # {{{
965 # Calls the given sub for each hook of the given type,
966 # passing it the hook function to call.
970 if (exists $hooks{$type}) {
972 foreach my $id (keys %{$hooks{$type}}) {
973 if ($hooks{$type}{$id}{last}) {
977 $sub->($hooks{$type}{$id}{call});
979 foreach my $id (@deferred) {
980 $sub->($hooks{$type}{$id}{call});
987 sub globlist_to_pagespec ($) { #{{{
988 my @globlist=split(' ', shift);
991 foreach my $glob (@globlist) {
992 if ($glob=~/^!(.*)/) {
1000 my $spec=join(' or ', @spec);
1002 my $skip=join(' and ', @skip);
1004 $spec="$skip and ($spec)";
1013 sub is_globlist ($) { #{{{
1015 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1018 sub safequote ($) { #{{{
1024 sub add_depends ($$) { #{{{
1028 if (! exists $depends{$page}) {
1029 $depends{$page}=$pagespec;
1032 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1038 sub file_pruned ($$) { #{{{
1040 my $file=File::Spec->canonpath(shift);
1041 my $base=File::Spec->canonpath(shift);
1042 $file =~ s#^\Q$base\E/*##;
1044 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1045 return $file =~ m/$regexp/;
1049 # Only use gettext in the rare cases it's needed.
1050 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1051 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1052 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1053 if (! $gettext_obj) {
1054 $gettext_obj=eval q{
1055 use Locale::gettext q{textdomain};
1056 Locale::gettext->domain('ikiwiki')
1064 return $gettext_obj->get(shift);
1071 sub pagespec_merge ($$) { #{{{
1075 return $a if $a eq $b;
1077 # Support for old-style GlobLists.
1078 if (is_globlist($a)) {
1079 $a=globlist_to_pagespec($a);
1081 if (is_globlist($b)) {
1082 $b=globlist_to_pagespec($b);
1085 return "($a) or ($b)";
1088 sub pagespec_translate ($) { #{{{
1089 # This assumes that $page is in scope in the function
1090 # that evalulates the translated pagespec code.
1093 # Support for old-style GlobLists.
1094 if (is_globlist($spec)) {
1095 $spec=globlist_to_pagespec($spec);
1098 # Convert spec to perl code.
1101 \s* # ignore whitespace
1102 ( # 1: match a single word
1109 \w+\([^\)]*\) # command(params)
1111 [^\s()]+ # any other text
1113 \s* # ignore whitespace
1116 if (lc $word eq 'and') {
1119 elsif (lc $word eq 'or') {
1122 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1125 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1126 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1127 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1134 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1141 sub pagespec_match ($$;@) { #{{{
1146 # Backwards compatability with old calling convention.
1148 unshift @params, 'location';
1151 my $ret=eval pagespec_translate($spec);
1152 return IkiWiki::FailReason->new('syntax error') if $@;
1156 package IkiWiki::FailReason;
1159 '""' => sub { ${$_[0]} },
1161 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1166 return bless \$_[1], $_[0];
1169 package IkiWiki::SuccessReason;
1172 '""' => sub { ${$_[0]} },
1174 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1179 return bless \$_[1], $_[0];
1182 package IkiWiki::PageSpec;
1184 sub match_glob ($$;@) { #{{{
1189 my $from=exists $params{location} ? $params{location} : '';
1192 if ($glob =~ m!^\./!) {
1193 $from=~s#/?[^/]+$##;
1195 $glob="$from/$glob" if length $from;
1198 # turn glob into safe regexp
1199 $glob=quotemeta($glob);
1203 if ($page=~/^$glob$/i) {
1204 return IkiWiki::SuccessReason->new("$glob matches $page");
1207 return IkiWiki::FailReason->new("$glob does not match $page");
1211 sub match_link ($$;@) { #{{{
1216 my $from=exists $params{location} ? $params{location} : '';
1219 if ($link =~ m!^\.! && defined $from) {
1220 $from=~s#/?[^/]+$##;
1222 $link="$from/$link" if length $from;
1225 my $links = $IkiWiki::links{$page};
1226 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1227 my $bestlink = IkiWiki::bestlink($from, $link);
1228 foreach my $p (@{$links}) {
1229 if (length $bestlink) {
1230 return IkiWiki::SuccessReason->new("$page links to $link")
1231 if $bestlink eq IkiWiki::bestlink($page, $p);
1234 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1235 if match_glob($p, $link, %params);
1238 return IkiWiki::FailReason->new("$page does not link to $link");
1241 sub match_backlink ($$;@) { #{{{
1242 return match_link($_[1], $_[0], @_);
1245 sub match_created_before ($$;@) { #{{{
1249 if (exists $IkiWiki::pagectime{$testpage}) {
1250 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1251 return IkiWiki::SuccessReason->new("$page created before $testpage");
1254 return IkiWiki::FailReason->new("$page not created before $testpage");
1258 return IkiWiki::FailReason->new("$testpage has no ctime");
1262 sub match_created_after ($$;@) { #{{{
1266 if (exists $IkiWiki::pagectime{$testpage}) {
1267 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1268 return IkiWiki::SuccessReason->new("$page created after $testpage");
1271 return IkiWiki::FailReason->new("$page not created after $testpage");
1275 return IkiWiki::FailReason->new("$testpage has no ctime");
1279 sub match_creation_day ($$;@) { #{{{
1280 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1281 return IkiWiki::SuccessReason->new('creation_day matched');
1284 return IkiWiki::FailReason->new('creation_day did not match');
1288 sub match_creation_month ($$;@) { #{{{
1289 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1290 return IkiWiki::SuccessReason->new('creation_month matched');
1293 return IkiWiki::FailReason->new('creation_month did not match');
1297 sub match_creation_year ($$;@) { #{{{
1298 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1299 return IkiWiki::SuccessReason->new('creation_year matched');
1302 return IkiWiki::FailReason->new('creation_year did not match');
1306 sub match_user ($$;@) { #{{{
1311 return IkiWiki::FailReason->new('cannot match user')
1312 unless exists $params{user};
1313 if ($user eq $params{user}) {
1314 return IkiWiki::SuccessReason->new("user is $user")
1317 return IkiWiki::FailReason->new("user is not $user");