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 isinternal ($) { #{{{
267 return exists $pagesources{$page} &&
268 $pagesources{$page} =~ /\._([^.]+)$/;
271 sub pagename ($) { #{{{
274 my $type=pagetype($file);
276 $page=~s/\Q.$type\E*$// if defined $type;
280 sub targetpage ($$) { #{{{
284 if (! $config{usedirs} || $page =~ /^index$/ ) {
285 return $page.".".$ext;
287 return $page."/index.".$ext;
291 sub htmlpage ($) { #{{{
294 return targetpage($page, $config{htmlext});
297 sub srcfile ($) { #{{{
300 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
301 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
302 return "$dir/$file" if -e "$dir/$file";
304 error("internal error: $file cannot be found in $config{srcdir} or underlay");
308 sub add_underlay ($) { #{{{
312 unshift @{$config{underlaydirs}}, $dir;
315 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
321 sub readfile ($;$$) { #{{{
327 error("cannot read a symlink ($file)");
331 open (my $in, "<", $file) || error("failed to read $file: $!");
332 binmode($in) if ($binary);
333 return \*$in if $wantfd;
335 close $in || error("failed to read $file: $!");
339 sub writefile ($$$;$$) { #{{{
340 my $file=shift; # can include subdirs
341 my $destdir=shift; # directory to put file in
347 while (length $test) {
348 if (-l "$destdir/$test") {
349 error("cannot write to a symlink ($test)");
351 $test=dirname($test);
353 my $newfile="$destdir/$file.ikiwiki-new";
355 error("cannot write to a symlink ($newfile)");
358 my $dir=dirname($newfile);
361 foreach my $s (split(m!/+!, $dir)) {
364 mkdir($d) || error("failed to create directory $d: $!");
369 my $cleanup = sub { unlink($newfile) };
370 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
371 binmode($out) if ($binary);
373 $writer->(\*$out, $cleanup);
376 print $out $content or error("failed writing to $newfile: $!", $cleanup);
378 close $out || error("failed saving $newfile: $!", $cleanup);
379 rename($newfile, "$destdir/$file") ||
380 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
386 sub will_render ($$;$) { #{{{
391 # Important security check.
392 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
393 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
394 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
397 if (! $clear || $cleared{$page}) {
398 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
401 foreach my $old (@{$renderedfiles{$page}}) {
402 delete $destsources{$old};
404 $renderedfiles{$page}=[$dest];
407 $destsources{$dest}=$page;
412 sub bestlink ($$) { #{{{
417 if ($link=~s/^\/+//) {
425 $l.="/" if length $l;
428 if (exists $links{$l}) {
431 elsif (exists $pagecase{lc $l}) {
432 return $pagecase{lc $l};
434 } while $cwd=~s!/?[^/]+$!!;
436 if (length $config{userdir}) {
437 my $l = "$config{userdir}/".lc($link);
438 if (exists $links{$l}) {
441 elsif (exists $pagecase{lc $l}) {
442 return $pagecase{lc $l};
446 #print STDERR "warning: page $page, broken link: $link\n";
450 sub isinlinableimage ($) { #{{{
453 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
456 sub pagetitle ($;$) { #{{{
461 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
464 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
470 sub titlepage ($) { #{{{
472 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
476 sub linkpage ($) { #{{{
478 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
482 sub cgiurl (@) { #{{{
485 return $config{cgiurl}."?".
486 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
489 sub baseurl (;$) { #{{{
492 return "$config{url}/" if ! defined $page;
494 $page=htmlpage($page);
496 $page=~s/[^\/]+\//..\//g;
500 sub abs2rel ($$) { #{{{
501 # Work around very innefficient behavior in File::Spec if abs2rel
502 # is passed two relative paths. It's much faster if paths are
503 # absolute! (Debian bug #376658; fixed in debian unstable now)
508 my $ret=File::Spec->abs2rel($path, $base);
509 $ret=~s/^// if defined $ret;
513 sub displaytime ($;$) { #{{{
516 if (! defined $format) {
517 $format=$config{timeformat};
520 # strftime doesn't know about encodings, so make sure
521 # its output is properly treated as utf8
522 return decode_utf8(POSIX::strftime($format, localtime($time)));
525 sub beautify_url ($) { #{{{
528 if ($config{usedirs}) {
529 $url =~ s!/index.$config{htmlext}$!/!;
531 $url =~ s!^$!./!; # Browsers don't like empty links...
536 sub urlto ($$) { #{{{
541 return beautify_url(baseurl($from));
544 if (! $destsources{$to}) {
548 my $link = abs2rel($to, dirname(htmlpage($from)));
550 return beautify_url($link);
553 sub htmllink ($$$;@) { #{{{
554 my $lpage=shift; # the page doing the linking
555 my $page=shift; # the page that will contain the link (different for inline)
562 if (! $opts{forcesubpage}) {
563 $bestlink=bestlink($lpage, $link);
566 $bestlink="$lpage/".lc($link);
570 if (defined $opts{linktext}) {
571 $linktext=$opts{linktext};
574 $linktext=pagetitle(basename($link));
577 return "<span class=\"selflink\">$linktext</span>"
578 if length $bestlink && $page eq $bestlink &&
579 ! defined $opts{anchor};
581 if (! $destsources{$bestlink}) {
582 $bestlink=htmlpage($bestlink);
584 if (! $destsources{$bestlink}) {
585 return $linktext unless length $config{cgiurl};
586 return "<span class=\"createlink\"><a href=\"".
589 page => pagetitle(lc($link), 1),
592 "\">?</a>$linktext</span>"
596 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
597 $bestlink=beautify_url($bestlink);
599 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
600 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
603 if (defined $opts{anchor}) {
604 $bestlink.="#".$opts{anchor};
608 if (defined $opts{rel}) {
609 push @attrs, ' rel="'.$opts{rel}.'"';
611 if (defined $opts{class}) {
612 push @attrs, ' class="'.$opts{class}.'"';
615 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
618 sub userlink ($) { #{{{
621 my $oiduser=eval { openiduser($user) };
622 if (defined $oiduser) {
623 return "<a href=\"$user\">$oiduser</a>";
626 return htmllink("", "", escapeHTML(
627 length $config{userdir} ? $config{userdir}."/".$user : $user
628 ), noimageinline => 1);
632 sub htmlize ($$$) { #{{{
637 my $oneline = $content !~ /\n/;
639 if (exists $hooks{htmlize}{$type}) {
640 $content=$hooks{htmlize}{$type}{call}->(
646 error("htmlization of $type not supported");
649 run_hooks(sanitize => sub {
657 # hack to get rid of enclosing junk added by markdown
658 # and other htmlizers
660 $content=~s/<\/p>$//i;
667 sub linkify ($$$) { #{{{
668 my $lpage=shift; # the page containing the links
669 my $page=shift; # the page the link will end up on (different for inline)
672 $content =~ s{(\\?)$config{wiki_link_regexp}}{
675 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
676 : htmllink($lpage, $page, linkpage($3),
677 anchor => $4, linktext => pagetitle($2)))
679 ? "[[$3".($4 ? "#$4" : "")."]]"
680 : htmllink($lpage, $page, linkpage($3),
688 our $preprocess_preview=0;
689 sub preprocess ($$$;$$) { #{{{
690 my $page=shift; # the page the data comes from
691 my $destpage=shift; # the page the data will appear in (different for inline)
696 # Using local because it needs to be set within any nested calls
698 local $preprocess_preview=$preview if defined $preview;
704 if (length $escape) {
705 return "[[$command $params]]";
707 elsif (exists $hooks{preprocess}{$command}) {
708 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
709 # Note: preserve order of params, some plugins may
710 # consider it significant.
713 (?:([-\w]+)=)? # 1: named parameter key?
715 """(.*?)""" # 2: triple-quoted value
717 "([^"]+)" # 3: single-quoted value
719 (\S+) # 4: unquoted value
721 (?:\s+|$) # delimiter to next param
739 push @params, $key, $val;
742 push @params, $val, '';
745 if ($preprocessing{$page}++ > 3) {
746 # Avoid loops of preprocessed pages preprocessing
747 # other pages that preprocess them, etc.
748 #translators: The first parameter is a
749 #translators: preprocessor directive name,
750 #translators: the second a page name, the
751 #translators: third a number.
752 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
753 $command, $page, $preprocessing{$page}).
758 $ret=$hooks{preprocess}{$command}{call}->(
761 destpage => $destpage,
762 preview => $preprocess_preview,
766 # use void context during scan pass
767 $hooks{preprocess}{$command}{call}->(
770 destpage => $destpage,
771 preview => $preprocess_preview,
775 $preprocessing{$page}--;
779 return "[[$command $params]]";
785 \[\[ # directive open
786 ([-\w]+) # 2: command
788 ( # 3: the parameters..
790 (?:[-\w]+=)? # named parameter key?
792 """.*?""" # triple-quoted value
794 "[^"]+" # single-quoted value
796 [^\s\]]+ # unquoted value
798 \s* # whitespace or end
801 *) # 0 or more parameters
802 \]\] # directive closed
803 }{$handle->($1, $2, $3)}sexg;
807 sub filter ($$$) { #{{{
812 run_hooks(filter => sub {
813 $content=shift->(page => $page, destpage => $destpage,
814 content => $content);
820 sub indexlink () { #{{{
821 return "<a href=\"$config{url}\">$config{wikiname}</a>";
826 sub lockwiki (;$) { #{{{
827 my $wait=@_ ? shift : 1;
828 # Take an exclusive lock on the wiki to prevent multiple concurrent
829 # run issues. The lock will be dropped on program exit.
830 if (! -d $config{wikistatedir}) {
831 mkdir($config{wikistatedir});
833 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
834 error ("cannot write to $config{wikistatedir}/lockfile: $!");
835 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
837 debug("wiki seems to be locked, waiting for lock");
838 my $wait=600; # arbitrary, but don't hang forever to
839 # prevent process pileup
841 return if flock($wikilock, 2 | 4);
844 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
853 sub unlockwiki () { #{{{
854 return close($wikilock) if $wikilock;
860 sub commit_hook_enabled () { #{{{
861 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
862 error("cannot write to $config{wikistatedir}/commitlock: $!");
863 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
864 close($commitlock) || error("failed closing commitlock: $!");
867 close($commitlock) || error("failed closing commitlock: $!");
871 sub disable_commit_hook () { #{{{
872 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
873 error("cannot write to $config{wikistatedir}/commitlock: $!");
874 if (! flock($commitlock, 2)) { # LOCK_EX
875 error("failed to get commit lock");
880 sub enable_commit_hook () { #{{{
881 return close($commitlock) if $commitlock;
885 sub loadindex () { #{{{
886 %oldrenderedfiles=%pagectime=();
887 if (! $config{rebuild}) {
888 %pagesources=%pagemtime=%oldlinks=%links=%depends=
889 %destsources=%renderedfiles=%pagecase=%pagestate=();
891 open (my $in, "<", "$config{wikistatedir}/index") || return;
893 $_=possibly_foolish_untaint($_);
898 foreach my $i (split(/ /, $_)) {
899 my ($item, $val)=split(/=/, $i, 2);
900 push @{$items{$item}}, decode_entities($val);
903 next unless exists $items{src}; # skip bad lines for now
905 my $page=pagename($items{src}[0]);
906 if (! $config{rebuild}) {
907 $pagesources{$page}=$items{src}[0];
908 $pagemtime{$page}=$items{mtime}[0];
909 $oldlinks{$page}=[@{$items{link}}];
910 $links{$page}=[@{$items{link}}];
911 $depends{$page}=$items{depends}[0] if exists $items{depends};
912 $destsources{$_}=$page foreach @{$items{dest}};
913 $renderedfiles{$page}=[@{$items{dest}}];
914 $pagecase{lc $page}=$page;
915 foreach my $k (grep /_/, keys %items) {
916 my ($id, $key)=split(/_/, $k, 2);
917 $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
920 $oldrenderedfiles{$page}=[@{$items{dest}}];
921 $pagectime{$page}=$items{ctime}[0];
926 sub saveindex () { #{{{
927 run_hooks(savestate => sub { shift->() });
930 foreach my $type (keys %hooks) {
931 $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
933 my @hookids=sort keys %hookids;
935 if (! -d $config{wikistatedir}) {
936 mkdir($config{wikistatedir});
938 my $newfile="$config{wikistatedir}/index.new";
939 my $cleanup = sub { unlink($newfile) };
940 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
941 foreach my $page (keys %pagemtime) {
942 next unless $pagemtime{$page};
943 my $line="mtime=$pagemtime{$page} ".
944 "ctime=$pagectime{$page} ".
945 "src=$pagesources{$page}";
946 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
948 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
949 if (exists $depends{$page}) {
950 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
952 if (exists $pagestate{$page}) {
953 foreach my $id (@hookids) {
954 foreach my $key (keys %{$pagestate{$page}{$id}}) {
955 $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key}, " \t\n");
959 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
961 close $out || error("failed saving to $newfile: $!", $cleanup);
962 rename($newfile, "$config{wikistatedir}/index") ||
963 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
968 sub template_file ($) { #{{{
971 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
972 return "$dir/$template" if -e "$dir/$template";
977 sub template_params (@) { #{{{
978 my $filename=template_file(shift);
980 if (! defined $filename) {
987 my $text_ref = shift;
988 ${$text_ref} = decode_utf8(${$text_ref});
990 filename => $filename,
991 loop_context_vars => 1,
992 die_on_bad_params => 0,
995 return wantarray ? @ret : {@ret};
998 sub template ($;@) { #{{{
999 require HTML::Template;
1000 return HTML::Template->new(template_params(@_));
1003 sub misctemplate ($$;@) { #{{{
1007 my $template=template("misc.tmpl");
1010 indexlink => indexlink(),
1011 wikiname => $config{wikiname},
1012 pagebody => $pagebody,
1013 baseurl => baseurl(),
1016 run_hooks(pagetemplate => sub {
1017 shift->(page => "", destpage => "", template => $template);
1019 return $template->output;
1022 sub hook (@) { # {{{
1025 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1026 error 'hook requires type, call, and id parameters';
1029 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1031 $hooks{$param{type}}{$param{id}}=\%param;
1035 sub run_hooks ($$) { # {{{
1036 # Calls the given sub for each hook of the given type,
1037 # passing it the hook function to call.
1041 if (exists $hooks{$type}) {
1043 foreach my $id (keys %{$hooks{$type}}) {
1044 if ($hooks{$type}{$id}{last}) {
1045 push @deferred, $id;
1048 $sub->($hooks{$type}{$id}{call});
1050 foreach my $id (@deferred) {
1051 $sub->($hooks{$type}{$id}{call});
1058 sub globlist_to_pagespec ($) { #{{{
1059 my @globlist=split(' ', shift);
1062 foreach my $glob (@globlist) {
1063 if ($glob=~/^!(.*)/) {
1071 my $spec=join(' or ', @spec);
1073 my $skip=join(' and ', @skip);
1075 $spec="$skip and ($spec)";
1084 sub is_globlist ($) { #{{{
1086 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1089 sub safequote ($) { #{{{
1095 sub add_depends ($$) { #{{{
1099 if (! exists $depends{$page}) {
1100 $depends{$page}=$pagespec;
1103 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1109 sub file_pruned ($$) { #{{{
1111 my $file=File::Spec->canonpath(shift);
1112 my $base=File::Spec->canonpath(shift);
1113 $file =~ s#^\Q$base\E/+##;
1115 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1116 return $file =~ m/$regexp/ && $file ne $base;
1120 # Only use gettext in the rare cases it's needed.
1121 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1122 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1123 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1124 if (! $gettext_obj) {
1125 $gettext_obj=eval q{
1126 use Locale::gettext q{textdomain};
1127 Locale::gettext->domain('ikiwiki')
1135 return $gettext_obj->get(shift);
1142 sub pagespec_merge ($$) { #{{{
1146 return $a if $a eq $b;
1148 # Support for old-style GlobLists.
1149 if (is_globlist($a)) {
1150 $a=globlist_to_pagespec($a);
1152 if (is_globlist($b)) {
1153 $b=globlist_to_pagespec($b);
1156 return "($a) or ($b)";
1159 sub pagespec_translate ($) { #{{{
1160 # This assumes that $page is in scope in the function
1161 # that evalulates the translated pagespec code.
1164 # Support for old-style GlobLists.
1165 if (is_globlist($spec)) {
1166 $spec=globlist_to_pagespec($spec);
1169 # Convert spec to perl code.
1172 \s* # ignore whitespace
1173 ( # 1: match a single word
1180 \w+\([^\)]*\) # command(params)
1182 [^\s()]+ # any other text
1184 \s* # ignore whitespace
1187 if (lc $word eq 'and') {
1190 elsif (lc $word eq 'or') {
1193 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1196 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1197 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1198 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1205 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1212 sub pagespec_match ($$;@) { #{{{
1217 # Backwards compatability with old calling convention.
1219 unshift @params, 'location';
1222 my $ret=eval pagespec_translate($spec);
1223 return IkiWiki::FailReason->new('syntax error') if $@;
1227 package IkiWiki::FailReason;
1230 '""' => sub { ${$_[0]} },
1232 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1237 return bless \$_[1], $_[0];
1240 package IkiWiki::SuccessReason;
1243 '""' => sub { ${$_[0]} },
1245 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1250 return bless \$_[1], $_[0];
1253 package IkiWiki::PageSpec;
1255 sub match_glob ($$;@) { #{{{
1260 my $from=exists $params{location} ? $params{location} : '';
1263 if ($glob =~ m!^\./!) {
1264 $from=~s#/?[^/]+$##;
1266 $glob="$from/$glob" if length $from;
1269 # turn glob into safe regexp
1270 $glob=quotemeta($glob);
1274 if ($page=~/^$glob$/i) {
1275 if (! IkiWiki::isinternal($page) || $params{internal}) {
1276 return IkiWiki::SuccessReason->new("$glob matches $page");
1279 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1283 return IkiWiki::FailReason->new("$glob does not match $page");
1287 sub match_internal ($$;@) { #{{{
1288 return match_glob($_[0], $_[1], @_, internal => 1)
1291 sub match_link ($$;@) { #{{{
1296 my $from=exists $params{location} ? $params{location} : '';
1299 if ($link =~ m!^\.! && defined $from) {
1300 $from=~s#/?[^/]+$##;
1302 $link="$from/$link" if length $from;
1305 my $links = $IkiWiki::links{$page};
1306 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1307 my $bestlink = IkiWiki::bestlink($from, $link);
1308 foreach my $p (@{$links}) {
1309 if (length $bestlink) {
1310 return IkiWiki::SuccessReason->new("$page links to $link")
1311 if $bestlink eq IkiWiki::bestlink($page, $p);
1314 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1315 if match_glob($p, $link, %params);
1318 return IkiWiki::FailReason->new("$page does not link to $link");
1321 sub match_backlink ($$;@) { #{{{
1322 return match_link($_[1], $_[0], @_);
1325 sub match_created_before ($$;@) { #{{{
1329 if (exists $IkiWiki::pagectime{$testpage}) {
1330 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1331 return IkiWiki::SuccessReason->new("$page created before $testpage");
1334 return IkiWiki::FailReason->new("$page not created before $testpage");
1338 return IkiWiki::FailReason->new("$testpage has no ctime");
1342 sub match_created_after ($$;@) { #{{{
1346 if (exists $IkiWiki::pagectime{$testpage}) {
1347 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1348 return IkiWiki::SuccessReason->new("$page created after $testpage");
1351 return IkiWiki::FailReason->new("$page not created after $testpage");
1355 return IkiWiki::FailReason->new("$testpage has no ctime");
1359 sub match_creation_day ($$;@) { #{{{
1360 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1361 return IkiWiki::SuccessReason->new('creation_day matched');
1364 return IkiWiki::FailReason->new('creation_day did not match');
1368 sub match_creation_month ($$;@) { #{{{
1369 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1370 return IkiWiki::SuccessReason->new('creation_month matched');
1373 return IkiWiki::FailReason->new('creation_month did not match');
1377 sub match_creation_year ($$;@) { #{{{
1378 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1379 return IkiWiki::SuccessReason->new('creation_year matched');
1382 return IkiWiki::FailReason->new('creation_year did not match');