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 if (exists $config{umask}) {
145 umask(possibly_foolish_untaint($config{umask}));
148 run_hooks(checkconfig => sub { shift->() });
153 sub loadplugins () { #{{{
154 if (defined $config{libdir}) {
155 unshift @INC, possibly_foolish_untaint($config{libdir});
158 loadplugin($_) foreach @{$config{plugin}};
160 run_hooks(getopt => sub { shift->() });
161 if (grep /^-/, @ARGV) {
162 print STDERR "Unknown option: $_\n"
163 foreach grep /^-/, @ARGV;
170 sub loadplugin ($) { #{{{
173 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
175 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
176 "$installdir/lib/ikiwiki") {
177 if (defined $dir && -x "$dir/plugins/$plugin") {
178 require IkiWiki::Plugin::external;
179 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
184 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
187 error("Failed to load plugin $mod: $@");
192 sub error ($;$) { #{{{
196 print "Content-type: text/html\n\n";
197 print misctemplate(gettext("Error"),
198 "<p>".gettext("Error").": $message</p>");
200 log_message('err' => $message) if $config{syslog};
201 if (defined $cleaner) {
208 return unless $config{verbose};
209 return log_message(debug => @_);
213 sub log_message ($$) { #{{{
216 if ($config{syslog}) {
219 Sys::Syslog::setlogsock('unix');
220 Sys::Syslog::openlog('ikiwiki', '', 'user');
224 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
227 elsif (! $config{cgi}) {
231 return print STDERR "@_\n";
235 sub possibly_foolish_untaint ($) { #{{{
237 my ($untainted)=$tainted=~/(.*)/s;
241 sub basename ($) { #{{{
248 sub dirname ($) { #{{{
255 sub pagetype ($) { #{{{
258 if ($page =~ /\.([^.]+)$/) {
259 return $1 if exists $hooks{htmlize}{$1};
264 sub pagename ($) { #{{{
267 my $type=pagetype($file);
269 $page=~s/\Q.$type\E*$// if defined $type;
273 sub targetpage ($$) { #{{{
277 if (! $config{usedirs} || $page =~ /^index$/ ) {
278 return $page.".".$ext;
280 return $page."/index.".$ext;
284 sub htmlpage ($) { #{{{
287 return targetpage($page, $config{htmlext});
290 sub srcfile ($) { #{{{
293 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
294 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
295 return "$dir/$file" if -e "$dir/$file";
297 error("internal error: $file cannot be found in $config{srcdir} or underlay");
301 sub add_underlay ($) { #{{{
305 unshift @{$config{underlaydirs}}, $dir;
308 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
314 sub readfile ($;$$) { #{{{
320 error("cannot read a symlink ($file)");
324 open (my $in, "<", $file) || error("failed to read $file: $!");
325 binmode($in) if ($binary);
326 return \*$in if $wantfd;
328 close $in || error("failed to read $file: $!");
332 sub writefile ($$$;$$) { #{{{
333 my $file=shift; # can include subdirs
334 my $destdir=shift; # directory to put file in
340 while (length $test) {
341 if (-l "$destdir/$test") {
342 error("cannot write to a symlink ($test)");
344 $test=dirname($test);
346 my $newfile="$destdir/$file.ikiwiki-new";
348 error("cannot write to a symlink ($newfile)");
351 my $dir=dirname($newfile);
354 foreach my $s (split(m!/+!, $dir)) {
357 mkdir($d) || error("failed to create directory $d: $!");
362 my $cleanup = sub { unlink($newfile) };
363 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
364 binmode($out) if ($binary);
366 $writer->(\*$out, $cleanup);
369 print $out $content or error("failed writing to $newfile: $!", $cleanup);
371 close $out || error("failed saving $newfile: $!", $cleanup);
372 rename($newfile, "$destdir/$file") ||
373 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
379 sub will_render ($$;$) { #{{{
384 # Important security check.
385 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
386 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
387 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
390 if (! $clear || $cleared{$page}) {
391 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
394 foreach my $old (@{$renderedfiles{$page}}) {
395 delete $destsources{$old};
397 $renderedfiles{$page}=[$dest];
400 $destsources{$dest}=$page;
405 sub bestlink ($$) { #{{{
410 if ($link=~s/^\/+//) {
418 $l.="/" if length $l;
421 if (exists $links{$l}) {
424 elsif (exists $pagecase{lc $l}) {
425 return $pagecase{lc $l};
427 } while $cwd=~s!/?[^/]+$!!;
429 if (length $config{userdir}) {
430 my $l = "$config{userdir}/".lc($link);
431 if (exists $links{$l}) {
434 elsif (exists $pagecase{lc $l}) {
435 return $pagecase{lc $l};
439 #print STDERR "warning: page $page, broken link: $link\n";
443 sub isinlinableimage ($) { #{{{
446 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
449 sub pagetitle ($;$) { #{{{
454 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
457 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
463 sub titlepage ($) { #{{{
465 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
469 sub linkpage ($) { #{{{
471 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
475 sub cgiurl (@) { #{{{
478 return $config{cgiurl}."?".
479 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
482 sub baseurl (;$) { #{{{
485 return "$config{url}/" if ! defined $page;
487 $page=htmlpage($page);
489 $page=~s/[^\/]+\//..\//g;
493 sub abs2rel ($$) { #{{{
494 # Work around very innefficient behavior in File::Spec if abs2rel
495 # is passed two relative paths. It's much faster if paths are
496 # absolute! (Debian bug #376658; fixed in debian unstable now)
501 my $ret=File::Spec->abs2rel($path, $base);
502 $ret=~s/^// if defined $ret;
506 sub displaytime ($;$) { #{{{
509 if (! defined $format) {
510 $format=$config{timeformat};
513 # strftime doesn't know about encodings, so make sure
514 # its output is properly treated as utf8
515 return decode_utf8(POSIX::strftime($format, localtime($time)));
518 sub beautify_url ($) { #{{{
521 if ($config{usedirs}) {
522 $url =~ s!/index.$config{htmlext}$!/!;
524 $url =~ s!^$!./!; # Browsers don't like empty links...
529 sub urlto ($$) { #{{{
534 return beautify_url(baseurl($from));
537 if (! $destsources{$to}) {
541 my $link = abs2rel($to, dirname(htmlpage($from)));
543 return beautify_url($link);
546 sub htmllink ($$$;@) { #{{{
547 my $lpage=shift; # the page doing the linking
548 my $page=shift; # the page that will contain the link (different for inline)
555 if (! $opts{forcesubpage}) {
556 $bestlink=bestlink($lpage, $link);
559 $bestlink="$lpage/".lc($link);
563 if (defined $opts{linktext}) {
564 $linktext=$opts{linktext};
567 $linktext=pagetitle(basename($link));
570 return "<span class=\"selflink\">$linktext</span>"
571 if length $bestlink && $page eq $bestlink &&
572 ! defined $opts{anchor};
574 if (! $destsources{$bestlink}) {
575 $bestlink=htmlpage($bestlink);
577 if (! $destsources{$bestlink}) {
578 return $linktext unless length $config{cgiurl};
579 return "<span class=\"createlink\"><a href=\"".
582 page => pagetitle(lc($link), 1),
585 "\">?</a>$linktext</span>"
589 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
590 $bestlink=beautify_url($bestlink);
592 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
593 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
596 if (defined $opts{anchor}) {
597 $bestlink.="#".$opts{anchor};
601 if (defined $opts{rel}) {
602 push @attrs, ' rel="'.$opts{rel}.'"';
604 if (defined $opts{class}) {
605 push @attrs, ' class="'.$opts{class}.'"';
608 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
611 sub htmlize ($$$) { #{{{
616 if (exists $hooks{htmlize}{$type}) {
617 $content=$hooks{htmlize}{$type}{call}->(
623 error("htmlization of $type not supported");
626 run_hooks(sanitize => sub {
636 sub linkify ($$$) { #{{{
637 my $lpage=shift; # the page containing the links
638 my $page=shift; # the page the link will end up on (different for inline)
641 $content =~ s{(\\?)$config{wiki_link_regexp}}{
644 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
645 : htmllink($lpage, $page, linkpage($3),
646 anchor => $4, linktext => pagetitle($2)))
648 ? "[[$3".($4 ? "#$4" : "")."]]"
649 : htmllink($lpage, $page, linkpage($3),
657 our $preprocess_preview=0;
658 sub preprocess ($$$;$$) { #{{{
659 my $page=shift; # the page the data comes from
660 my $destpage=shift; # the page the data will appear in (different for inline)
665 # Using local because it needs to be set within any nested calls
667 local $preprocess_preview=$preview if defined $preview;
673 if (length $escape) {
674 return "[[$command $params]]";
676 elsif (exists $hooks{preprocess}{$command}) {
677 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
678 # Note: preserve order of params, some plugins may
679 # consider it significant.
682 (?:(\w+)=)? # 1: named parameter key?
684 """(.*?)""" # 2: triple-quoted value
686 "([^"]+)" # 3: single-quoted value
688 (\S+) # 4: unquoted value
690 (?:\s+|$) # delimiter to next param
708 push @params, $key, $val;
711 push @params, $val, '';
714 if ($preprocessing{$page}++ > 3) {
715 # Avoid loops of preprocessed pages preprocessing
716 # other pages that preprocess them, etc.
717 #translators: The first parameter is a
718 #translators: preprocessor directive name,
719 #translators: the second a page name, the
720 #translators: third a number.
721 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
722 $command, $page, $preprocessing{$page}).
725 my $ret=$hooks{preprocess}{$command}{call}->(
728 destpage => $destpage,
729 preview => $preprocess_preview,
731 $preprocessing{$page}--;
735 return "[[$command $params]]";
741 \[\[ # directive open
744 ( # 3: the parameters..
746 (?:\w+=)? # named parameter key?
748 """.*?""" # triple-quoted value
750 "[^"]+" # single-quoted value
752 [^\s\]]+ # unquoted value
754 \s* # whitespace or end
757 *) # 0 or more parameters
758 \]\] # directive closed
759 }{$handle->($1, $2, $3)}sexg;
763 sub filter ($$$) { #{{{
768 run_hooks(filter => sub {
769 $content=shift->(page => $page, destpage => $destpage,
770 content => $content);
776 sub indexlink () { #{{{
777 return "<a href=\"$config{url}\">$config{wikiname}</a>";
782 sub lockwiki (;$) { #{{{
783 my $wait=@_ ? shift : 1;
784 # Take an exclusive lock on the wiki to prevent multiple concurrent
785 # run issues. The lock will be dropped on program exit.
786 if (! -d $config{wikistatedir}) {
787 mkdir($config{wikistatedir});
789 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
790 error ("cannot write to $config{wikistatedir}/lockfile: $!");
791 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
793 debug("wiki seems to be locked, waiting for lock");
794 my $wait=600; # arbitrary, but don't hang forever to
795 # prevent process pileup
797 return if flock($wikilock, 2 | 4);
800 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
809 sub unlockwiki () { #{{{
810 return close($wikilock) if $wikilock;
816 sub commit_hook_enabled () { #{{{
817 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
818 error("cannot write to $config{wikistatedir}/commitlock: $!");
819 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
820 close($commitlock) || error("failed closing commitlock: $!");
823 close($commitlock) || error("failed closing commitlock: $!");
827 sub disable_commit_hook () { #{{{
828 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
829 error("cannot write to $config{wikistatedir}/commitlock: $!");
830 if (! flock($commitlock, 2)) { # LOCK_EX
831 error("failed to get commit lock");
836 sub enable_commit_hook () { #{{{
837 return close($commitlock) if $commitlock;
841 sub loadindex () { #{{{
842 %oldrenderedfiles=%pagectime=();
843 if (! $config{rebuild}) {
844 %pagesources=%pagemtime=%oldlinks=%links=%depends=
845 %destsources=%renderedfiles=%pagecase=();
847 open (my $in, "<", "$config{wikistatedir}/index") || return;
849 $_=possibly_foolish_untaint($_);
854 foreach my $i (split(/ /, $_)) {
855 my ($item, $val)=split(/=/, $i, 2);
856 push @{$items{$item}}, decode_entities($val);
859 next unless exists $items{src}; # skip bad lines for now
861 my $page=pagename($items{src}[0]);
862 if (! $config{rebuild}) {
863 $pagesources{$page}=$items{src}[0];
864 $pagemtime{$page}=$items{mtime}[0];
865 $oldlinks{$page}=[@{$items{link}}];
866 $links{$page}=[@{$items{link}}];
867 $depends{$page}=$items{depends}[0] if exists $items{depends};
868 $destsources{$_}=$page foreach @{$items{dest}};
869 $renderedfiles{$page}=[@{$items{dest}}];
870 $pagecase{lc $page}=$page;
872 $oldrenderedfiles{$page}=[@{$items{dest}}];
873 $pagectime{$page}=$items{ctime}[0];
878 sub saveindex () { #{{{
879 run_hooks(savestate => sub { shift->() });
881 if (! -d $config{wikistatedir}) {
882 mkdir($config{wikistatedir});
884 my $newfile="$config{wikistatedir}/index.new";
885 my $cleanup = sub { unlink($newfile) };
886 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
887 foreach my $page (keys %pagemtime) {
888 next unless $pagemtime{$page};
889 my $line="mtime=$pagemtime{$page} ".
890 "ctime=$pagectime{$page} ".
891 "src=$pagesources{$page}";
892 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
894 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
895 if (exists $depends{$page}) {
896 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
898 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
900 close $out || error("failed saving to $newfile: $!", $cleanup);
901 rename($newfile, "$config{wikistatedir}/index") ||
902 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
907 sub template_file ($) { #{{{
910 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
911 return "$dir/$template" if -e "$dir/$template";
916 sub template_params (@) { #{{{
917 my $filename=template_file(shift);
919 if (! defined $filename) {
926 my $text_ref = shift;
927 ${$text_ref} = decode_utf8(${$text_ref});
929 filename => $filename,
930 loop_context_vars => 1,
931 die_on_bad_params => 0,
934 return wantarray ? @ret : {@ret};
937 sub template ($;@) { #{{{
938 require HTML::Template;
939 return HTML::Template->new(template_params(@_));
942 sub misctemplate ($$;@) { #{{{
946 my $template=template("misc.tmpl");
949 indexlink => indexlink(),
950 wikiname => $config{wikiname},
951 pagebody => $pagebody,
952 baseurl => baseurl(),
955 run_hooks(pagetemplate => sub {
956 shift->(page => "", destpage => "", template => $template);
958 return $template->output;
964 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
965 error 'hook requires type, call, and id parameters';
968 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
970 $hooks{$param{type}}{$param{id}}=\%param;
974 sub run_hooks ($$) { # {{{
975 # Calls the given sub for each hook of the given type,
976 # passing it the hook function to call.
980 if (exists $hooks{$type}) {
982 foreach my $id (keys %{$hooks{$type}}) {
983 if ($hooks{$type}{$id}{last}) {
987 $sub->($hooks{$type}{$id}{call});
989 foreach my $id (@deferred) {
990 $sub->($hooks{$type}{$id}{call});
997 sub globlist_to_pagespec ($) { #{{{
998 my @globlist=split(' ', shift);
1001 foreach my $glob (@globlist) {
1002 if ($glob=~/^!(.*)/) {
1010 my $spec=join(' or ', @spec);
1012 my $skip=join(' and ', @skip);
1014 $spec="$skip and ($spec)";
1023 sub is_globlist ($) { #{{{
1025 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1028 sub safequote ($) { #{{{
1034 sub add_depends ($$) { #{{{
1038 if (! exists $depends{$page}) {
1039 $depends{$page}=$pagespec;
1042 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1048 sub file_pruned ($$) { #{{{
1050 my $file=File::Spec->canonpath(shift);
1051 my $base=File::Spec->canonpath(shift);
1052 $file =~ s#^\Q$base\E/*##;
1054 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1055 return $file =~ m/$regexp/;
1059 # Only use gettext in the rare cases it's needed.
1060 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1061 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1062 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1063 if (! $gettext_obj) {
1064 $gettext_obj=eval q{
1065 use Locale::gettext q{textdomain};
1066 Locale::gettext->domain('ikiwiki')
1074 return $gettext_obj->get(shift);
1081 sub pagespec_merge ($$) { #{{{
1085 return $a if $a eq $b;
1087 # Support for old-style GlobLists.
1088 if (is_globlist($a)) {
1089 $a=globlist_to_pagespec($a);
1091 if (is_globlist($b)) {
1092 $b=globlist_to_pagespec($b);
1095 return "($a) or ($b)";
1098 sub pagespec_translate ($) { #{{{
1099 # This assumes that $page is in scope in the function
1100 # that evalulates the translated pagespec code.
1103 # Support for old-style GlobLists.
1104 if (is_globlist($spec)) {
1105 $spec=globlist_to_pagespec($spec);
1108 # Convert spec to perl code.
1111 \s* # ignore whitespace
1112 ( # 1: match a single word
1119 \w+\([^\)]*\) # command(params)
1121 [^\s()]+ # any other text
1123 \s* # ignore whitespace
1126 if (lc $word eq 'and') {
1129 elsif (lc $word eq 'or') {
1132 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1135 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1136 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1137 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1144 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1151 sub pagespec_match ($$;@) { #{{{
1156 # Backwards compatability with old calling convention.
1158 unshift @params, 'location';
1161 my $ret=eval pagespec_translate($spec);
1162 return IkiWiki::FailReason->new('syntax error') if $@;
1166 package IkiWiki::FailReason;
1169 '""' => sub { ${$_[0]} },
1171 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1176 return bless \$_[1], $_[0];
1179 package IkiWiki::SuccessReason;
1182 '""' => sub { ${$_[0]} },
1184 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1189 return bless \$_[1], $_[0];
1192 package IkiWiki::PageSpec;
1194 sub match_glob ($$;@) { #{{{
1199 my $from=exists $params{location} ? $params{location} : '';
1202 if ($glob =~ m!^\./!) {
1203 $from=~s#/?[^/]+$##;
1205 $glob="$from/$glob" if length $from;
1208 # turn glob into safe regexp
1209 $glob=quotemeta($glob);
1213 if ($page=~/^$glob$/i) {
1214 return IkiWiki::SuccessReason->new("$glob matches $page");
1217 return IkiWiki::FailReason->new("$glob does not match $page");
1221 sub match_link ($$;@) { #{{{
1226 my $from=exists $params{location} ? $params{location} : '';
1229 if ($link =~ m!^\.! && defined $from) {
1230 $from=~s#/?[^/]+$##;
1232 $link="$from/$link" if length $from;
1235 my $links = $IkiWiki::links{$page};
1236 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1237 my $bestlink = IkiWiki::bestlink($from, $link);
1238 foreach my $p (@{$links}) {
1239 if (length $bestlink) {
1240 return IkiWiki::SuccessReason->new("$page links to $link")
1241 if $bestlink eq IkiWiki::bestlink($page, $p);
1244 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1245 if match_glob($p, $link, %params);
1248 return IkiWiki::FailReason->new("$page does not link to $link");
1251 sub match_backlink ($$;@) { #{{{
1252 return match_link($_[1], $_[0], @_);
1255 sub match_created_before ($$;@) { #{{{
1259 if (exists $IkiWiki::pagectime{$testpage}) {
1260 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1261 return IkiWiki::SuccessReason->new("$page created before $testpage");
1264 return IkiWiki::FailReason->new("$page not created before $testpage");
1268 return IkiWiki::FailReason->new("$testpage has no ctime");
1272 sub match_created_after ($$;@) { #{{{
1276 if (exists $IkiWiki::pagectime{$testpage}) {
1277 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1278 return IkiWiki::SuccessReason->new("$page created after $testpage");
1281 return IkiWiki::FailReason->new("$page not created after $testpage");
1285 return IkiWiki::FailReason->new("$testpage has no ctime");
1289 sub match_creation_day ($$;@) { #{{{
1290 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1291 return IkiWiki::SuccessReason->new('creation_day matched');
1294 return IkiWiki::FailReason->new('creation_day did not match');
1298 sub match_creation_month ($$;@) { #{{{
1299 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1300 return IkiWiki::SuccessReason->new('creation_month matched');
1303 return IkiWiki::FailReason->new('creation_month did not match');
1307 sub match_creation_year ($$;@) { #{{{
1308 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1309 return IkiWiki::SuccessReason->new('creation_year matched');
1312 return IkiWiki::FailReason->new('creation_year did not match');
1316 sub match_user ($$;@) { #{{{
1321 return IkiWiki::FailReason->new('cannot match user')
1322 unless exists $params{user};
1323 if ($user eq $params{user}) {
1324 return IkiWiki::SuccessReason->new("user is $user")
1327 return IkiWiki::FailReason->new("user is not $user");