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 ([^\]\|]+) # 1: link text
47 ([^\]#]+) # 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",
81 gitorigin_branch => "origin",
82 gitmaster_branch => "master",
86 templatedir => "$installdir/share/ikiwiki/templates",
87 underlaydir => "$installdir/share/ikiwiki/basewiki",
92 plugin => [qw{mdwn inline htmlscrubber passwordauth openid signinedit
93 lockedit conditional recentchanges}],
102 account_creation_password => "",
103 prefix_directives => 0,
106 sub checkconfig () { #{{{
107 # locale stuff; avoid LC_ALL since it overrides everything
108 if (defined $ENV{LC_ALL}) {
109 $ENV{LANG} = $ENV{LC_ALL};
112 if (defined $config{locale}) {
113 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
114 $ENV{LANG}=$config{locale};
119 if ($config{w3mmode}) {
120 eval q{use Cwd q{abs_path}};
122 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
123 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
124 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
125 unless $config{cgiurl} =~ m!file:///!;
126 $config{url}="file://".$config{destdir};
129 if ($config{cgi} && ! length $config{url}) {
130 error(gettext("Must specify url to wiki with --url when using --cgi"));
133 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
134 unless exists $config{wikistatedir};
137 eval qq{use IkiWiki::Rcs::$config{rcs}};
139 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
143 require IkiWiki::Rcs::Stub;
146 if (exists $config{umask}) {
147 umask(possibly_foolish_untaint($config{umask}));
150 if (!$config{prefix_directives}) {
151 $config{wiki_link_regexp} = qr{
152 \[\[ # beginning of link
154 ([^\]\|\n\s]+) # 1: link text
158 ([^\s\]#]+) # 2: page to link to
160 \# # '#', beginning of anchor
161 ([^\s\]]+) # 3: anchor text
168 run_hooks(checkconfig => sub { shift->() });
173 sub loadplugins () { #{{{
174 if (defined $config{libdir}) {
175 unshift @INC, possibly_foolish_untaint($config{libdir});
178 loadplugin($_) foreach @{$config{plugin}};
180 run_hooks(getopt => sub { shift->() });
181 if (grep /^-/, @ARGV) {
182 print STDERR "Unknown option: $_\n"
183 foreach grep /^-/, @ARGV;
190 sub loadplugin ($) { #{{{
193 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
195 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
196 "$installdir/lib/ikiwiki") {
197 if (defined $dir && -x "$dir/plugins/$plugin") {
198 require IkiWiki::Plugin::external;
199 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
204 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
207 error("Failed to load plugin $mod: $@");
212 sub error ($;$) { #{{{
216 print "Content-type: text/html\n\n";
217 print misctemplate(gettext("Error"),
218 "<p>".gettext("Error").": $message</p>");
220 log_message('err' => $message) if $config{syslog};
221 if (defined $cleaner) {
228 return unless $config{verbose};
229 return log_message(debug => @_);
233 sub log_message ($$) { #{{{
236 if ($config{syslog}) {
239 Sys::Syslog::setlogsock('unix');
240 Sys::Syslog::openlog('ikiwiki', '', 'user');
244 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
247 elsif (! $config{cgi}) {
251 return print STDERR "@_\n";
255 sub possibly_foolish_untaint ($) { #{{{
257 my ($untainted)=$tainted=~/(.*)/s;
261 sub basename ($) { #{{{
268 sub dirname ($) { #{{{
275 sub pagetype ($) { #{{{
278 if ($page =~ /\.([^.]+)$/) {
279 return $1 if exists $hooks{htmlize}{$1};
284 sub isinternal ($) { #{{{
286 return exists $pagesources{$page} &&
287 $pagesources{$page} =~ /\._([^.]+)$/;
290 sub pagename ($) { #{{{
293 my $type=pagetype($file);
295 $page=~s/\Q.$type\E*$// if defined $type;
299 sub targetpage ($$) { #{{{
303 if (! $config{usedirs} || $page =~ /^index$/ ) {
304 return $page.".".$ext;
306 return $page."/index.".$ext;
310 sub htmlpage ($) { #{{{
313 return targetpage($page, $config{htmlext});
316 sub srcfile ($) { #{{{
319 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
320 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
321 return "$dir/$file" if -e "$dir/$file";
323 error("internal error: $file cannot be found in $config{srcdir} or underlay");
327 sub add_underlay ($) { #{{{
331 unshift @{$config{underlaydirs}}, $dir;
334 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
340 sub readfile ($;$$) { #{{{
346 error("cannot read a symlink ($file)");
350 open (my $in, "<", $file) || error("failed to read $file: $!");
351 binmode($in) if ($binary);
352 return \*$in if $wantfd;
354 close $in || error("failed to read $file: $!");
358 sub writefile ($$$;$$) { #{{{
359 my $file=shift; # can include subdirs
360 my $destdir=shift; # directory to put file in
366 while (length $test) {
367 if (-l "$destdir/$test") {
368 error("cannot write to a symlink ($test)");
370 $test=dirname($test);
372 my $newfile="$destdir/$file.ikiwiki-new";
374 error("cannot write to a symlink ($newfile)");
377 my $dir=dirname($newfile);
380 foreach my $s (split(m!/+!, $dir)) {
383 mkdir($d) || error("failed to create directory $d: $!");
388 my $cleanup = sub { unlink($newfile) };
389 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
390 binmode($out) if ($binary);
392 $writer->(\*$out, $cleanup);
395 print $out $content or error("failed writing to $newfile: $!", $cleanup);
397 close $out || error("failed saving $newfile: $!", $cleanup);
398 rename($newfile, "$destdir/$file") ||
399 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
405 sub will_render ($$;$) { #{{{
410 # Important security check.
411 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
412 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
413 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
416 if (! $clear || $cleared{$page}) {
417 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
420 foreach my $old (@{$renderedfiles{$page}}) {
421 delete $destsources{$old};
423 $renderedfiles{$page}=[$dest];
426 $destsources{$dest}=$page;
431 sub bestlink ($$) { #{{{
436 if ($link=~s/^\/+//) {
444 $l.="/" if length $l;
447 if (exists $links{$l}) {
450 elsif (exists $pagecase{lc $l}) {
451 return $pagecase{lc $l};
453 } while $cwd=~s!/?[^/]+$!!;
455 if (length $config{userdir}) {
456 my $l = "$config{userdir}/".lc($link);
457 if (exists $links{$l}) {
460 elsif (exists $pagecase{lc $l}) {
461 return $pagecase{lc $l};
465 #print STDERR "warning: page $page, broken link: $link\n";
469 sub isinlinableimage ($) { #{{{
472 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
475 sub pagetitle ($;$) { #{{{
480 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
483 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
489 sub titlepage ($) { #{{{
491 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
495 sub linkpage ($) { #{{{
497 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
501 sub cgiurl (@) { #{{{
504 return $config{cgiurl}."?".
505 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
508 sub baseurl (;$) { #{{{
511 return "$config{url}/" if ! defined $page;
513 $page=htmlpage($page);
515 $page=~s/[^\/]+\//..\//g;
519 sub abs2rel ($$) { #{{{
520 # Work around very innefficient behavior in File::Spec if abs2rel
521 # is passed two relative paths. It's much faster if paths are
522 # absolute! (Debian bug #376658; fixed in debian unstable now)
527 my $ret=File::Spec->abs2rel($path, $base);
528 $ret=~s/^// if defined $ret;
532 sub displaytime ($;$) { #{{{
535 if (! defined $format) {
536 $format=$config{timeformat};
539 # strftime doesn't know about encodings, so make sure
540 # its output is properly treated as utf8
541 return decode_utf8(POSIX::strftime($format, localtime($time)));
544 sub beautify_url ($) { #{{{
547 if ($config{usedirs}) {
548 $url =~ s!/index.$config{htmlext}$!/!;
550 $url =~ s!^$!./!; # Browsers don't like empty links...
555 sub urlto ($$) { #{{{
560 return beautify_url(baseurl($from));
563 if (! $destsources{$to}) {
567 my $link = abs2rel($to, dirname(htmlpage($from)));
569 return beautify_url($link);
572 sub htmllink ($$$;@) { #{{{
573 my $lpage=shift; # the page doing the linking
574 my $page=shift; # the page that will contain the link (different for inline)
581 if (! $opts{forcesubpage}) {
582 $bestlink=bestlink($lpage, $link);
585 $bestlink="$lpage/".lc($link);
589 if (defined $opts{linktext}) {
590 $linktext=$opts{linktext};
593 $linktext=pagetitle(basename($link));
596 return "<span class=\"selflink\">$linktext</span>"
597 if length $bestlink && $page eq $bestlink &&
598 ! defined $opts{anchor};
600 if (! $destsources{$bestlink}) {
601 $bestlink=htmlpage($bestlink);
603 if (! $destsources{$bestlink}) {
604 return $linktext unless length $config{cgiurl};
605 return "<span class=\"createlink\"><a href=\"".
608 page => pagetitle(lc($link), 1),
611 "\">?</a>$linktext</span>"
615 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
616 $bestlink=beautify_url($bestlink);
618 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
619 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
622 if (defined $opts{anchor}) {
623 $bestlink.="#".$opts{anchor};
627 if (defined $opts{rel}) {
628 push @attrs, ' rel="'.$opts{rel}.'"';
630 if (defined $opts{class}) {
631 push @attrs, ' class="'.$opts{class}.'"';
634 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
637 sub userlink ($) { #{{{
640 my $oiduser=eval { openiduser($user) };
641 if (defined $oiduser) {
642 return "<a href=\"$user\">$oiduser</a>";
645 return htmllink("", "", escapeHTML(
646 length $config{userdir} ? $config{userdir}."/".$user : $user
647 ), noimageinline => 1);
651 sub htmlize ($$$) { #{{{
656 my $oneline = $content !~ /\n/;
658 if (exists $hooks{htmlize}{$type}) {
659 $content=$hooks{htmlize}{$type}{call}->(
665 error("htmlization of $type not supported");
668 run_hooks(sanitize => sub {
676 # hack to get rid of enclosing junk added by markdown
677 # and other htmlizers
679 $content=~s/<\/p>$//i;
686 sub linkify ($$$) { #{{{
687 my $lpage=shift; # the page containing the links
688 my $page=shift; # the page the link will end up on (different for inline)
691 $content =~ s{(\\?)$config{wiki_link_regexp}}{
694 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
695 : htmllink($lpage, $page, linkpage($3),
696 anchor => $4, linktext => pagetitle($2)))
698 ? "[[$3".($4 ? "#$4" : "")."]]"
699 : htmllink($lpage, $page, linkpage($3),
707 our $preprocess_preview=0;
708 sub preprocess ($$$;$$) { #{{{
709 my $page=shift; # the page the data comes from
710 my $destpage=shift; # the page the data will appear in (different for inline)
715 # Using local because it needs to be set within any nested calls
717 local $preprocess_preview=$preview if defined $preview;
724 if (length $escape) {
725 return "[[$prefix$command $params]]";
727 elsif (exists $hooks{preprocess}{$command}) {
728 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
729 # Note: preserve order of params, some plugins may
730 # consider it significant.
733 (?:([-\w]+)=)? # 1: named parameter key?
735 """(.*?)""" # 2: triple-quoted value
737 "([^"]+)" # 3: single-quoted value
739 (\S+) # 4: unquoted value
741 (?:\s+|$) # delimiter to next param
759 push @params, $key, $val;
762 push @params, $val, '';
765 if ($preprocessing{$page}++ > 3) {
766 # Avoid loops of preprocessed pages preprocessing
767 # other pages that preprocess them, etc.
768 #translators: The first parameter is a
769 #translators: preprocessor directive name,
770 #translators: the second a page name, the
771 #translators: third a number.
772 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
773 $command, $page, $preprocessing{$page}).
778 $ret=$hooks{preprocess}{$command}{call}->(
781 destpage => $destpage,
782 preview => $preprocess_preview,
786 # use void context during scan pass
787 $hooks{preprocess}{$command}{call}->(
790 destpage => $destpage,
791 preview => $preprocess_preview,
795 $preprocessing{$page}--;
799 return "[[$prefix$command $params]]";
804 if ($config{prefix_directives}) {
807 \[\[(!) # directive open; 2: prefix
808 ([-\w]+) # 3: command
809 ( # 4: the parameters..
810 \s+ # Must have space if parameters present
812 (?:[-\w]+=)? # named parameter key?
814 """.*?""" # triple-quoted value
816 "[^"]+" # single-quoted value
818 [^\s\]]+ # unquoted value
820 \s* # whitespace or end
823 *)? # 0 or more parameters
824 \]\] # directive closed
829 \[\[(!?) # directive open; 2: optional prefix
830 ([-\w]+) # 3: command
832 ( # 4: the parameters..
834 (?:[-\w]+=)? # named parameter key?
836 """.*?""" # triple-quoted value
838 "[^"]+" # single-quoted value
840 [^\s\]]+ # unquoted value
842 \s* # whitespace or end
845 *) # 0 or more parameters
846 \]\] # directive closed
850 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
854 sub filter ($$$) { #{{{
859 run_hooks(filter => sub {
860 $content=shift->(page => $page, destpage => $destpage,
861 content => $content);
867 sub indexlink () { #{{{
868 return "<a href=\"$config{url}\">$config{wikiname}</a>";
873 sub lockwiki (;$) { #{{{
874 my $wait=@_ ? shift : 1;
875 # Take an exclusive lock on the wiki to prevent multiple concurrent
876 # run issues. The lock will be dropped on program exit.
877 if (! -d $config{wikistatedir}) {
878 mkdir($config{wikistatedir});
880 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
881 error ("cannot write to $config{wikistatedir}/lockfile: $!");
882 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
884 debug("wiki seems to be locked, waiting for lock");
885 my $wait=600; # arbitrary, but don't hang forever to
886 # prevent process pileup
888 return if flock($wikilock, 2 | 4);
891 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
900 sub unlockwiki () { #{{{
901 return close($wikilock) if $wikilock;
907 sub commit_hook_enabled () { #{{{
908 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
909 error("cannot write to $config{wikistatedir}/commitlock: $!");
910 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
911 close($commitlock) || error("failed closing commitlock: $!");
914 close($commitlock) || error("failed closing commitlock: $!");
918 sub disable_commit_hook () { #{{{
919 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
920 error("cannot write to $config{wikistatedir}/commitlock: $!");
921 if (! flock($commitlock, 2)) { # LOCK_EX
922 error("failed to get commit lock");
927 sub enable_commit_hook () { #{{{
928 return close($commitlock) if $commitlock;
932 sub loadindex () { #{{{
933 %oldrenderedfiles=%pagectime=();
934 if (! $config{rebuild}) {
935 %pagesources=%pagemtime=%oldlinks=%links=%depends=
936 %destsources=%renderedfiles=%pagecase=%pagestate=();
938 open (my $in, "<", "$config{wikistatedir}/index") || return;
940 $_=possibly_foolish_untaint($_);
945 foreach my $i (split(/ /, $_)) {
946 my ($item, $val)=split(/=/, $i, 2);
947 push @{$items{$item}}, decode_entities($val);
950 next unless exists $items{src}; # skip bad lines for now
952 my $page=pagename($items{src}[0]);
953 if (! $config{rebuild}) {
954 $pagesources{$page}=$items{src}[0];
955 $pagemtime{$page}=$items{mtime}[0];
956 $oldlinks{$page}=[@{$items{link}}];
957 $links{$page}=[@{$items{link}}];
958 $depends{$page}=$items{depends}[0] if exists $items{depends};
959 $destsources{$_}=$page foreach @{$items{dest}};
960 $renderedfiles{$page}=[@{$items{dest}}];
961 $pagecase{lc $page}=$page;
962 foreach my $k (grep /_/, keys %items) {
963 my ($id, $key)=split(/_/, $k, 2);
964 $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
967 $oldrenderedfiles{$page}=[@{$items{dest}}];
968 $pagectime{$page}=$items{ctime}[0];
973 sub saveindex () { #{{{
974 run_hooks(savestate => sub { shift->() });
977 foreach my $type (keys %hooks) {
978 $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
980 my @hookids=sort keys %hookids;
982 if (! -d $config{wikistatedir}) {
983 mkdir($config{wikistatedir});
985 my $newfile="$config{wikistatedir}/index.new";
986 my $cleanup = sub { unlink($newfile) };
987 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
988 foreach my $page (keys %pagemtime) {
989 next unless $pagemtime{$page};
990 my $line="mtime=$pagemtime{$page} ".
991 "ctime=$pagectime{$page} ".
992 "src=$pagesources{$page}";
993 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
995 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
996 if (exists $depends{$page}) {
997 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
999 if (exists $pagestate{$page}) {
1000 foreach my $id (@hookids) {
1001 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1002 $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key}, " \t\n");
1006 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
1008 close $out || error("failed saving to $newfile: $!", $cleanup);
1009 rename($newfile, "$config{wikistatedir}/index") ||
1010 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
1015 sub template_file ($) { #{{{
1018 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1019 return "$dir/$template" if -e "$dir/$template";
1024 sub template_params (@) { #{{{
1025 my $filename=template_file(shift);
1027 if (! defined $filename) {
1028 return if wantarray;
1034 my $text_ref = shift;
1035 ${$text_ref} = decode_utf8(${$text_ref});
1037 filename => $filename,
1038 loop_context_vars => 1,
1039 die_on_bad_params => 0,
1042 return wantarray ? @ret : {@ret};
1045 sub template ($;@) { #{{{
1046 require HTML::Template;
1047 return HTML::Template->new(template_params(@_));
1050 sub misctemplate ($$;@) { #{{{
1054 my $template=template("misc.tmpl");
1057 indexlink => indexlink(),
1058 wikiname => $config{wikiname},
1059 pagebody => $pagebody,
1060 baseurl => baseurl(),
1063 run_hooks(pagetemplate => sub {
1064 shift->(page => "", destpage => "", template => $template);
1066 return $template->output;
1069 sub hook (@) { # {{{
1072 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1073 error 'hook requires type, call, and id parameters';
1076 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1078 $hooks{$param{type}}{$param{id}}=\%param;
1082 sub run_hooks ($$) { # {{{
1083 # Calls the given sub for each hook of the given type,
1084 # passing it the hook function to call.
1088 if (exists $hooks{$type}) {
1090 foreach my $id (keys %{$hooks{$type}}) {
1091 if ($hooks{$type}{$id}{last}) {
1092 push @deferred, $id;
1095 $sub->($hooks{$type}{$id}{call});
1097 foreach my $id (@deferred) {
1098 $sub->($hooks{$type}{$id}{call});
1105 sub globlist_to_pagespec ($) { #{{{
1106 my @globlist=split(' ', shift);
1109 foreach my $glob (@globlist) {
1110 if ($glob=~/^!(.*)/) {
1118 my $spec=join(' or ', @spec);
1120 my $skip=join(' and ', @skip);
1122 $spec="$skip and ($spec)";
1131 sub is_globlist ($) { #{{{
1133 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1136 sub safequote ($) { #{{{
1142 sub add_depends ($$) { #{{{
1146 if (! exists $depends{$page}) {
1147 $depends{$page}=$pagespec;
1150 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1156 sub file_pruned ($$) { #{{{
1158 my $file=File::Spec->canonpath(shift);
1159 my $base=File::Spec->canonpath(shift);
1160 $file =~ s#^\Q$base\E/+##;
1162 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1163 return $file =~ m/$regexp/ && $file ne $base;
1167 # Only use gettext in the rare cases it's needed.
1168 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1169 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1170 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1171 if (! $gettext_obj) {
1172 $gettext_obj=eval q{
1173 use Locale::gettext q{textdomain};
1174 Locale::gettext->domain('ikiwiki')
1182 return $gettext_obj->get(shift);
1189 sub pagespec_merge ($$) { #{{{
1193 return $a if $a eq $b;
1195 # Support for old-style GlobLists.
1196 if (is_globlist($a)) {
1197 $a=globlist_to_pagespec($a);
1199 if (is_globlist($b)) {
1200 $b=globlist_to_pagespec($b);
1203 return "($a) or ($b)";
1206 sub pagespec_translate ($) { #{{{
1207 # This assumes that $page is in scope in the function
1208 # that evalulates the translated pagespec code.
1211 # Support for old-style GlobLists.
1212 if (is_globlist($spec)) {
1213 $spec=globlist_to_pagespec($spec);
1216 # Convert spec to perl code.
1219 \s* # ignore whitespace
1220 ( # 1: match a single word
1227 \w+\([^\)]*\) # command(params)
1229 [^\s()]+ # any other text
1231 \s* # ignore whitespace
1234 if (lc $word eq 'and') {
1237 elsif (lc $word eq 'or') {
1240 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1243 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1244 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1245 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1252 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1259 sub pagespec_match ($$;@) { #{{{
1264 # Backwards compatability with old calling convention.
1266 unshift @params, 'location';
1269 my $ret=eval pagespec_translate($spec);
1270 return IkiWiki::FailReason->new('syntax error') if $@;
1274 package IkiWiki::FailReason;
1277 '""' => sub { ${$_[0]} },
1279 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1284 return bless \$_[1], $_[0];
1287 package IkiWiki::SuccessReason;
1290 '""' => sub { ${$_[0]} },
1292 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1297 return bless \$_[1], $_[0];
1300 package IkiWiki::PageSpec;
1302 sub match_glob ($$;@) { #{{{
1307 my $from=exists $params{location} ? $params{location} : '';
1310 if ($glob =~ m!^\./!) {
1311 $from=~s#/?[^/]+$##;
1313 $glob="$from/$glob" if length $from;
1316 # turn glob into safe regexp
1317 $glob=quotemeta($glob);
1321 if ($page=~/^$glob$/i) {
1322 if (! IkiWiki::isinternal($page) || $params{internal}) {
1323 return IkiWiki::SuccessReason->new("$glob matches $page");
1326 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1330 return IkiWiki::FailReason->new("$glob does not match $page");
1334 sub match_internal ($$;@) { #{{{
1335 return match_glob($_[0], $_[1], @_, internal => 1)
1338 sub match_link ($$;@) { #{{{
1343 my $from=exists $params{location} ? $params{location} : '';
1346 if ($link =~ m!^\.! && defined $from) {
1347 $from=~s#/?[^/]+$##;
1349 $link="$from/$link" if length $from;
1352 my $links = $IkiWiki::links{$page};
1353 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1354 my $bestlink = IkiWiki::bestlink($from, $link);
1355 foreach my $p (@{$links}) {
1356 if (length $bestlink) {
1357 return IkiWiki::SuccessReason->new("$page links to $link")
1358 if $bestlink eq IkiWiki::bestlink($page, $p);
1361 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1362 if match_glob($p, $link, %params);
1365 return IkiWiki::FailReason->new("$page does not link to $link");
1368 sub match_backlink ($$;@) { #{{{
1369 return match_link($_[1], $_[0], @_);
1372 sub match_created_before ($$;@) { #{{{
1376 if (exists $IkiWiki::pagectime{$testpage}) {
1377 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1378 return IkiWiki::SuccessReason->new("$page created before $testpage");
1381 return IkiWiki::FailReason->new("$page not created before $testpage");
1385 return IkiWiki::FailReason->new("$testpage has no ctime");
1389 sub match_created_after ($$;@) { #{{{
1393 if (exists $IkiWiki::pagectime{$testpage}) {
1394 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1395 return IkiWiki::SuccessReason->new("$page created after $testpage");
1398 return IkiWiki::FailReason->new("$page not created after $testpage");
1402 return IkiWiki::FailReason->new("$testpage has no ctime");
1406 sub match_creation_day ($$;@) { #{{{
1407 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1408 return IkiWiki::SuccessReason->new('creation_day matched');
1411 return IkiWiki::FailReason->new('creation_day did not match');
1415 sub match_creation_month ($$;@) { #{{{
1416 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1417 return IkiWiki::SuccessReason->new('creation_month matched');
1420 return IkiWiki::FailReason->new('creation_month did not match');
1424 sub match_creation_year ($$;@) { #{{{
1425 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1426 return IkiWiki::SuccessReason->new('creation_year matched');
1429 return IkiWiki::FailReason->new('creation_year did not match');