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",
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 => "",
105 sub checkconfig () { #{{{
106 # locale stuff; avoid LC_ALL since it overrides everything
107 if (defined $ENV{LC_ALL}) {
108 $ENV{LANG} = $ENV{LC_ALL};
111 if (defined $config{locale}) {
112 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
113 $ENV{LANG}=$config{locale};
118 if ($config{w3mmode}) {
119 eval q{use Cwd q{abs_path}};
121 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
122 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
123 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
124 unless $config{cgiurl} =~ m!file:///!;
125 $config{url}="file://".$config{destdir};
128 if ($config{cgi} && ! length $config{url}) {
129 error(gettext("Must specify url to wiki with --url when using --cgi"));
132 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
133 unless exists $config{wikistatedir};
136 eval qq{use IkiWiki::Rcs::$config{rcs}};
138 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
142 require IkiWiki::Rcs::Stub;
145 if (exists $config{umask}) {
146 umask(possibly_foolish_untaint($config{umask}));
149 run_hooks(checkconfig => sub { shift->() });
154 sub loadplugins () { #{{{
155 if (defined $config{libdir}) {
156 unshift @INC, possibly_foolish_untaint($config{libdir});
159 loadplugin($_) foreach @{$config{plugin}};
161 run_hooks(getopt => sub { shift->() });
162 if (grep /^-/, @ARGV) {
163 print STDERR "Unknown option: $_\n"
164 foreach grep /^-/, @ARGV;
171 sub loadplugin ($) { #{{{
174 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
176 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
177 "$installdir/lib/ikiwiki") {
178 if (defined $dir && -x "$dir/plugins/$plugin") {
179 require IkiWiki::Plugin::external;
180 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
185 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
188 error("Failed to load plugin $mod: $@");
193 sub error ($;$) { #{{{
197 print "Content-type: text/html\n\n";
198 print misctemplate(gettext("Error"),
199 "<p>".gettext("Error").": $message</p>");
201 log_message('err' => $message) if $config{syslog};
202 if (defined $cleaner) {
209 return unless $config{verbose};
210 return log_message(debug => @_);
214 sub log_message ($$) { #{{{
217 if ($config{syslog}) {
220 Sys::Syslog::setlogsock('unix');
221 Sys::Syslog::openlog('ikiwiki', '', 'user');
225 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
228 elsif (! $config{cgi}) {
232 return print STDERR "@_\n";
236 sub possibly_foolish_untaint ($) { #{{{
238 my ($untainted)=$tainted=~/(.*)/s;
242 sub basename ($) { #{{{
249 sub dirname ($) { #{{{
256 sub pagetype ($) { #{{{
259 if ($page =~ /\.([^.]+)$/) {
260 return $1 if exists $hooks{htmlize}{$1};
265 sub pagename ($) { #{{{
268 my $type=pagetype($file);
270 $page=~s/\Q.$type\E*$// if defined $type;
274 sub targetpage ($$) { #{{{
278 if (! $config{usedirs} || $page =~ /^index$/ ) {
279 return $page.".".$ext;
281 return $page."/index.".$ext;
285 sub htmlpage ($) { #{{{
288 return targetpage($page, $config{htmlext});
291 sub srcfile ($) { #{{{
294 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
295 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
296 return "$dir/$file" if -e "$dir/$file";
298 error("internal error: $file cannot be found in $config{srcdir} or underlay");
302 sub add_underlay ($) { #{{{
306 unshift @{$config{underlaydirs}}, $dir;
309 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
315 sub readfile ($;$$) { #{{{
321 error("cannot read a symlink ($file)");
325 open (my $in, "<", $file) || error("failed to read $file: $!");
326 binmode($in) if ($binary);
327 return \*$in if $wantfd;
329 close $in || error("failed to read $file: $!");
333 sub writefile ($$$;$$) { #{{{
334 my $file=shift; # can include subdirs
335 my $destdir=shift; # directory to put file in
341 while (length $test) {
342 if (-l "$destdir/$test") {
343 error("cannot write to a symlink ($test)");
345 $test=dirname($test);
347 my $newfile="$destdir/$file.ikiwiki-new";
349 error("cannot write to a symlink ($newfile)");
352 my $dir=dirname($newfile);
355 foreach my $s (split(m!/+!, $dir)) {
358 mkdir($d) || error("failed to create directory $d: $!");
363 my $cleanup = sub { unlink($newfile) };
364 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
365 binmode($out) if ($binary);
367 $writer->(\*$out, $cleanup);
370 print $out $content or error("failed writing to $newfile: $!", $cleanup);
372 close $out || error("failed saving $newfile: $!", $cleanup);
373 rename($newfile, "$destdir/$file") ||
374 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
380 sub will_render ($$;$) { #{{{
385 # Important security check.
386 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
387 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
388 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
391 if (! $clear || $cleared{$page}) {
392 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
395 foreach my $old (@{$renderedfiles{$page}}) {
396 delete $destsources{$old};
398 $renderedfiles{$page}=[$dest];
401 $destsources{$dest}=$page;
406 sub bestlink ($$) { #{{{
411 if ($link=~s/^\/+//) {
419 $l.="/" if length $l;
422 if (exists $links{$l}) {
425 elsif (exists $pagecase{lc $l}) {
426 return $pagecase{lc $l};
428 } while $cwd=~s!/?[^/]+$!!;
430 if (length $config{userdir}) {
431 my $l = "$config{userdir}/".lc($link);
432 if (exists $links{$l}) {
435 elsif (exists $pagecase{lc $l}) {
436 return $pagecase{lc $l};
440 #print STDERR "warning: page $page, broken link: $link\n";
444 sub isinlinableimage ($) { #{{{
447 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
450 sub pagetitle ($;$) { #{{{
455 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
458 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
464 sub titlepage ($) { #{{{
466 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
470 sub linkpage ($) { #{{{
472 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
476 sub cgiurl (@) { #{{{
479 return $config{cgiurl}."?".
480 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
483 sub baseurl (;$) { #{{{
486 return "$config{url}/" if ! defined $page;
488 $page=htmlpage($page);
490 $page=~s/[^\/]+\//..\//g;
494 sub abs2rel ($$) { #{{{
495 # Work around very innefficient behavior in File::Spec if abs2rel
496 # is passed two relative paths. It's much faster if paths are
497 # absolute! (Debian bug #376658; fixed in debian unstable now)
502 my $ret=File::Spec->abs2rel($path, $base);
503 $ret=~s/^// if defined $ret;
507 sub displaytime ($;$) { #{{{
510 if (! defined $format) {
511 $format=$config{timeformat};
514 # strftime doesn't know about encodings, so make sure
515 # its output is properly treated as utf8
516 return decode_utf8(POSIX::strftime($format, localtime($time)));
519 sub beautify_url ($) { #{{{
522 if ($config{usedirs}) {
523 $url =~ s!/index.$config{htmlext}$!/!;
525 $url =~ s!^$!./!; # Browsers don't like empty links...
530 sub urlto ($$) { #{{{
535 return beautify_url(baseurl($from));
538 if (! $destsources{$to}) {
542 my $link = abs2rel($to, dirname(htmlpage($from)));
544 return beautify_url($link);
547 sub htmllink ($$$;@) { #{{{
548 my $lpage=shift; # the page doing the linking
549 my $page=shift; # the page that will contain the link (different for inline)
556 if (! $opts{forcesubpage}) {
557 $bestlink=bestlink($lpage, $link);
560 $bestlink="$lpage/".lc($link);
564 if (defined $opts{linktext}) {
565 $linktext=$opts{linktext};
568 $linktext=pagetitle(basename($link));
571 return "<span class=\"selflink\">$linktext</span>"
572 if length $bestlink && $page eq $bestlink &&
573 ! defined $opts{anchor};
575 if (! $destsources{$bestlink}) {
576 $bestlink=htmlpage($bestlink);
578 if (! $destsources{$bestlink}) {
579 return $linktext unless length $config{cgiurl};
580 return "<span class=\"createlink\"><a href=\"".
583 page => pagetitle(lc($link), 1),
586 "\">?</a>$linktext</span>"
590 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
591 $bestlink=beautify_url($bestlink);
593 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
594 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
597 if (defined $opts{anchor}) {
598 $bestlink.="#".$opts{anchor};
602 if (defined $opts{rel}) {
603 push @attrs, ' rel="'.$opts{rel}.'"';
605 if (defined $opts{class}) {
606 push @attrs, ' class="'.$opts{class}.'"';
609 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
612 sub userlink ($) { #{{{
615 eval q{use CGI 'escapeHTML'};
617 if ($user =~ m!^https?://! &&
618 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
619 # Munge user-urls, as used by eg, OpenID.
620 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
621 my $display=$oid->display;
622 # Convert "user.somehost.com" to "user [somehost.com]".
623 if ($display !~ /\[/) {
624 $display=~s/^(.*?)\.([^.]+\.[a-z]+)$/$1 [$2]/;
626 # Convert "http://somehost.com/user" to "user [somehost.com]".
627 if ($display !~ /\[/) {
628 $display=~s/^https?:\/\/(.+)\/([^\/]+)$/$2 [$1]/;
630 $display=~s!^https?://!!; # make sure this is removed
631 return "<a href=\"$user\">".escapeHTML($display)."</a>";
638 sub htmlize ($$$) { #{{{
643 my $oneline = $content !~ /\n/;
645 if (exists $hooks{htmlize}{$type}) {
646 $content=$hooks{htmlize}{$type}{call}->(
652 error("htmlization of $type not supported");
655 run_hooks(sanitize => sub {
663 # hack to get rid of enclosing junk added by markdown
664 # and other htmlizers
666 $content=~s/<\/p>$//i;
673 sub linkify ($$$) { #{{{
674 my $lpage=shift; # the page containing the links
675 my $page=shift; # the page the link will end up on (different for inline)
678 $content =~ s{(\\?)$config{wiki_link_regexp}}{
681 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
682 : htmllink($lpage, $page, linkpage($3),
683 anchor => $4, linktext => pagetitle($2)))
685 ? "[[$3".($4 ? "#$4" : "")."]]"
686 : htmllink($lpage, $page, linkpage($3),
694 our $preprocess_preview=0;
695 sub preprocess ($$$;$$) { #{{{
696 my $page=shift; # the page the data comes from
697 my $destpage=shift; # the page the data will appear in (different for inline)
702 # Using local because it needs to be set within any nested calls
704 local $preprocess_preview=$preview if defined $preview;
710 if (length $escape) {
711 return "[[$command $params]]";
713 elsif (exists $hooks{preprocess}{$command}) {
714 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
715 # Note: preserve order of params, some plugins may
716 # consider it significant.
719 (?:([-\w]+)=)? # 1: named parameter key?
721 """(.*?)""" # 2: triple-quoted value
723 "([^"]+)" # 3: single-quoted value
725 (\S+) # 4: unquoted value
727 (?:\s+|$) # delimiter to next param
745 push @params, $key, $val;
748 push @params, $val, '';
751 if ($preprocessing{$page}++ > 3) {
752 # Avoid loops of preprocessed pages preprocessing
753 # other pages that preprocess them, etc.
754 #translators: The first parameter is a
755 #translators: preprocessor directive name,
756 #translators: the second a page name, the
757 #translators: third a number.
758 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
759 $command, $page, $preprocessing{$page}).
764 $ret=$hooks{preprocess}{$command}{call}->(
767 destpage => $destpage,
768 preview => $preprocess_preview,
772 # use void context during scan pass
773 $hooks{preprocess}{$command}{call}->(
776 destpage => $destpage,
777 preview => $preprocess_preview,
781 $preprocessing{$page}--;
785 return "[[$command $params]]";
791 \[\[ # directive open
792 ([-\w]+) # 2: command
794 ( # 3: the parameters..
796 (?:[-\w]+=)? # named parameter key?
798 """.*?""" # triple-quoted value
800 "[^"]+" # single-quoted value
802 [^\s\]]+ # unquoted value
804 \s* # whitespace or end
807 *) # 0 or more parameters
808 \]\] # directive closed
809 }{$handle->($1, $2, $3)}sexg;
813 sub filter ($$$) { #{{{
818 run_hooks(filter => sub {
819 $content=shift->(page => $page, destpage => $destpage,
820 content => $content);
826 sub indexlink () { #{{{
827 return "<a href=\"$config{url}\">$config{wikiname}</a>";
832 sub lockwiki (;$) { #{{{
833 my $wait=@_ ? shift : 1;
834 # Take an exclusive lock on the wiki to prevent multiple concurrent
835 # run issues. The lock will be dropped on program exit.
836 if (! -d $config{wikistatedir}) {
837 mkdir($config{wikistatedir});
839 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
840 error ("cannot write to $config{wikistatedir}/lockfile: $!");
841 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
843 debug("wiki seems to be locked, waiting for lock");
844 my $wait=600; # arbitrary, but don't hang forever to
845 # prevent process pileup
847 return if flock($wikilock, 2 | 4);
850 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
859 sub unlockwiki () { #{{{
860 return close($wikilock) if $wikilock;
866 sub commit_hook_enabled () { #{{{
867 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
868 error("cannot write to $config{wikistatedir}/commitlock: $!");
869 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
870 close($commitlock) || error("failed closing commitlock: $!");
873 close($commitlock) || error("failed closing commitlock: $!");
877 sub disable_commit_hook () { #{{{
878 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
879 error("cannot write to $config{wikistatedir}/commitlock: $!");
880 if (! flock($commitlock, 2)) { # LOCK_EX
881 error("failed to get commit lock");
886 sub enable_commit_hook () { #{{{
887 return close($commitlock) if $commitlock;
891 sub loadindex () { #{{{
892 %oldrenderedfiles=%pagectime=();
893 if (! $config{rebuild}) {
894 %pagesources=%pagemtime=%oldlinks=%links=%depends=
895 %destsources=%renderedfiles=%pagecase=();
897 open (my $in, "<", "$config{wikistatedir}/index") || return;
899 $_=possibly_foolish_untaint($_);
904 foreach my $i (split(/ /, $_)) {
905 my ($item, $val)=split(/=/, $i, 2);
906 push @{$items{$item}}, decode_entities($val);
909 next unless exists $items{src}; # skip bad lines for now
911 my $page=pagename($items{src}[0]);
912 if (! $config{rebuild}) {
913 $pagesources{$page}=$items{src}[0];
914 $pagemtime{$page}=$items{mtime}[0];
915 $oldlinks{$page}=[@{$items{link}}];
916 $links{$page}=[@{$items{link}}];
917 $depends{$page}=$items{depends}[0] if exists $items{depends};
918 $destsources{$_}=$page foreach @{$items{dest}};
919 $renderedfiles{$page}=[@{$items{dest}}];
920 $pagecase{lc $page}=$page;
921 foreach my $k (grep /_/, keys %items) {
922 my ($id, $key)=split(/_/, $k, 2);
923 $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
926 $oldrenderedfiles{$page}=[@{$items{dest}}];
927 $pagectime{$page}=$items{ctime}[0];
932 sub saveindex () { #{{{
933 run_hooks(savestate => sub { shift->() });
936 foreach my $type (keys %hooks) {
937 $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
939 my @hookids=sort keys %hookids;
941 if (! -d $config{wikistatedir}) {
942 mkdir($config{wikistatedir});
944 my $newfile="$config{wikistatedir}/index.new";
945 my $cleanup = sub { unlink($newfile) };
946 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
947 foreach my $page (keys %pagemtime) {
948 next unless $pagemtime{$page};
949 my $line="mtime=$pagemtime{$page} ".
950 "ctime=$pagectime{$page} ".
951 "src=$pagesources{$page}";
952 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
954 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
955 if (exists $depends{$page}) {
956 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
958 if (exists $pagestate{$page}) {
959 foreach my $id (@hookids) {
960 foreach my $key (keys %{$pagestate{$page}{$id}}) {
961 $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key});
965 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
967 close $out || error("failed saving to $newfile: $!", $cleanup);
968 rename($newfile, "$config{wikistatedir}/index") ||
969 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
974 sub template_file ($) { #{{{
977 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
978 return "$dir/$template" if -e "$dir/$template";
983 sub template_params (@) { #{{{
984 my $filename=template_file(shift);
986 if (! defined $filename) {
993 my $text_ref = shift;
994 ${$text_ref} = decode_utf8(${$text_ref});
996 filename => $filename,
997 loop_context_vars => 1,
998 die_on_bad_params => 0,
1001 return wantarray ? @ret : {@ret};
1004 sub template ($;@) { #{{{
1005 require HTML::Template;
1006 return HTML::Template->new(template_params(@_));
1009 sub misctemplate ($$;@) { #{{{
1013 my $template=template("misc.tmpl");
1016 indexlink => indexlink(),
1017 wikiname => $config{wikiname},
1018 pagebody => $pagebody,
1019 baseurl => baseurl(),
1022 run_hooks(pagetemplate => sub {
1023 shift->(page => "", destpage => "", template => $template);
1025 return $template->output;
1028 sub hook (@) { # {{{
1031 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1032 error 'hook requires type, call, and id parameters';
1035 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1037 $hooks{$param{type}}{$param{id}}=\%param;
1041 sub run_hooks ($$) { # {{{
1042 # Calls the given sub for each hook of the given type,
1043 # passing it the hook function to call.
1047 if (exists $hooks{$type}) {
1049 foreach my $id (keys %{$hooks{$type}}) {
1050 if ($hooks{$type}{$id}{last}) {
1051 push @deferred, $id;
1054 $sub->($hooks{$type}{$id}{call});
1056 foreach my $id (@deferred) {
1057 $sub->($hooks{$type}{$id}{call});
1064 sub globlist_to_pagespec ($) { #{{{
1065 my @globlist=split(' ', shift);
1068 foreach my $glob (@globlist) {
1069 if ($glob=~/^!(.*)/) {
1077 my $spec=join(' or ', @spec);
1079 my $skip=join(' and ', @skip);
1081 $spec="$skip and ($spec)";
1090 sub is_globlist ($) { #{{{
1092 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1095 sub safequote ($) { #{{{
1101 sub add_depends ($$) { #{{{
1105 if (! exists $depends{$page}) {
1106 $depends{$page}=$pagespec;
1109 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1115 sub file_pruned ($$) { #{{{
1117 my $file=File::Spec->canonpath(shift);
1118 my $base=File::Spec->canonpath(shift);
1119 $file =~ s#^\Q$base\E/+##;
1121 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1122 return $file =~ m/$regexp/ && $file ne $base;
1126 # Only use gettext in the rare cases it's needed.
1127 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1128 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1129 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1130 if (! $gettext_obj) {
1131 $gettext_obj=eval q{
1132 use Locale::gettext q{textdomain};
1133 Locale::gettext->domain('ikiwiki')
1141 return $gettext_obj->get(shift);
1148 sub pagespec_merge ($$) { #{{{
1152 return $a if $a eq $b;
1154 # Support for old-style GlobLists.
1155 if (is_globlist($a)) {
1156 $a=globlist_to_pagespec($a);
1158 if (is_globlist($b)) {
1159 $b=globlist_to_pagespec($b);
1162 return "($a) or ($b)";
1165 sub pagespec_translate ($) { #{{{
1166 # This assumes that $page is in scope in the function
1167 # that evalulates the translated pagespec code.
1170 # Support for old-style GlobLists.
1171 if (is_globlist($spec)) {
1172 $spec=globlist_to_pagespec($spec);
1175 # Convert spec to perl code.
1178 \s* # ignore whitespace
1179 ( # 1: match a single word
1186 \w+\([^\)]*\) # command(params)
1188 [^\s()]+ # any other text
1190 \s* # ignore whitespace
1193 if (lc $word eq 'and') {
1196 elsif (lc $word eq 'or') {
1199 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1202 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1203 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1204 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1211 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1218 sub pagespec_match ($$;@) { #{{{
1223 # Backwards compatability with old calling convention.
1225 unshift @params, 'location';
1228 my $ret=eval pagespec_translate($spec);
1229 return IkiWiki::FailReason->new('syntax error') if $@;
1233 package IkiWiki::FailReason;
1236 '""' => sub { ${$_[0]} },
1238 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1243 return bless \$_[1], $_[0];
1246 package IkiWiki::SuccessReason;
1249 '""' => sub { ${$_[0]} },
1251 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1256 return bless \$_[1], $_[0];
1259 package IkiWiki::PageSpec;
1261 sub match_glob ($$;@) { #{{{
1266 my $from=exists $params{location} ? $params{location} : '';
1269 if ($glob =~ m!^\./!) {
1270 $from=~s#/?[^/]+$##;
1272 $glob="$from/$glob" if length $from;
1275 # turn glob into safe regexp
1276 $glob=quotemeta($glob);
1280 if ($page=~/^$glob$/i) {
1281 return IkiWiki::SuccessReason->new("$glob matches $page");
1284 return IkiWiki::FailReason->new("$glob does not match $page");
1288 sub match_link ($$;@) { #{{{
1293 my $from=exists $params{location} ? $params{location} : '';
1296 if ($link =~ m!^\.! && defined $from) {
1297 $from=~s#/?[^/]+$##;
1299 $link="$from/$link" if length $from;
1302 my $links = $IkiWiki::links{$page};
1303 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1304 my $bestlink = IkiWiki::bestlink($from, $link);
1305 foreach my $p (@{$links}) {
1306 if (length $bestlink) {
1307 return IkiWiki::SuccessReason->new("$page links to $link")
1308 if $bestlink eq IkiWiki::bestlink($page, $p);
1311 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1312 if match_glob($p, $link, %params);
1315 return IkiWiki::FailReason->new("$page does not link to $link");
1318 sub match_backlink ($$;@) { #{{{
1319 return match_link($_[1], $_[0], @_);
1322 sub match_created_before ($$;@) { #{{{
1326 if (exists $IkiWiki::pagectime{$testpage}) {
1327 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1328 return IkiWiki::SuccessReason->new("$page created before $testpage");
1331 return IkiWiki::FailReason->new("$page not created before $testpage");
1335 return IkiWiki::FailReason->new("$testpage has no ctime");
1339 sub match_created_after ($$;@) { #{{{
1343 if (exists $IkiWiki::pagectime{$testpage}) {
1344 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1345 return IkiWiki::SuccessReason->new("$page created after $testpage");
1348 return IkiWiki::FailReason->new("$page not created after $testpage");
1352 return IkiWiki::FailReason->new("$testpage has no ctime");
1356 sub match_creation_day ($$;@) { #{{{
1357 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1358 return IkiWiki::SuccessReason->new('creation_day matched');
1361 return IkiWiki::FailReason->new('creation_day did not match');
1365 sub match_creation_month ($$;@) { #{{{
1366 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1367 return IkiWiki::SuccessReason->new('creation_month matched');
1370 return IkiWiki::FailReason->new('creation_month did not match');
1374 sub match_creation_year ($$;@) { #{{{
1375 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1376 return IkiWiki::SuccessReason->new('creation_year matched');
1379 return IkiWiki::FailReason->new('creation_year did not match');
1383 sub match_user ($$;@) { #{{{
1388 return IkiWiki::FailReason->new('cannot match user')
1389 unless exists $params{user};
1390 if ($user eq $params{user}) {
1391 return IkiWiki::SuccessReason->new("user is $user")
1394 return IkiWiki::FailReason->new("user is not $user");