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 isinternal ($) { #{{{
265 return exists $pagesources{$page} &&
266 $pagesources{$page} =~ /\._([^.]+)$/;
269 sub pagename ($) { #{{{
272 my $type=pagetype($file);
274 $page=~s/\Q.$type\E*$// if defined $type;
278 sub targetpage ($$) { #{{{
282 if (! $config{usedirs} || $page =~ /^index$/ ) {
283 return $page.".".$ext;
285 return $page."/index.".$ext;
289 sub htmlpage ($) { #{{{
292 return targetpage($page, $config{htmlext});
295 sub srcfile ($) { #{{{
298 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
299 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
300 return "$dir/$file" if -e "$dir/$file";
302 error("internal error: $file cannot be found in $config{srcdir} or underlay");
306 sub add_underlay ($) { #{{{
310 unshift @{$config{underlaydirs}}, $dir;
313 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
319 sub readfile ($;$$) { #{{{
325 error("cannot read a symlink ($file)");
329 open (my $in, "<", $file) || error("failed to read $file: $!");
330 binmode($in) if ($binary);
331 return \*$in if $wantfd;
333 close $in || error("failed to read $file: $!");
337 sub writefile ($$$;$$) { #{{{
338 my $file=shift; # can include subdirs
339 my $destdir=shift; # directory to put file in
345 while (length $test) {
346 if (-l "$destdir/$test") {
347 error("cannot write to a symlink ($test)");
349 $test=dirname($test);
351 my $newfile="$destdir/$file.ikiwiki-new";
353 error("cannot write to a symlink ($newfile)");
356 my $dir=dirname($newfile);
359 foreach my $s (split(m!/+!, $dir)) {
362 mkdir($d) || error("failed to create directory $d: $!");
367 my $cleanup = sub { unlink($newfile) };
368 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
369 binmode($out) if ($binary);
371 $writer->(\*$out, $cleanup);
374 print $out $content or error("failed writing to $newfile: $!", $cleanup);
376 close $out || error("failed saving $newfile: $!", $cleanup);
377 rename($newfile, "$destdir/$file") ||
378 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
384 sub will_render ($$;$) { #{{{
389 # Important security check.
390 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
391 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
392 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
395 if (! $clear || $cleared{$page}) {
396 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
399 foreach my $old (@{$renderedfiles{$page}}) {
400 delete $destsources{$old};
402 $renderedfiles{$page}=[$dest];
405 $destsources{$dest}=$page;
410 sub bestlink ($$) { #{{{
415 if ($link=~s/^\/+//) {
423 $l.="/" if length $l;
426 if (exists $links{$l}) {
429 elsif (exists $pagecase{lc $l}) {
430 return $pagecase{lc $l};
432 } while $cwd=~s!/?[^/]+$!!;
434 if (length $config{userdir}) {
435 my $l = "$config{userdir}/".lc($link);
436 if (exists $links{$l}) {
439 elsif (exists $pagecase{lc $l}) {
440 return $pagecase{lc $l};
444 #print STDERR "warning: page $page, broken link: $link\n";
448 sub isinlinableimage ($) { #{{{
451 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
454 sub pagetitle ($;$) { #{{{
459 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
462 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
468 sub titlepage ($) { #{{{
470 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
474 sub linkpage ($) { #{{{
476 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
480 sub cgiurl (@) { #{{{
483 return $config{cgiurl}."?".
484 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
487 sub baseurl (;$) { #{{{
490 return "$config{url}/" if ! defined $page;
492 $page=htmlpage($page);
494 $page=~s/[^\/]+\//..\//g;
498 sub abs2rel ($$) { #{{{
499 # Work around very innefficient behavior in File::Spec if abs2rel
500 # is passed two relative paths. It's much faster if paths are
501 # absolute! (Debian bug #376658; fixed in debian unstable now)
506 my $ret=File::Spec->abs2rel($path, $base);
507 $ret=~s/^// if defined $ret;
511 sub displaytime ($;$) { #{{{
514 if (! defined $format) {
515 $format=$config{timeformat};
518 # strftime doesn't know about encodings, so make sure
519 # its output is properly treated as utf8
520 return decode_utf8(POSIX::strftime($format, localtime($time)));
523 sub beautify_url ($) { #{{{
526 if ($config{usedirs}) {
527 $url =~ s!/index.$config{htmlext}$!/!;
529 $url =~ s!^$!./!; # Browsers don't like empty links...
534 sub urlto ($$) { #{{{
539 return beautify_url(baseurl($from));
542 if (! $destsources{$to}) {
546 my $link = abs2rel($to, dirname(htmlpage($from)));
548 return beautify_url($link);
551 sub htmllink ($$$;@) { #{{{
552 my $lpage=shift; # the page doing the linking
553 my $page=shift; # the page that will contain the link (different for inline)
560 if (! $opts{forcesubpage}) {
561 $bestlink=bestlink($lpage, $link);
564 $bestlink="$lpage/".lc($link);
568 if (defined $opts{linktext}) {
569 $linktext=$opts{linktext};
572 $linktext=pagetitle(basename($link));
575 return "<span class=\"selflink\">$linktext</span>"
576 if length $bestlink && $page eq $bestlink &&
577 ! defined $opts{anchor};
579 if (! $destsources{$bestlink}) {
580 $bestlink=htmlpage($bestlink);
582 if (! $destsources{$bestlink}) {
583 return $linktext unless length $config{cgiurl};
584 return "<span class=\"createlink\"><a href=\"".
587 page => pagetitle(lc($link), 1),
590 "\">?</a>$linktext</span>"
594 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
595 $bestlink=beautify_url($bestlink);
597 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
598 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
601 if (defined $opts{anchor}) {
602 $bestlink.="#".$opts{anchor};
606 if (defined $opts{rel}) {
607 push @attrs, ' rel="'.$opts{rel}.'"';
609 if (defined $opts{class}) {
610 push @attrs, ' class="'.$opts{class}.'"';
613 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
616 sub openiduser ($) { #{{{
619 if ($user =~ m!^https?://! &&
620 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
621 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
622 my $display=$oid->display;
623 # Convert "user.somehost.com" to "user [somehost.com]".
624 if ($display !~ /\[/) {
625 $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
627 # Convert "http://somehost.com/user" to "user [somehost.com]".
628 if ($display !~ /\[/) {
629 $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
631 $display=~s!^https?://!!; # make sure this is removed
632 eval q{use CGI 'escapeHTML'};
634 return escapeHTML($display);
639 sub userlink ($) { #{{{
642 my $oiduser=openiduser($user);
643 if (defined $oiduser) {
644 return "<a href=\"$user\">$oiduser</a>";
647 return htmllink("", "", escapeHTML(
648 length $config{userdir} ? $config{userdir}."/".$user : $user
649 ), noimageinline => 1);
653 sub htmlize ($$$) { #{{{
658 my $oneline = $content !~ /\n/;
660 if (exists $hooks{htmlize}{$type}) {
661 $content=$hooks{htmlize}{$type}{call}->(
667 error("htmlization of $type not supported");
670 run_hooks(sanitize => sub {
678 # hack to get rid of enclosing junk added by markdown
679 # and other htmlizers
681 $content=~s/<\/p>$//i;
688 sub linkify ($$$) { #{{{
689 my $lpage=shift; # the page containing the links
690 my $page=shift; # the page the link will end up on (different for inline)
693 $content =~ s{(\\?)$config{wiki_link_regexp}}{
696 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
697 : htmllink($lpage, $page, linkpage($3),
698 anchor => $4, linktext => pagetitle($2)))
700 ? "[[$3".($4 ? "#$4" : "")."]]"
701 : htmllink($lpage, $page, linkpage($3),
709 our $preprocess_preview=0;
710 sub preprocess ($$$;$$) { #{{{
711 my $page=shift; # the page the data comes from
712 my $destpage=shift; # the page the data will appear in (different for inline)
717 # Using local because it needs to be set within any nested calls
719 local $preprocess_preview=$preview if defined $preview;
725 if (length $escape) {
726 return "[[$command $params]]";
728 elsif (exists $hooks{preprocess}{$command}) {
729 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
730 # Note: preserve order of params, some plugins may
731 # consider it significant.
734 (?:([-\w]+)=)? # 1: named parameter key?
736 """(.*?)""" # 2: triple-quoted value
738 "([^"]+)" # 3: single-quoted value
740 (\S+) # 4: unquoted value
742 (?:\s+|$) # delimiter to next param
760 push @params, $key, $val;
763 push @params, $val, '';
766 if ($preprocessing{$page}++ > 3) {
767 # Avoid loops of preprocessed pages preprocessing
768 # other pages that preprocess them, etc.
769 #translators: The first parameter is a
770 #translators: preprocessor directive name,
771 #translators: the second a page name, the
772 #translators: third a number.
773 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
774 $command, $page, $preprocessing{$page}).
779 $ret=$hooks{preprocess}{$command}{call}->(
782 destpage => $destpage,
783 preview => $preprocess_preview,
787 # use void context during scan pass
788 $hooks{preprocess}{$command}{call}->(
791 destpage => $destpage,
792 preview => $preprocess_preview,
796 $preprocessing{$page}--;
800 return "[[$command $params]]";
806 \[\[ # directive open
807 ([-\w]+) # 2: command
809 ( # 3: the parameters..
811 (?:[-\w]+=)? # named parameter key?
813 """.*?""" # triple-quoted value
815 "[^"]+" # single-quoted value
817 [^\s\]]+ # unquoted value
819 \s* # whitespace or end
822 *) # 0 or more parameters
823 \]\] # directive closed
824 }{$handle->($1, $2, $3)}sexg;
828 sub filter ($$$) { #{{{
833 run_hooks(filter => sub {
834 $content=shift->(page => $page, destpage => $destpage,
835 content => $content);
841 sub indexlink () { #{{{
842 return "<a href=\"$config{url}\">$config{wikiname}</a>";
847 sub lockwiki (;$) { #{{{
848 my $wait=@_ ? shift : 1;
849 # Take an exclusive lock on the wiki to prevent multiple concurrent
850 # run issues. The lock will be dropped on program exit.
851 if (! -d $config{wikistatedir}) {
852 mkdir($config{wikistatedir});
854 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
855 error ("cannot write to $config{wikistatedir}/lockfile: $!");
856 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
858 debug("wiki seems to be locked, waiting for lock");
859 my $wait=600; # arbitrary, but don't hang forever to
860 # prevent process pileup
862 return if flock($wikilock, 2 | 4);
865 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
874 sub unlockwiki () { #{{{
875 return close($wikilock) if $wikilock;
881 sub commit_hook_enabled () { #{{{
882 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
883 error("cannot write to $config{wikistatedir}/commitlock: $!");
884 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
885 close($commitlock) || error("failed closing commitlock: $!");
888 close($commitlock) || error("failed closing commitlock: $!");
892 sub disable_commit_hook () { #{{{
893 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
894 error("cannot write to $config{wikistatedir}/commitlock: $!");
895 if (! flock($commitlock, 2)) { # LOCK_EX
896 error("failed to get commit lock");
901 sub enable_commit_hook () { #{{{
902 return close($commitlock) if $commitlock;
906 sub loadindex () { #{{{
907 %oldrenderedfiles=%pagectime=();
908 if (! $config{rebuild}) {
909 %pagesources=%pagemtime=%oldlinks=%links=%depends=
910 %destsources=%renderedfiles=%pagecase=();
912 open (my $in, "<", "$config{wikistatedir}/index") || return;
914 $_=possibly_foolish_untaint($_);
919 foreach my $i (split(/ /, $_)) {
920 my ($item, $val)=split(/=/, $i, 2);
921 push @{$items{$item}}, decode_entities($val);
924 next unless exists $items{src}; # skip bad lines for now
926 my $page=pagename($items{src}[0]);
927 if (! $config{rebuild}) {
928 $pagesources{$page}=$items{src}[0];
929 $pagemtime{$page}=$items{mtime}[0];
930 $oldlinks{$page}=[@{$items{link}}];
931 $links{$page}=[@{$items{link}}];
932 $depends{$page}=$items{depends}[0] if exists $items{depends};
933 $destsources{$_}=$page foreach @{$items{dest}};
934 $renderedfiles{$page}=[@{$items{dest}}];
935 $pagecase{lc $page}=$page;
936 foreach my $k (grep /_/, keys %items) {
937 my ($id, $key)=split(/_/, $k, 2);
938 $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
941 $oldrenderedfiles{$page}=[@{$items{dest}}];
942 $pagectime{$page}=$items{ctime}[0];
947 sub saveindex () { #{{{
948 run_hooks(savestate => sub { shift->() });
951 foreach my $type (keys %hooks) {
952 $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
954 my @hookids=sort keys %hookids;
956 if (! -d $config{wikistatedir}) {
957 mkdir($config{wikistatedir});
959 my $newfile="$config{wikistatedir}/index.new";
960 my $cleanup = sub { unlink($newfile) };
961 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
962 foreach my $page (keys %pagemtime) {
963 next unless $pagemtime{$page};
964 my $line="mtime=$pagemtime{$page} ".
965 "ctime=$pagectime{$page} ".
966 "src=$pagesources{$page}";
967 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
969 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
970 if (exists $depends{$page}) {
971 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
973 if (exists $pagestate{$page}) {
974 foreach my $id (@hookids) {
975 foreach my $key (keys %{$pagestate{$page}{$id}}) {
976 $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key}, " \t\n");
980 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
982 close $out || error("failed saving to $newfile: $!", $cleanup);
983 rename($newfile, "$config{wikistatedir}/index") ||
984 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
989 sub template_file ($) { #{{{
992 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
993 return "$dir/$template" if -e "$dir/$template";
998 sub template_params (@) { #{{{
999 my $filename=template_file(shift);
1001 if (! defined $filename) {
1002 return if wantarray;
1008 my $text_ref = shift;
1009 ${$text_ref} = decode_utf8(${$text_ref});
1011 filename => $filename,
1012 loop_context_vars => 1,
1013 die_on_bad_params => 0,
1016 return wantarray ? @ret : {@ret};
1019 sub template ($;@) { #{{{
1020 require HTML::Template;
1021 return HTML::Template->new(template_params(@_));
1024 sub misctemplate ($$;@) { #{{{
1028 my $template=template("misc.tmpl");
1031 indexlink => indexlink(),
1032 wikiname => $config{wikiname},
1033 pagebody => $pagebody,
1034 baseurl => baseurl(),
1037 run_hooks(pagetemplate => sub {
1038 shift->(page => "", destpage => "", template => $template);
1040 return $template->output;
1043 sub hook (@) { # {{{
1046 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1047 error 'hook requires type, call, and id parameters';
1050 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1052 $hooks{$param{type}}{$param{id}}=\%param;
1056 sub run_hooks ($$) { # {{{
1057 # Calls the given sub for each hook of the given type,
1058 # passing it the hook function to call.
1062 if (exists $hooks{$type}) {
1064 foreach my $id (keys %{$hooks{$type}}) {
1065 if ($hooks{$type}{$id}{last}) {
1066 push @deferred, $id;
1069 $sub->($hooks{$type}{$id}{call});
1071 foreach my $id (@deferred) {
1072 $sub->($hooks{$type}{$id}{call});
1079 sub globlist_to_pagespec ($) { #{{{
1080 my @globlist=split(' ', shift);
1083 foreach my $glob (@globlist) {
1084 if ($glob=~/^!(.*)/) {
1092 my $spec=join(' or ', @spec);
1094 my $skip=join(' and ', @skip);
1096 $spec="$skip and ($spec)";
1105 sub is_globlist ($) { #{{{
1107 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1110 sub safequote ($) { #{{{
1116 sub add_depends ($$) { #{{{
1120 if (! exists $depends{$page}) {
1121 $depends{$page}=$pagespec;
1124 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1130 sub file_pruned ($$) { #{{{
1132 my $file=File::Spec->canonpath(shift);
1133 my $base=File::Spec->canonpath(shift);
1134 $file =~ s#^\Q$base\E/+##;
1136 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1137 return $file =~ m/$regexp/ && $file ne $base;
1141 # Only use gettext in the rare cases it's needed.
1142 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1143 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1144 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1145 if (! $gettext_obj) {
1146 $gettext_obj=eval q{
1147 use Locale::gettext q{textdomain};
1148 Locale::gettext->domain('ikiwiki')
1156 return $gettext_obj->get(shift);
1163 sub pagespec_merge ($$) { #{{{
1167 return $a if $a eq $b;
1169 # Support for old-style GlobLists.
1170 if (is_globlist($a)) {
1171 $a=globlist_to_pagespec($a);
1173 if (is_globlist($b)) {
1174 $b=globlist_to_pagespec($b);
1177 return "($a) or ($b)";
1180 sub pagespec_translate ($) { #{{{
1181 # This assumes that $page is in scope in the function
1182 # that evalulates the translated pagespec code.
1185 # Support for old-style GlobLists.
1186 if (is_globlist($spec)) {
1187 $spec=globlist_to_pagespec($spec);
1190 # Convert spec to perl code.
1193 \s* # ignore whitespace
1194 ( # 1: match a single word
1201 \w+\([^\)]*\) # command(params)
1203 [^\s()]+ # any other text
1205 \s* # ignore whitespace
1208 if (lc $word eq 'and') {
1211 elsif (lc $word eq 'or') {
1214 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1217 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1218 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1219 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1226 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1233 sub pagespec_match ($$;@) { #{{{
1238 # Backwards compatability with old calling convention.
1240 unshift @params, 'location';
1243 my $ret=eval pagespec_translate($spec);
1244 return IkiWiki::FailReason->new('syntax error') if $@;
1248 package IkiWiki::FailReason;
1251 '""' => sub { ${$_[0]} },
1253 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1258 return bless \$_[1], $_[0];
1261 package IkiWiki::SuccessReason;
1264 '""' => sub { ${$_[0]} },
1266 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1271 return bless \$_[1], $_[0];
1274 package IkiWiki::PageSpec;
1276 sub match_glob ($$;@) { #{{{
1281 my $from=exists $params{location} ? $params{location} : '';
1284 if ($glob =~ m!^\./!) {
1285 $from=~s#/?[^/]+$##;
1287 $glob="$from/$glob" if length $from;
1290 # turn glob into safe regexp
1291 $glob=quotemeta($glob);
1295 if ($page=~/^$glob$/i) {
1296 if (! IkiWiki::isinternal($page) || $params{internal}) {
1297 return IkiWiki::SuccessReason->new("$glob matches $page");
1300 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1304 return IkiWiki::FailReason->new("$glob does not match $page");
1308 sub match_internal ($$;@) { #{{{
1309 return match_glob($_[0], $_[1], @_, internal => 1)
1312 sub match_link ($$;@) { #{{{
1317 my $from=exists $params{location} ? $params{location} : '';
1320 if ($link =~ m!^\.! && defined $from) {
1321 $from=~s#/?[^/]+$##;
1323 $link="$from/$link" if length $from;
1326 my $links = $IkiWiki::links{$page};
1327 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1328 my $bestlink = IkiWiki::bestlink($from, $link);
1329 foreach my $p (@{$links}) {
1330 if (length $bestlink) {
1331 return IkiWiki::SuccessReason->new("$page links to $link")
1332 if $bestlink eq IkiWiki::bestlink($page, $p);
1335 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1336 if match_glob($p, $link, %params);
1339 return IkiWiki::FailReason->new("$page does not link to $link");
1342 sub match_backlink ($$;@) { #{{{
1343 return match_link($_[1], $_[0], @_);
1346 sub match_created_before ($$;@) { #{{{
1350 if (exists $IkiWiki::pagectime{$testpage}) {
1351 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1352 return IkiWiki::SuccessReason->new("$page created before $testpage");
1355 return IkiWiki::FailReason->new("$page not created before $testpage");
1359 return IkiWiki::FailReason->new("$testpage has no ctime");
1363 sub match_created_after ($$;@) { #{{{
1367 if (exists $IkiWiki::pagectime{$testpage}) {
1368 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1369 return IkiWiki::SuccessReason->new("$page created after $testpage");
1372 return IkiWiki::FailReason->new("$page not created after $testpage");
1376 return IkiWiki::FailReason->new("$testpage has no ctime");
1380 sub match_creation_day ($$;@) { #{{{
1381 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1382 return IkiWiki::SuccessReason->new('creation_day matched');
1385 return IkiWiki::FailReason->new('creation_day did not match');
1389 sub match_creation_month ($$;@) { #{{{
1390 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1391 return IkiWiki::SuccessReason->new('creation_month matched');
1394 return IkiWiki::FailReason->new('creation_month did not match');
1398 sub match_creation_year ($$;@) { #{{{
1399 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1400 return IkiWiki::SuccessReason->new('creation_year matched');
1403 return IkiWiki::FailReason->new('creation_year did not match');