8 use URI::Escape q{uri_escape_utf8};
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14 %pagestate %renderedfiles %oldrenderedfiles %pagesources
15 %destsources %depends %hooks %forcerebuild $gettext_obj};
17 use Exporter q{import};
18 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
19 bestlink htmllink readfile writefile pagetype srcfile pagename
20 displaytime will_render gettext urlto targetpage
22 %config %links %pagestate %renderedfiles
23 %pagesources %destsources);
24 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
25 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
26 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
31 memoize("pagespec_translate");
32 memoize("file_pruned");
34 sub defaultconfig () { #{{{
36 wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
37 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
38 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
41 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
42 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
46 default_pageext => "mdwn",
67 gitorigin_branch => "origin",
68 gitmaster_branch => "master",
72 templatedir => "$installdir/share/ikiwiki/templates",
73 underlaydir => "$installdir/share/ikiwiki/basewiki",
78 plugin => [qw{mdwn link inline htmlscrubber passwordauth openid
79 signinedit lockedit conditional recentchanges}],
88 account_creation_password => "",
89 prefix_directives => 0,
93 sub checkconfig () { #{{{
94 # locale stuff; avoid LC_ALL since it overrides everything
95 if (defined $ENV{LC_ALL}) {
96 $ENV{LANG} = $ENV{LC_ALL};
99 if (defined $config{locale}) {
100 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
101 $ENV{LANG}=$config{locale};
106 if ($config{w3mmode}) {
107 eval q{use Cwd q{abs_path}};
109 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
110 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
111 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
112 unless $config{cgiurl} =~ m!file:///!;
113 $config{url}="file://".$config{destdir};
116 if ($config{cgi} && ! length $config{url}) {
117 error(gettext("Must specify url to wiki with --url when using --cgi"));
120 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
121 unless exists $config{wikistatedir};
124 eval qq{use IkiWiki::Rcs::$config{rcs}};
126 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
130 require IkiWiki::Rcs::Stub;
133 if (exists $config{umask}) {
134 umask(possibly_foolish_untaint($config{umask}));
137 run_hooks(checkconfig => sub { shift->() });
142 sub loadplugins () { #{{{
143 if (defined $config{libdir}) {
144 unshift @INC, possibly_foolish_untaint($config{libdir});
147 loadplugin($_) foreach @{$config{plugin}};
149 run_hooks(getopt => sub { shift->() });
150 if (grep /^-/, @ARGV) {
151 print STDERR "Unknown option: $_\n"
152 foreach grep /^-/, @ARGV;
159 sub loadplugin ($) { #{{{
162 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
164 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
165 "$installdir/lib/ikiwiki") {
166 if (defined $dir && -x "$dir/plugins/$plugin") {
167 require IkiWiki::Plugin::external;
168 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
173 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
176 error("Failed to load plugin $mod: $@");
181 sub error ($;$) { #{{{
185 print "Content-type: text/html\n\n";
186 print misctemplate(gettext("Error"),
187 "<p>".gettext("Error").": $message</p>");
189 log_message('err' => $message) if $config{syslog};
190 if (defined $cleaner) {
197 return unless $config{verbose};
198 return log_message(debug => @_);
202 sub log_message ($$) { #{{{
205 if ($config{syslog}) {
208 Sys::Syslog::setlogsock('unix');
209 Sys::Syslog::openlog('ikiwiki', '', 'user');
213 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
216 elsif (! $config{cgi}) {
220 return print STDERR "@_\n";
224 sub possibly_foolish_untaint ($) { #{{{
226 my ($untainted)=$tainted=~/(.*)/s;
230 sub basename ($) { #{{{
237 sub dirname ($) { #{{{
244 sub pagetype ($) { #{{{
247 if ($page =~ /\.([^.]+)$/) {
248 return $1 if exists $hooks{htmlize}{$1};
253 sub isinternal ($) { #{{{
255 return exists $pagesources{$page} &&
256 $pagesources{$page} =~ /\._([^.]+)$/;
259 sub pagename ($) { #{{{
262 my $type=pagetype($file);
264 $page=~s/\Q.$type\E*$// if defined $type;
268 sub targetpage ($$) { #{{{
272 if (! $config{usedirs} || $page =~ /^index$/ ) {
273 return $page.".".$ext;
275 return $page."/index.".$ext;
279 sub htmlpage ($) { #{{{
282 return targetpage($page, $config{htmlext});
285 sub srcfile ($) { #{{{
288 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
289 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
290 return "$dir/$file" if -e "$dir/$file";
292 error("internal error: $file cannot be found in $config{srcdir} or underlay");
296 sub add_underlay ($) { #{{{
300 unshift @{$config{underlaydirs}}, $dir;
303 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
309 sub readfile ($;$$) { #{{{
315 error("cannot read a symlink ($file)");
319 open (my $in, "<", $file) || error("failed to read $file: $!");
320 binmode($in) if ($binary);
321 return \*$in if $wantfd;
323 close $in || error("failed to read $file: $!");
327 sub prep_writefile ($$) {
332 while (length $test) {
333 if (-l "$destdir/$test") {
334 error("cannot write to a symlink ($test)");
336 $test=dirname($test);
339 my $dir=dirname("$destdir/$file");
342 foreach my $s (split(m!/+!, $dir)) {
345 mkdir($d) || error("failed to create directory $d: $!");
353 sub writefile ($$$;$$) { #{{{
354 my $file=shift; # can include subdirs
355 my $destdir=shift; # directory to put file in
360 prep_writefile($file, $destdir);
362 my $newfile="$destdir/$file.ikiwiki-new";
364 error("cannot write to a symlink ($newfile)");
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 userlink ($) { #{{{
619 my $oiduser=eval { openiduser($user) };
620 if (defined $oiduser) {
621 return "<a href=\"$user\">$oiduser</a>";
624 eval q{use CGI 'escapeHTML'};
627 return htmllink("", "", escapeHTML(
628 length $config{userdir} ? $config{userdir}."/".$user : $user
629 ), noimageinline => 1);
633 sub htmlize ($$$) { #{{{
638 my $oneline = $content !~ /\n/;
640 if (exists $hooks{htmlize}{$type}) {
641 $content=$hooks{htmlize}{$type}{call}->(
647 error("htmlization of $type not supported");
650 run_hooks(sanitize => sub {
658 # hack to get rid of enclosing junk added by markdown
659 # and other htmlizers
661 $content=~s/<\/p>$//i;
668 sub linkify ($$$) { #{{{
673 run_hooks(linkify => sub {
676 destpage => $destpage,
685 our $preprocess_preview=0;
686 sub preprocess ($$$;$$) { #{{{
687 my $page=shift; # the page the data comes from
688 my $destpage=shift; # the page the data will appear in (different for inline)
693 # Using local because it needs to be set within any nested calls
695 local $preprocess_preview=$preview if defined $preview;
702 if (length $escape) {
703 return "[[$prefix$command $params]]";
705 elsif (exists $hooks{preprocess}{$command}) {
706 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
707 # Note: preserve order of params, some plugins may
708 # consider it significant.
711 (?:([-\w]+)=)? # 1: named parameter key?
713 """(.*?)""" # 2: triple-quoted value
715 "([^"]+)" # 3: single-quoted value
717 (\S+) # 4: unquoted value
719 (?:\s+|$) # delimiter to next param
737 push @params, $key, $val;
740 push @params, $val, '';
743 if ($preprocessing{$page}++ > 3) {
744 # Avoid loops of preprocessed pages preprocessing
745 # other pages that preprocess them, etc.
746 #translators: The first parameter is a
747 #translators: preprocessor directive name,
748 #translators: the second a page name, the
749 #translators: third a number.
750 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
751 $command, $page, $preprocessing{$page}).
756 $ret=$hooks{preprocess}{$command}{call}->(
759 destpage => $destpage,
760 preview => $preprocess_preview,
764 # use void context during scan pass
765 $hooks{preprocess}{$command}{call}->(
768 destpage => $destpage,
769 preview => $preprocess_preview,
773 $preprocessing{$page}--;
777 return "[[$prefix$command $params]]";
782 if ($config{prefix_directives}) {
785 \[\[(!) # directive open; 2: prefix
786 ([-\w]+) # 3: command
787 ( # 4: the parameters..
788 \s+ # Must have space if parameters present
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
807 \[\[(!?) # directive open; 2: optional prefix
808 ([-\w]+) # 3: command
810 ( # 4: the parameters..
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
828 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
832 sub filter ($$$) { #{{{
837 run_hooks(filter => sub {
838 $content=shift->(page => $page, destpage => $destpage,
839 content => $content);
845 sub indexlink () { #{{{
846 return "<a href=\"$config{url}\">$config{wikiname}</a>";
851 sub lockwiki (;$) { #{{{
852 my $wait=@_ ? shift : 1;
853 # Take an exclusive lock on the wiki to prevent multiple concurrent
854 # run issues. The lock will be dropped on program exit.
855 if (! -d $config{wikistatedir}) {
856 mkdir($config{wikistatedir});
858 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
859 error ("cannot write to $config{wikistatedir}/lockfile: $!");
860 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
862 debug("wiki seems to be locked, waiting for lock");
863 my $wait=600; # arbitrary, but don't hang forever to
864 # prevent process pileup
866 return if flock($wikilock, 2 | 4);
869 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
878 sub unlockwiki () { #{{{
879 return close($wikilock) if $wikilock;
885 sub commit_hook_enabled () { #{{{
886 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
887 error("cannot write to $config{wikistatedir}/commitlock: $!");
888 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
889 close($commitlock) || error("failed closing commitlock: $!");
892 close($commitlock) || error("failed closing commitlock: $!");
896 sub disable_commit_hook () { #{{{
897 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
898 error("cannot write to $config{wikistatedir}/commitlock: $!");
899 if (! flock($commitlock, 2)) { # LOCK_EX
900 error("failed to get commit lock");
905 sub enable_commit_hook () { #{{{
906 return close($commitlock) if $commitlock;
910 sub loadindex () { #{{{
911 %oldrenderedfiles=%pagectime=();
912 if (! $config{rebuild}) {
913 %pagesources=%pagemtime=%oldlinks=%links=%depends=
914 %destsources=%renderedfiles=%pagecase=%pagestate=();
917 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
918 if (-e "$config{wikistatedir}/index") {
919 system("ikiwiki-transition", "indexdb", $config{srcdir});
920 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
926 my $ret=Storable::fd_retrieve($in);
927 if (! defined $ret) {
931 foreach my $src (keys %index) {
932 my %d=%{$index{$src}};
933 my $page=pagename($src);
934 $pagectime{$page}=$d{ctime};
935 if (! $config{rebuild}) {
936 $pagesources{$page}=$src;
937 $pagemtime{$page}=$d{mtime};
938 $renderedfiles{$page}=$d{dest};
939 if (exists $d{links} && ref $d{links}) {
940 $links{$page}=$d{links};
941 $oldlinks{$page}=[@{$d{links}}];
943 if (exists $d{depends}) {
944 $depends{$page}=$d{depends};
946 if (exists $d{state}) {
947 $pagestate{$page}=$d{state};
950 $oldrenderedfiles{$page}=[@{$d{dest}}];
952 foreach my $page (keys %pagesources) {
953 $pagecase{lc $page}=$page;
955 foreach my $page (keys %renderedfiles) {
956 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
961 sub saveindex () { #{{{
962 run_hooks(savestate => sub { shift->() });
965 foreach my $type (keys %hooks) {
966 $hookids{$_}=1 foreach keys %{$hooks{$type}};
968 my @hookids=keys %hookids;
970 if (! -d $config{wikistatedir}) {
971 mkdir($config{wikistatedir});
973 my $newfile="$config{wikistatedir}/indexdb.new";
974 my $cleanup = sub { unlink($newfile) };
975 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
977 foreach my $page (keys %pagemtime) {
978 next unless $pagemtime{$page};
979 my $src=$pagesources{$page};
982 ctime => $pagectime{$page},
983 mtime => $pagemtime{$page},
984 dest => $renderedfiles{$page},
985 links => $links{$page},
988 if (exists $depends{$page}) {
989 $index{$src}{depends} = $depends{$page};
992 if (exists $pagestate{$page}) {
993 foreach my $id (@hookids) {
994 foreach my $key (keys %{$pagestate{$page}{$id}}) {
995 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1000 my $ret=Storable::nstore_fd(\%index, $out);
1001 return if ! defined $ret || ! $ret;
1002 close $out || error("failed saving to $newfile: $!", $cleanup);
1003 rename($newfile, "$config{wikistatedir}/indexdb") ||
1004 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1009 sub template_file ($) { #{{{
1012 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1013 return "$dir/$template" if -e "$dir/$template";
1018 sub template_params (@) { #{{{
1019 my $filename=template_file(shift);
1021 if (! defined $filename) {
1022 return if wantarray;
1028 my $text_ref = shift;
1029 ${$text_ref} = decode_utf8(${$text_ref});
1031 filename => $filename,
1032 loop_context_vars => 1,
1033 die_on_bad_params => 0,
1036 return wantarray ? @ret : {@ret};
1039 sub template ($;@) { #{{{
1040 require HTML::Template;
1041 return HTML::Template->new(template_params(@_));
1044 sub misctemplate ($$;@) { #{{{
1048 my $template=template("misc.tmpl");
1051 indexlink => indexlink(),
1052 wikiname => $config{wikiname},
1053 pagebody => $pagebody,
1054 baseurl => baseurl(),
1057 run_hooks(pagetemplate => sub {
1058 shift->(page => "", destpage => "", template => $template);
1060 return $template->output;
1063 sub hook (@) { # {{{
1066 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1067 error 'hook requires type, call, and id parameters';
1070 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1072 $hooks{$param{type}}{$param{id}}=\%param;
1076 sub run_hooks ($$) { # {{{
1077 # Calls the given sub for each hook of the given type,
1078 # passing it the hook function to call.
1082 if (exists $hooks{$type}) {
1084 foreach my $id (keys %{$hooks{$type}}) {
1085 if ($hooks{$type}{$id}{last}) {
1086 push @deferred, $id;
1089 $sub->($hooks{$type}{$id}{call});
1091 foreach my $id (@deferred) {
1092 $sub->($hooks{$type}{$id}{call});
1099 sub globlist_to_pagespec ($) { #{{{
1100 my @globlist=split(' ', shift);
1103 foreach my $glob (@globlist) {
1104 if ($glob=~/^!(.*)/) {
1112 my $spec=join(' or ', @spec);
1114 my $skip=join(' and ', @skip);
1116 $spec="$skip and ($spec)";
1125 sub is_globlist ($) { #{{{
1127 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1130 sub safequote ($) { #{{{
1136 sub add_depends ($$) { #{{{
1140 return unless pagespec_valid($pagespec);
1142 if (! exists $depends{$page}) {
1143 $depends{$page}=$pagespec;
1146 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1152 sub file_pruned ($$) { #{{{
1154 my $file=File::Spec->canonpath(shift);
1155 my $base=File::Spec->canonpath(shift);
1156 $file =~ s#^\Q$base\E/+##;
1158 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1159 return $file =~ m/$regexp/ && $file ne $base;
1163 # Only use gettext in the rare cases it's needed.
1164 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1165 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1166 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1167 if (! $gettext_obj) {
1168 $gettext_obj=eval q{
1169 use Locale::gettext q{textdomain};
1170 Locale::gettext->domain('ikiwiki')
1178 return $gettext_obj->get(shift);
1185 sub pagespec_merge ($$) { #{{{
1189 return $a if $a eq $b;
1191 # Support for old-style GlobLists.
1192 if (is_globlist($a)) {
1193 $a=globlist_to_pagespec($a);
1195 if (is_globlist($b)) {
1196 $b=globlist_to_pagespec($b);
1199 return "($a) or ($b)";
1202 sub pagespec_translate ($) { #{{{
1205 # Support for old-style GlobLists.
1206 if (is_globlist($spec)) {
1207 $spec=globlist_to_pagespec($spec);
1210 # Convert spec to perl code.
1213 \s* # ignore whitespace
1214 ( # 1: match a single word
1221 \w+\([^\)]*\) # command(params)
1223 [^\s()]+ # any other text
1225 \s* # ignore whitespace
1228 if (lc $word eq 'and') {
1231 elsif (lc $word eq 'or') {
1234 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1237 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1238 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1239 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1246 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1250 if (! length $code) {
1254 return eval 'sub { my $page=shift; '.$code.' }';
1257 sub pagespec_match ($$;@) { #{{{
1262 # Backwards compatability with old calling convention.
1264 unshift @params, 'location';
1267 my $sub=pagespec_translate($spec);
1268 return IkiWiki::FailReason->new('syntax error') if $@;
1269 return $sub->($page, @params);
1272 sub pagespec_valid ($) { #{{{
1275 my $sub=pagespec_translate($spec);
1279 package IkiWiki::FailReason;
1282 '""' => sub { ${$_[0]} },
1284 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1289 return bless \$_[1], $_[0];
1292 package IkiWiki::SuccessReason;
1295 '""' => sub { ${$_[0]} },
1297 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1302 return bless \$_[1], $_[0];
1305 package IkiWiki::PageSpec;
1307 sub match_glob ($$;@) { #{{{
1312 my $from=exists $params{location} ? $params{location} : '';
1315 if ($glob =~ m!^\./!) {
1316 $from=~s#/?[^/]+$##;
1318 $glob="$from/$glob" if length $from;
1321 # turn glob into safe regexp
1322 $glob=quotemeta($glob);
1326 if ($page=~/^$glob$/i) {
1327 if (! IkiWiki::isinternal($page) || $params{internal}) {
1328 return IkiWiki::SuccessReason->new("$glob matches $page");
1331 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1335 return IkiWiki::FailReason->new("$glob does not match $page");
1339 sub match_internal ($$;@) { #{{{
1340 return match_glob($_[0], $_[1], @_, internal => 1)
1343 sub match_link ($$;@) { #{{{
1348 my $from=exists $params{location} ? $params{location} : '';
1351 if ($link =~ m!^\.! && defined $from) {
1352 $from=~s#/?[^/]+$##;
1354 $link="$from/$link" if length $from;
1357 my $links = $IkiWiki::links{$page};
1358 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1359 my $bestlink = IkiWiki::bestlink($from, $link);
1360 foreach my $p (@{$links}) {
1361 if (length $bestlink) {
1362 return IkiWiki::SuccessReason->new("$page links to $link")
1363 if $bestlink eq IkiWiki::bestlink($page, $p);
1366 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1367 if match_glob($p, $link, %params);
1370 return IkiWiki::FailReason->new("$page does not link to $link");
1373 sub match_backlink ($$;@) { #{{{
1374 return match_link($_[1], $_[0], @_);
1377 sub match_created_before ($$;@) { #{{{
1381 if (exists $IkiWiki::pagectime{$testpage}) {
1382 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1383 return IkiWiki::SuccessReason->new("$page created before $testpage");
1386 return IkiWiki::FailReason->new("$page not created before $testpage");
1390 return IkiWiki::FailReason->new("$testpage has no ctime");
1394 sub match_created_after ($$;@) { #{{{
1398 if (exists $IkiWiki::pagectime{$testpage}) {
1399 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1400 return IkiWiki::SuccessReason->new("$page created after $testpage");
1403 return IkiWiki::FailReason->new("$page not created after $testpage");
1407 return IkiWiki::FailReason->new("$testpage has no ctime");
1411 sub match_creation_day ($$;@) { #{{{
1412 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1413 return IkiWiki::SuccessReason->new('creation_day matched');
1416 return IkiWiki::FailReason->new('creation_day did not match');
1420 sub match_creation_month ($$;@) { #{{{
1421 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1422 return IkiWiki::SuccessReason->new('creation_month matched');
1425 return IkiWiki::FailReason->new('creation_month did not match');
1429 sub match_creation_year ($$;@) { #{{{
1430 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1431 return IkiWiki::SuccessReason->new('creation_year matched');
1434 return IkiWiki::FailReason->new('creation_year did not match');