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 %pagestate %renderedfiles %oldrenderedfiles %pagesources
14 %destsources %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 %pagestate %renderedfiles
22 %pagesources %destsources);
23 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
24 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
25 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
30 memoize("pagespec_translate");
31 memoize("file_pruned");
33 sub defaultconfig () { #{{{
35 wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
36 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
37 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
40 wiki_link_regexp => qr{
41 \[\[ # beginning of link
43 ([^\]\|\n\s]+) # 1: link text
47 ([^\s\]#]+) # 2: page to link to
49 \# # '#', beginning of anchor
50 ([^\s\]]+) # 3: anchor text
55 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
56 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
60 default_pageext => "mdwn",
79 gitorigin_branch => "origin",
80 gitmaster_branch => "master",
84 templatedir => "$installdir/share/ikiwiki/templates",
85 underlaydir => "$installdir/share/ikiwiki/basewiki",
90 plugin => [qw{mdwn inline htmlscrubber passwordauth openid signinedit
91 lockedit conditional recentchanges}],
100 account_creation_password => "",
103 sub checkconfig () { #{{{
104 # locale stuff; avoid LC_ALL since it overrides everything
105 if (defined $ENV{LC_ALL}) {
106 $ENV{LANG} = $ENV{LC_ALL};
109 if (defined $config{locale}) {
110 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
111 $ENV{LANG}=$config{locale};
116 if ($config{w3mmode}) {
117 eval q{use Cwd q{abs_path}};
119 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
120 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
121 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
122 unless $config{cgiurl} =~ m!file:///!;
123 $config{url}="file://".$config{destdir};
126 if ($config{cgi} && ! length $config{url}) {
127 error(gettext("Must specify url to wiki with --url when using --cgi"));
130 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
131 unless exists $config{wikistatedir};
134 eval qq{use IkiWiki::Rcs::$config{rcs}};
136 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
140 require IkiWiki::Rcs::Stub;
143 if (exists $config{umask}) {
144 umask(possibly_foolish_untaint($config{umask}));
147 run_hooks(checkconfig => sub { shift->() });
152 sub loadplugins () { #{{{
153 if (defined $config{libdir}) {
154 unshift @INC, possibly_foolish_untaint($config{libdir});
157 loadplugin($_) foreach @{$config{plugin}};
159 run_hooks(getopt => sub { shift->() });
160 if (grep /^-/, @ARGV) {
161 print STDERR "Unknown option: $_\n"
162 foreach grep /^-/, @ARGV;
169 sub loadplugin ($) { #{{{
172 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
174 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
175 "$installdir/lib/ikiwiki") {
176 if (defined $dir && -x "$dir/plugins/$plugin") {
177 require IkiWiki::Plugin::external;
178 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
183 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
186 error("Failed to load plugin $mod: $@");
191 sub error ($;$) { #{{{
195 print "Content-type: text/html\n\n";
196 print misctemplate(gettext("Error"),
197 "<p>".gettext("Error").": $message</p>");
199 log_message('err' => $message) if $config{syslog};
200 if (defined $cleaner) {
207 return unless $config{verbose};
208 return log_message(debug => @_);
212 sub log_message ($$) { #{{{
215 if ($config{syslog}) {
218 Sys::Syslog::setlogsock('unix');
219 Sys::Syslog::openlog('ikiwiki', '', 'user');
223 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
226 elsif (! $config{cgi}) {
230 return print STDERR "@_\n";
234 sub possibly_foolish_untaint ($) { #{{{
236 my ($untainted)=$tainted=~/(.*)/s;
240 sub basename ($) { #{{{
247 sub dirname ($) { #{{{
254 sub pagetype ($) { #{{{
257 if ($page =~ /\.([^.]+)$/) {
258 return $1 if exists $hooks{htmlize}{$1};
263 sub pagename ($) { #{{{
266 my $type=pagetype($file);
268 $page=~s/\Q.$type\E*$// if defined $type;
272 sub targetpage ($$) { #{{{
276 if (! $config{usedirs} || $page =~ /^index$/ ) {
277 return $page.".".$ext;
279 return $page."/index.".$ext;
283 sub htmlpage ($) { #{{{
286 return targetpage($page, $config{htmlext});
289 sub srcfile ($) { #{{{
292 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
293 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
294 return "$dir/$file" if -e "$dir/$file";
296 error("internal error: $file cannot be found in $config{srcdir} or underlay");
300 sub add_underlay ($) { #{{{
304 unshift @{$config{underlaydirs}}, $dir;
307 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
313 sub readfile ($;$$) { #{{{
319 error("cannot read a symlink ($file)");
323 open (my $in, "<", $file) || error("failed to read $file: $!");
324 binmode($in) if ($binary);
325 return \*$in if $wantfd;
327 close $in || error("failed to read $file: $!");
331 sub writefile ($$$;$$) { #{{{
332 my $file=shift; # can include subdirs
333 my $destdir=shift; # directory to put file in
339 while (length $test) {
340 if (-l "$destdir/$test") {
341 error("cannot write to a symlink ($test)");
343 $test=dirname($test);
345 my $newfile="$destdir/$file.ikiwiki-new";
347 error("cannot write to a symlink ($newfile)");
350 my $dir=dirname($newfile);
353 foreach my $s (split(m!/+!, $dir)) {
356 mkdir($d) || error("failed to create directory $d: $!");
361 my $cleanup = sub { unlink($newfile) };
362 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
363 binmode($out) if ($binary);
365 $writer->(\*$out, $cleanup);
368 print $out $content or error("failed writing to $newfile: $!", $cleanup);
370 close $out || error("failed saving $newfile: $!", $cleanup);
371 rename($newfile, "$destdir/$file") ||
372 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
378 sub will_render ($$;$) { #{{{
383 # Important security check.
384 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
385 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
386 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
389 if (! $clear || $cleared{$page}) {
390 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
393 foreach my $old (@{$renderedfiles{$page}}) {
394 delete $destsources{$old};
396 $renderedfiles{$page}=[$dest];
399 $destsources{$dest}=$page;
404 sub bestlink ($$) { #{{{
409 if ($link=~s/^\/+//) {
417 $l.="/" if length $l;
420 if (exists $links{$l}) {
423 elsif (exists $pagecase{lc $l}) {
424 return $pagecase{lc $l};
426 } while $cwd=~s!/?[^/]+$!!;
428 if (length $config{userdir}) {
429 my $l = "$config{userdir}/".lc($link);
430 if (exists $links{$l}) {
433 elsif (exists $pagecase{lc $l}) {
434 return $pagecase{lc $l};
438 #print STDERR "warning: page $page, broken link: $link\n";
442 sub isinlinableimage ($) { #{{{
445 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
448 sub pagetitle ($;$) { #{{{
453 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
456 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
462 sub titlepage ($) { #{{{
464 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
468 sub linkpage ($) { #{{{
470 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
474 sub cgiurl (@) { #{{{
477 return $config{cgiurl}."?".
478 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
481 sub baseurl (;$) { #{{{
484 return "$config{url}/" if ! defined $page;
486 $page=htmlpage($page);
488 $page=~s/[^\/]+\//..\//g;
492 sub abs2rel ($$) { #{{{
493 # Work around very innefficient behavior in File::Spec if abs2rel
494 # is passed two relative paths. It's much faster if paths are
495 # absolute! (Debian bug #376658; fixed in debian unstable now)
500 my $ret=File::Spec->abs2rel($path, $base);
501 $ret=~s/^// if defined $ret;
505 sub displaytime ($;$) { #{{{
508 if (! defined $format) {
509 $format=$config{timeformat};
512 # strftime doesn't know about encodings, so make sure
513 # its output is properly treated as utf8
514 return decode_utf8(POSIX::strftime($format, localtime($time)));
517 sub beautify_url ($) { #{{{
520 if ($config{usedirs}) {
521 $url =~ s!/index.$config{htmlext}$!/!;
523 $url =~ s!^$!./!; # Browsers don't like empty links...
528 sub urlto ($$) { #{{{
533 return beautify_url(baseurl($from));
536 if (! $destsources{$to}) {
540 my $link = abs2rel($to, dirname(htmlpage($from)));
542 return beautify_url($link);
545 sub htmllink ($$$;@) { #{{{
546 my $lpage=shift; # the page doing the linking
547 my $page=shift; # the page that will contain the link (different for inline)
554 if (! $opts{forcesubpage}) {
555 $bestlink=bestlink($lpage, $link);
558 $bestlink="$lpage/".lc($link);
562 if (defined $opts{linktext}) {
563 $linktext=$opts{linktext};
566 $linktext=pagetitle(basename($link));
569 return "<span class=\"selflink\">$linktext</span>"
570 if length $bestlink && $page eq $bestlink &&
571 ! defined $opts{anchor};
573 if (! $destsources{$bestlink}) {
574 $bestlink=htmlpage($bestlink);
576 if (! $destsources{$bestlink}) {
577 return $linktext unless length $config{cgiurl};
578 return "<span class=\"createlink\"><a href=\"".
581 page => pagetitle(lc($link), 1),
584 "\">?</a>$linktext</span>"
588 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
589 $bestlink=beautify_url($bestlink);
591 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
592 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
595 if (defined $opts{anchor}) {
596 $bestlink.="#".$opts{anchor};
600 if (defined $opts{rel}) {
601 push @attrs, ' rel="'.$opts{rel}.'"';
603 if (defined $opts{class}) {
604 push @attrs, ' class="'.$opts{class}.'"';
607 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
610 sub openiduser ($) { #{{{
613 if ($user =~ m!^https?://! &&
614 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
615 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
616 my $display=$oid->display;
617 # Convert "user.somehost.com" to "user [somehost.com]".
618 if ($display !~ /\[/) {
619 $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
621 # Convert "http://somehost.com/user" to "user [somehost.com]".
622 if ($display !~ /\[/) {
623 $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
625 $display=~s!^https?://!!; # make sure this is removed
626 eval q{use CGI 'escapeHTML'};
628 return escapeHTML($display);
633 sub userlink ($) { #{{{
636 my $oiduser=openiduser($user);
637 if (defined $oiduser) {
638 return "<a href=\"$user\">$oiduser</a>";
641 return htmllink("", "", escapeHTML(
642 length $config{userdir} ? $config{userdir}."/".$user : $user
643 ), noimageinline => 1);
647 sub htmlize ($$$) { #{{{
652 my $oneline = $content !~ /\n/;
654 if (exists $hooks{htmlize}{$type}) {
655 $content=$hooks{htmlize}{$type}{call}->(
661 error("htmlization of $type not supported");
664 run_hooks(sanitize => sub {
672 # hack to get rid of enclosing junk added by markdown
673 # and other htmlizers
675 $content=~s/<\/p>$//i;
682 sub linkify ($$$) { #{{{
683 my $lpage=shift; # the page containing the links
684 my $page=shift; # the page the link will end up on (different for inline)
687 $content =~ s{(\\?)$config{wiki_link_regexp}}{
690 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
691 : htmllink($lpage, $page, linkpage($3),
692 anchor => $4, linktext => pagetitle($2)))
694 ? "[[$3".($4 ? "#$4" : "")."]]"
695 : htmllink($lpage, $page, linkpage($3),
703 our $preprocess_preview=0;
704 sub preprocess ($$$;$$) { #{{{
705 my $page=shift; # the page the data comes from
706 my $destpage=shift; # the page the data will appear in (different for inline)
711 # Using local because it needs to be set within any nested calls
713 local $preprocess_preview=$preview if defined $preview;
719 if (length $escape) {
720 return "[[$command $params]]";
722 elsif (exists $hooks{preprocess}{$command}) {
723 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
724 # Note: preserve order of params, some plugins may
725 # consider it significant.
728 (?:([-\w]+)=)? # 1: named parameter key?
730 """(.*?)""" # 2: triple-quoted value
732 "([^"]+)" # 3: single-quoted value
734 (\S+) # 4: unquoted value
736 (?:\s+|$) # delimiter to next param
754 push @params, $key, $val;
757 push @params, $val, '';
760 if ($preprocessing{$page}++ > 3) {
761 # Avoid loops of preprocessed pages preprocessing
762 # other pages that preprocess them, etc.
763 #translators: The first parameter is a
764 #translators: preprocessor directive name,
765 #translators: the second a page name, the
766 #translators: third a number.
767 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
768 $command, $page, $preprocessing{$page}).
773 $ret=$hooks{preprocess}{$command}{call}->(
776 destpage => $destpage,
777 preview => $preprocess_preview,
781 # use void context during scan pass
782 $hooks{preprocess}{$command}{call}->(
785 destpage => $destpage,
786 preview => $preprocess_preview,
790 $preprocessing{$page}--;
794 return "[[$command $params]]";
800 \[\[ # directive open
801 ([-\w]+) # 2: command
803 ( # 3: the parameters..
805 (?:[-\w]+=)? # named parameter key?
807 """.*?""" # triple-quoted value
809 "[^"]+" # single-quoted value
811 [^\s\]]+ # unquoted value
813 \s* # whitespace or end
816 *) # 0 or more parameters
817 \]\] # directive closed
818 }{$handle->($1, $2, $3)}sexg;
822 sub filter ($$$) { #{{{
827 run_hooks(filter => sub {
828 $content=shift->(page => $page, destpage => $destpage,
829 content => $content);
835 sub indexlink () { #{{{
836 return "<a href=\"$config{url}\">$config{wikiname}</a>";
841 sub lockwiki (;$) { #{{{
842 my $wait=@_ ? shift : 1;
843 # Take an exclusive lock on the wiki to prevent multiple concurrent
844 # run issues. The lock will be dropped on program exit.
845 if (! -d $config{wikistatedir}) {
846 mkdir($config{wikistatedir});
848 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
849 error ("cannot write to $config{wikistatedir}/lockfile: $!");
850 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
852 debug("wiki seems to be locked, waiting for lock");
853 my $wait=600; # arbitrary, but don't hang forever to
854 # prevent process pileup
856 return if flock($wikilock, 2 | 4);
859 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
868 sub unlockwiki () { #{{{
869 return close($wikilock) if $wikilock;
875 sub commit_hook_enabled () { #{{{
876 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
877 error("cannot write to $config{wikistatedir}/commitlock: $!");
878 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
879 close($commitlock) || error("failed closing commitlock: $!");
882 close($commitlock) || error("failed closing commitlock: $!");
886 sub disable_commit_hook () { #{{{
887 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
888 error("cannot write to $config{wikistatedir}/commitlock: $!");
889 if (! flock($commitlock, 2)) { # LOCK_EX
890 error("failed to get commit lock");
895 sub enable_commit_hook () { #{{{
896 return close($commitlock) if $commitlock;
900 sub loadindex () { #{{{
901 %oldrenderedfiles=%pagectime=();
902 if (! $config{rebuild}) {
903 %pagesources=%pagemtime=%oldlinks=%links=%depends=
904 %destsources=%renderedfiles=%pagecase=();
906 open (my $in, "<", "$config{wikistatedir}/index") || return;
908 $_=possibly_foolish_untaint($_);
913 foreach my $i (split(/ /, $_)) {
914 my ($item, $val)=split(/=/, $i, 2);
915 push @{$items{$item}}, decode_entities($val);
918 next unless exists $items{src}; # skip bad lines for now
920 my $page=pagename($items{src}[0]);
921 if (! $config{rebuild}) {
922 $pagesources{$page}=$items{src}[0];
923 $pagemtime{$page}=$items{mtime}[0];
924 $oldlinks{$page}=[@{$items{link}}];
925 $links{$page}=[@{$items{link}}];
926 $depends{$page}=$items{depends}[0] if exists $items{depends};
927 $destsources{$_}=$page foreach @{$items{dest}};
928 $renderedfiles{$page}=[@{$items{dest}}];
929 $pagecase{lc $page}=$page;
930 foreach my $k (grep /_/, keys %items) {
931 my ($id, $key)=split(/_/, $k, 2);
932 $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
935 $oldrenderedfiles{$page}=[@{$items{dest}}];
936 $pagectime{$page}=$items{ctime}[0];
941 sub saveindex () { #{{{
942 run_hooks(savestate => sub { shift->() });
945 foreach my $type (keys %hooks) {
946 $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
948 my @hookids=sort keys %hookids;
950 if (! -d $config{wikistatedir}) {
951 mkdir($config{wikistatedir});
953 my $newfile="$config{wikistatedir}/index.new";
954 my $cleanup = sub { unlink($newfile) };
955 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
956 foreach my $page (keys %pagemtime) {
957 next unless $pagemtime{$page};
958 my $line="mtime=$pagemtime{$page} ".
959 "ctime=$pagectime{$page} ".
960 "src=$pagesources{$page}";
961 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
963 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
964 if (exists $depends{$page}) {
965 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
967 if (exists $pagestate{$page}) {
968 foreach my $id (@hookids) {
969 foreach my $key (keys %{$pagestate{$page}{$id}}) {
970 $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key});
974 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
976 close $out || error("failed saving to $newfile: $!", $cleanup);
977 rename($newfile, "$config{wikistatedir}/index") ||
978 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
983 sub template_file ($) { #{{{
986 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
987 return "$dir/$template" if -e "$dir/$template";
992 sub template_params (@) { #{{{
993 my $filename=template_file(shift);
995 if (! defined $filename) {
1002 my $text_ref = shift;
1003 ${$text_ref} = decode_utf8(${$text_ref});
1005 filename => $filename,
1006 loop_context_vars => 1,
1007 die_on_bad_params => 0,
1010 return wantarray ? @ret : {@ret};
1013 sub template ($;@) { #{{{
1014 require HTML::Template;
1015 return HTML::Template->new(template_params(@_));
1018 sub misctemplate ($$;@) { #{{{
1022 my $template=template("misc.tmpl");
1025 indexlink => indexlink(),
1026 wikiname => $config{wikiname},
1027 pagebody => $pagebody,
1028 baseurl => baseurl(),
1031 run_hooks(pagetemplate => sub {
1032 shift->(page => "", destpage => "", template => $template);
1034 return $template->output;
1037 sub hook (@) { # {{{
1040 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1041 error 'hook requires type, call, and id parameters';
1044 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1046 $hooks{$param{type}}{$param{id}}=\%param;
1050 sub run_hooks ($$) { # {{{
1051 # Calls the given sub for each hook of the given type,
1052 # passing it the hook function to call.
1056 if (exists $hooks{$type}) {
1058 foreach my $id (keys %{$hooks{$type}}) {
1059 if ($hooks{$type}{$id}{last}) {
1060 push @deferred, $id;
1063 $sub->($hooks{$type}{$id}{call});
1065 foreach my $id (@deferred) {
1066 $sub->($hooks{$type}{$id}{call});
1073 sub globlist_to_pagespec ($) { #{{{
1074 my @globlist=split(' ', shift);
1077 foreach my $glob (@globlist) {
1078 if ($glob=~/^!(.*)/) {
1086 my $spec=join(' or ', @spec);
1088 my $skip=join(' and ', @skip);
1090 $spec="$skip and ($spec)";
1099 sub is_globlist ($) { #{{{
1101 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1104 sub safequote ($) { #{{{
1110 sub add_depends ($$) { #{{{
1114 if (! exists $depends{$page}) {
1115 $depends{$page}=$pagespec;
1118 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1124 sub file_pruned ($$) { #{{{
1126 my $file=File::Spec->canonpath(shift);
1127 my $base=File::Spec->canonpath(shift);
1128 $file =~ s#^\Q$base\E/+##;
1130 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1131 return $file =~ m/$regexp/ && $file ne $base;
1135 # Only use gettext in the rare cases it's needed.
1136 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1137 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1138 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1139 if (! $gettext_obj) {
1140 $gettext_obj=eval q{
1141 use Locale::gettext q{textdomain};
1142 Locale::gettext->domain('ikiwiki')
1150 return $gettext_obj->get(shift);
1157 sub pagespec_merge ($$) { #{{{
1161 return $a if $a eq $b;
1163 # Support for old-style GlobLists.
1164 if (is_globlist($a)) {
1165 $a=globlist_to_pagespec($a);
1167 if (is_globlist($b)) {
1168 $b=globlist_to_pagespec($b);
1171 return "($a) or ($b)";
1174 sub pagespec_translate ($) { #{{{
1175 # This assumes that $page is in scope in the function
1176 # that evalulates the translated pagespec code.
1179 # Support for old-style GlobLists.
1180 if (is_globlist($spec)) {
1181 $spec=globlist_to_pagespec($spec);
1184 # Convert spec to perl code.
1187 \s* # ignore whitespace
1188 ( # 1: match a single word
1195 \w+\([^\)]*\) # command(params)
1197 [^\s()]+ # any other text
1199 \s* # ignore whitespace
1202 if (lc $word eq 'and') {
1205 elsif (lc $word eq 'or') {
1208 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1211 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1212 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1213 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1220 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1227 sub pagespec_match ($$;@) { #{{{
1232 # Backwards compatability with old calling convention.
1234 unshift @params, 'location';
1237 my $ret=eval pagespec_translate($spec);
1238 return IkiWiki::FailReason->new('syntax error') if $@;
1242 package IkiWiki::FailReason;
1245 '""' => sub { ${$_[0]} },
1247 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1252 return bless \$_[1], $_[0];
1255 package IkiWiki::SuccessReason;
1258 '""' => sub { ${$_[0]} },
1260 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1265 return bless \$_[1], $_[0];
1268 package IkiWiki::PageSpec;
1270 sub match_glob ($$;@) { #{{{
1275 my $from=exists $params{location} ? $params{location} : '';
1278 if ($glob =~ m!^\./!) {
1279 $from=~s#/?[^/]+$##;
1281 $glob="$from/$glob" if length $from;
1284 # turn glob into safe regexp
1285 $glob=quotemeta($glob);
1289 if ($page=~/^$glob$/i) {
1290 return IkiWiki::SuccessReason->new("$glob matches $page");
1293 return IkiWiki::FailReason->new("$glob does not match $page");
1297 sub match_link ($$;@) { #{{{
1302 my $from=exists $params{location} ? $params{location} : '';
1305 if ($link =~ m!^\.! && defined $from) {
1306 $from=~s#/?[^/]+$##;
1308 $link="$from/$link" if length $from;
1311 my $links = $IkiWiki::links{$page};
1312 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1313 my $bestlink = IkiWiki::bestlink($from, $link);
1314 foreach my $p (@{$links}) {
1315 if (length $bestlink) {
1316 return IkiWiki::SuccessReason->new("$page links to $link")
1317 if $bestlink eq IkiWiki::bestlink($page, $p);
1320 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1321 if match_glob($p, $link, %params);
1324 return IkiWiki::FailReason->new("$page does not link to $link");
1327 sub match_backlink ($$;@) { #{{{
1328 return match_link($_[1], $_[0], @_);
1331 sub match_created_before ($$;@) { #{{{
1335 if (exists $IkiWiki::pagectime{$testpage}) {
1336 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1337 return IkiWiki::SuccessReason->new("$page created before $testpage");
1340 return IkiWiki::FailReason->new("$page not created before $testpage");
1344 return IkiWiki::FailReason->new("$testpage has no ctime");
1348 sub match_created_after ($$;@) { #{{{
1352 if (exists $IkiWiki::pagectime{$testpage}) {
1353 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1354 return IkiWiki::SuccessReason->new("$page created after $testpage");
1357 return IkiWiki::FailReason->new("$page not created after $testpage");
1361 return IkiWiki::FailReason->new("$testpage has no ctime");
1365 sub match_creation_day ($$;@) { #{{{
1366 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1367 return IkiWiki::SuccessReason->new('creation_day matched');
1370 return IkiWiki::FailReason->new('creation_day did not match');
1374 sub match_creation_month ($$;@) { #{{{
1375 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1376 return IkiWiki::SuccessReason->new('creation_month matched');
1379 return IkiWiki::FailReason->new('creation_month did not match');
1383 sub match_creation_year ($$;@) { #{{{
1384 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1385 return IkiWiki::SuccessReason->new('creation_year matched');
1388 return IkiWiki::FailReason->new('creation_year did not match');
1392 sub match_user ($$;@) { #{{{
1397 return IkiWiki::FailReason->new('cannot match user')
1398 unless exists $params{user};
1399 if ($user eq $params{user}) {
1400 return IkiWiki::SuccessReason->new("user is $user")
1403 return IkiWiki::FailReason->new("user is not $user");