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]+) # 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 # strftime doesn't know about encodings, so make sure
505 # its output is properly treated as utf8
506 return decode_utf8(POSIX::strftime(
507 $config{timeformat}, localtime($time)));
510 sub beautify_url ($) { #{{{
513 $url =~ s!/index.$config{htmlext}$!/!;
514 $url =~ s!^$!./!; # Browsers don't like empty links...
519 sub urlto ($$) { #{{{
524 return beautify_url(baseurl($from));
527 if (! $destsources{$to}) {
531 my $link = abs2rel($to, dirname(htmlpage($from)));
533 return beautify_url($link);
536 sub htmllink ($$$;@) { #{{{
537 my $lpage=shift; # the page doing the linking
538 my $page=shift; # the page that will contain the link (different for inline)
543 if (! $opts{forcesubpage}) {
544 $bestlink=bestlink($lpage, $link);
547 $bestlink="$lpage/".lc($link);
551 if (defined $opts{linktext}) {
552 $linktext=$opts{linktext};
555 $linktext=pagetitle(basename($link));
558 return "<span class=\"selflink\">$linktext</span>"
559 if length $bestlink && $page eq $bestlink;
561 if (! $destsources{$bestlink}) {
562 $bestlink=htmlpage($bestlink);
564 if (! $destsources{$bestlink}) {
565 return $linktext unless length $config{cgiurl};
566 return "<span><a href=\"".
569 page => pagetitle(lc($link), 1),
572 "\">?</a>$linktext</span>"
576 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
577 $bestlink=beautify_url($bestlink);
579 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
580 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
583 if (defined $opts{anchor}) {
584 $bestlink.="#".$opts{anchor};
588 if (defined $opts{rel}) {
589 push @attrs, ' rel="'.$opts{rel}.'"';
592 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
595 sub htmlize ($$$) { #{{{
600 if (exists $hooks{htmlize}{$type}) {
601 $content=$hooks{htmlize}{$type}{call}->(
607 error("htmlization of $type not supported");
610 run_hooks(sanitize => sub {
620 sub linkify ($$$) { #{{{
621 my $lpage=shift; # the page containing the links
622 my $page=shift; # the page the link will end up on (different for inline)
625 $content =~ s{(\\?)$config{wiki_link_regexp}}{
628 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
629 : htmllink($lpage, $page, linkpage($3),
630 anchor => $4, linktext => pagetitle($2)))
632 ? "[[$3".($4 ? "#$4" : "")."]]"
633 : htmllink($lpage, $page, linkpage($3),
641 our $preprocess_preview=0;
642 sub preprocess ($$$;$$) { #{{{
643 my $page=shift; # the page the data comes from
644 my $destpage=shift; # the page the data will appear in (different for inline)
649 # Using local because it needs to be set within any nested calls
651 local $preprocess_preview=$preview if defined $preview;
657 if (length $escape) {
658 return "[[$command $params]]";
660 elsif (exists $hooks{preprocess}{$command}) {
661 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
662 # Note: preserve order of params, some plugins may
663 # consider it significant.
666 (?:(\w+)=)? # 1: named parameter key?
668 """(.*?)""" # 2: triple-quoted value
670 "([^"]+)" # 3: single-quoted value
672 (\S+) # 4: unquoted value
674 (?:\s+|$) # delimiter to next param
692 push @params, $key, $val;
695 push @params, $val, '';
698 if ($preprocessing{$page}++ > 3) {
699 # Avoid loops of preprocessed pages preprocessing
700 # other pages that preprocess them, etc.
701 #translators: The first parameter is a
702 #translators: preprocessor directive name,
703 #translators: the second a page name, the
704 #translators: third a number.
705 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
706 $command, $page, $preprocessing{$page}).
709 my $ret=$hooks{preprocess}{$command}{call}->(
712 destpage => $destpage,
713 preview => $preprocess_preview,
715 $preprocessing{$page}--;
719 return "[[$command $params]]";
725 \[\[ # directive open
728 ( # 3: the parameters..
730 (?:\w+=)? # named parameter key?
732 """.*?""" # triple-quoted value
734 "[^"]+" # single-quoted value
736 [^\s\]]+ # unquoted value
738 \s* # whitespace or end
741 *) # 0 or more parameters
742 \]\] # directive closed
743 }{$handle->($1, $2, $3)}sexg;
747 sub filter ($$$) { #{{{
752 run_hooks(filter => sub {
753 $content=shift->(page => $page, destpage => $destpage,
754 content => $content);
760 sub indexlink () { #{{{
761 return "<a href=\"$config{url}\">$config{wikiname}</a>";
766 sub lockwiki (;$) { #{{{
767 my $wait=@_ ? shift : 1;
768 # Take an exclusive lock on the wiki to prevent multiple concurrent
769 # run issues. The lock will be dropped on program exit.
770 if (! -d $config{wikistatedir}) {
771 mkdir($config{wikistatedir});
773 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
774 error ("cannot write to $config{wikistatedir}/lockfile: $!");
775 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
777 debug("wiki seems to be locked, waiting for lock");
778 my $wait=600; # arbitrary, but don't hang forever to
779 # prevent process pileup
781 return if flock($wikilock, 2 | 4);
784 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
793 sub unlockwiki () { #{{{
794 return close($wikilock) if $wikilock;
800 sub commit_hook_enabled () { #{{{
801 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
802 error("cannot write to $config{wikistatedir}/commitlock: $!");
803 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
804 close($commitlock) || error("failed closing commitlock: $!");
807 close($commitlock) || error("failed closing commitlock: $!");
811 sub disable_commit_hook () { #{{{
812 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
813 error("cannot write to $config{wikistatedir}/commitlock: $!");
814 if (! flock($commitlock, 2)) { # LOCK_EX
815 error("failed to get commit lock");
820 sub enable_commit_hook () { #{{{
821 return close($commitlock) if $commitlock;
825 sub loadindex () { #{{{
826 open (my $in, "<", "$config{wikistatedir}/index") || return;
828 $_=possibly_foolish_untaint($_);
833 foreach my $i (split(/ /, $_)) {
834 my ($item, $val)=split(/=/, $i, 2);
835 push @{$items{$item}}, decode_entities($val);
838 next unless exists $items{src}; # skip bad lines for now
840 my $page=pagename($items{src}[0]);
841 if (! $config{rebuild}) {
842 $pagesources{$page}=$items{src}[0];
843 $pagemtime{$page}=$items{mtime}[0];
844 $oldlinks{$page}=[@{$items{link}}];
845 $links{$page}=[@{$items{link}}];
846 $depends{$page}=$items{depends}[0] if exists $items{depends};
847 $destsources{$_}=$page foreach @{$items{dest}};
848 $renderedfiles{$page}=[@{$items{dest}}];
849 $pagecase{lc $page}=$page;
851 $oldrenderedfiles{$page}=[@{$items{dest}}];
852 $pagectime{$page}=$items{ctime}[0];
857 sub saveindex () { #{{{
858 run_hooks(savestate => sub { shift->() });
860 if (! -d $config{wikistatedir}) {
861 mkdir($config{wikistatedir});
863 my $newfile="$config{wikistatedir}/index.new";
864 my $cleanup = sub { unlink($newfile) };
865 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
866 foreach my $page (keys %pagemtime) {
867 next unless $pagemtime{$page};
868 my $line="mtime=$pagemtime{$page} ".
869 "ctime=$pagectime{$page} ".
870 "src=$pagesources{$page}";
871 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
873 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
874 if (exists $depends{$page}) {
875 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
877 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
879 close $out || error("failed saving to $newfile: $!", $cleanup);
880 rename($newfile, "$config{wikistatedir}/index") ||
881 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
886 sub template_file ($) { #{{{
889 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
890 return "$dir/$template" if -e "$dir/$template";
895 sub template_params (@) { #{{{
896 my $filename=template_file(shift);
898 if (! defined $filename) {
905 my $text_ref = shift;
906 ${$text_ref} = Encode::decode_utf8(${$text_ref});
908 filename => $filename,
909 loop_context_vars => 1,
910 die_on_bad_params => 0,
913 return wantarray ? @ret : {@ret};
916 sub template ($;@) { #{{{
917 require HTML::Template;
918 return HTML::Template->new(template_params(@_));
921 sub misctemplate ($$;@) { #{{{
925 my $template=template("misc.tmpl");
928 indexlink => indexlink(),
929 wikiname => $config{wikiname},
930 pagebody => $pagebody,
931 baseurl => baseurl(),
934 run_hooks(pagetemplate => sub {
935 shift->(page => "", destpage => "", template => $template);
937 return $template->output;
943 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
944 error 'hook requires type, call, and id parameters';
947 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
949 $hooks{$param{type}}{$param{id}}=\%param;
953 sub run_hooks ($$) { # {{{
954 # Calls the given sub for each hook of the given type,
955 # passing it the hook function to call.
959 if (exists $hooks{$type}) {
961 foreach my $id (keys %{$hooks{$type}}) {
962 if ($hooks{$type}{$id}{last}) {
966 $sub->($hooks{$type}{$id}{call});
968 foreach my $id (@deferred) {
969 $sub->($hooks{$type}{$id}{call});
976 sub globlist_to_pagespec ($) { #{{{
977 my @globlist=split(' ', shift);
980 foreach my $glob (@globlist) {
981 if ($glob=~/^!(.*)/) {
989 my $spec=join(' or ', @spec);
991 my $skip=join(' and ', @skip);
993 $spec="$skip and ($spec)";
1002 sub is_globlist ($) { #{{{
1004 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1007 sub safequote ($) { #{{{
1013 sub add_depends ($$) { #{{{
1017 if (! exists $depends{$page}) {
1018 $depends{$page}=$pagespec;
1021 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1027 sub file_pruned ($$) { #{{{
1029 my $file=File::Spec->canonpath(shift);
1030 my $base=File::Spec->canonpath(shift);
1031 $file =~ s#^\Q$base\E/*##;
1033 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1034 return $file =~ m/$regexp/;
1038 # Only use gettext in the rare cases it's needed.
1039 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1040 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1041 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1042 if (! $gettext_obj) {
1043 $gettext_obj=eval q{
1044 use Locale::gettext q{textdomain};
1045 Locale::gettext->domain('ikiwiki')
1053 return $gettext_obj->get(shift);
1060 sub pagespec_merge ($$) { #{{{
1064 return $a if $a eq $b;
1066 # Support for old-style GlobLists.
1067 if (is_globlist($a)) {
1068 $a=globlist_to_pagespec($a);
1070 if (is_globlist($b)) {
1071 $b=globlist_to_pagespec($b);
1074 return "($a) or ($b)";
1077 sub pagespec_translate ($) { #{{{
1078 # This assumes that $page is in scope in the function
1079 # that evalulates the translated pagespec code.
1082 # Support for old-style GlobLists.
1083 if (is_globlist($spec)) {
1084 $spec=globlist_to_pagespec($spec);
1087 # Convert spec to perl code.
1090 \s* # ignore whitespace
1091 ( # 1: match a single word
1098 \w+\([^\)]*\) # command(params)
1100 [^\s()]+ # any other text
1102 \s* # ignore whitespace
1105 if (lc $word eq 'and') {
1108 elsif (lc $word eq 'or') {
1111 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1114 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1115 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1116 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1123 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1130 sub pagespec_match ($$;@) { #{{{
1135 # Backwards compatability with old calling convention.
1137 unshift @params, 'location';
1140 my $ret=eval pagespec_translate($spec);
1141 return IkiWiki::FailReason->new('syntax error') if $@;
1145 package IkiWiki::FailReason;
1148 '""' => sub { ${$_[0]} },
1150 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1155 return bless \$_[1], $_[0];
1158 package IkiWiki::SuccessReason;
1161 '""' => sub { ${$_[0]} },
1163 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1168 return bless \$_[1], $_[0];
1171 package IkiWiki::PageSpec;
1173 sub match_glob ($$;@) { #{{{
1178 my $from=exists $params{location} ? $params{location} : '';
1181 if ($glob =~ m!^\./!) {
1182 $from=~s#/?[^/]+$##;
1184 $glob="$from/$glob" if length $from;
1187 # turn glob into safe regexp
1188 $glob=quotemeta($glob);
1192 if ($page=~/^$glob$/i) {
1193 return IkiWiki::SuccessReason->new("$glob matches $page");
1196 return IkiWiki::FailReason->new("$glob does not match $page");
1200 sub match_link ($$;@) { #{{{
1205 my $from=exists $params{location} ? $params{location} : '';
1208 if ($link =~ m!^\.! && defined $from) {
1209 $from=~s#/?[^/]+$##;
1211 $link="$from/$link" if length $from;
1214 my $links = $IkiWiki::links{$page};
1215 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1216 my $bestlink = IkiWiki::bestlink($from, $link);
1217 foreach my $p (@{$links}) {
1218 if (length $bestlink) {
1219 return IkiWiki::SuccessReason->new("$page links to $link")
1220 if $bestlink eq IkiWiki::bestlink($page, $p);
1223 return IkiWiki::SuccessReason->new("$page links to page matching $link")
1224 if match_glob($p, $link, %params);
1227 return IkiWiki::FailReason->new("$page does not link to $link");
1230 sub match_backlink ($$;@) { #{{{
1231 return match_link($_[1], $_[0], @_);
1234 sub match_created_before ($$;@) { #{{{
1238 if (exists $IkiWiki::pagectime{$testpage}) {
1239 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1240 return IkiWiki::SuccessReason->new("$page created before $testpage");
1243 return IkiWiki::FailReason->new("$page not created before $testpage");
1247 return IkiWiki::FailReason->new("$testpage has no ctime");
1251 sub match_created_after ($$;@) { #{{{
1255 if (exists $IkiWiki::pagectime{$testpage}) {
1256 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1257 return IkiWiki::SuccessReason->new("$page created after $testpage");
1260 return IkiWiki::FailReason->new("$page not created after $testpage");
1264 return IkiWiki::FailReason->new("$testpage has no ctime");
1268 sub match_creation_day ($$;@) { #{{{
1269 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1270 return IkiWiki::SuccessReason->new('creation_day matched');
1273 return IkiWiki::FailReason->new('creation_day did not match');
1277 sub match_creation_month ($$;@) { #{{{
1278 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1279 return IkiWiki::SuccessReason->new('creation_month matched');
1282 return IkiWiki::FailReason->new('creation_month did not match');
1286 sub match_creation_year ($$;@) { #{{{
1287 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1288 return IkiWiki::SuccessReason->new('creation_year matched');
1291 return IkiWiki::FailReason->new('creation_year did not match');
1295 sub match_user ($$;@) { #{{{
1300 return IkiWiki::FailReason->new('cannot match user')
1301 unless exists $params{user};
1302 if ($user eq $params{user}) {
1303 return IkiWiki::SuccessReason->new("user is $user")
1306 return IkiWiki::FailReason->new("user is not $user");