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 ($;$) { #{{{
289 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
290 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
291 return "$dir/$file" if -e "$dir/$file";
293 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
297 sub add_underlay ($) { #{{{
301 unshift @{$config{underlaydirs}}, $dir;
304 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
310 sub readfile ($;$$) { #{{{
316 error("cannot read a symlink ($file)");
320 open (my $in, "<", $file) || error("failed to read $file: $!");
321 binmode($in) if ($binary);
322 return \*$in if $wantfd;
324 close $in || error("failed to read $file: $!");
328 sub prep_writefile ($$) {
333 while (length $test) {
334 if (-l "$destdir/$test") {
335 error("cannot write to a symlink ($test)");
337 $test=dirname($test);
340 my $dir=dirname("$destdir/$file");
343 foreach my $s (split(m!/+!, $dir)) {
346 mkdir($d) || error("failed to create directory $d: $!");
354 sub writefile ($$$;$$) { #{{{
355 my $file=shift; # can include subdirs
356 my $destdir=shift; # directory to put file in
361 prep_writefile($file, $destdir);
363 my $newfile="$destdir/$file.ikiwiki-new";
365 error("cannot write to a symlink ($newfile)");
368 my $cleanup = sub { unlink($newfile) };
369 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
370 binmode($out) if ($binary);
372 $writer->(\*$out, $cleanup);
375 print $out $content or error("failed writing to $newfile: $!", $cleanup);
377 close $out || error("failed saving $newfile: $!", $cleanup);
378 rename($newfile, "$destdir/$file") ||
379 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
385 sub will_render ($$;$) { #{{{
390 # Important security check.
391 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
392 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
393 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
396 if (! $clear || $cleared{$page}) {
397 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
400 foreach my $old (@{$renderedfiles{$page}}) {
401 delete $destsources{$old};
403 $renderedfiles{$page}=[$dest];
406 $destsources{$dest}=$page;
411 sub bestlink ($$) { #{{{
416 if ($link=~s/^\/+//) {
424 $l.="/" if length $l;
427 if (exists $links{$l}) {
430 elsif (exists $pagecase{lc $l}) {
431 return $pagecase{lc $l};
433 } while $cwd=~s!/?[^/]+$!!;
435 if (length $config{userdir}) {
436 my $l = "$config{userdir}/".lc($link);
437 if (exists $links{$l}) {
440 elsif (exists $pagecase{lc $l}) {
441 return $pagecase{lc $l};
445 #print STDERR "warning: page $page, broken link: $link\n";
449 sub isinlinableimage ($) { #{{{
452 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
455 sub pagetitle ($;$) { #{{{
460 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
463 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
469 sub titlepage ($) { #{{{
471 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
475 sub linkpage ($) { #{{{
477 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
481 sub cgiurl (@) { #{{{
484 return $config{cgiurl}."?".
485 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
488 sub baseurl (;$) { #{{{
491 return "$config{url}/" if ! defined $page;
493 $page=htmlpage($page);
495 $page=~s/[^\/]+\//..\//g;
499 sub abs2rel ($$) { #{{{
500 # Work around very innefficient behavior in File::Spec if abs2rel
501 # is passed two relative paths. It's much faster if paths are
502 # absolute! (Debian bug #376658; fixed in debian unstable now)
507 my $ret=File::Spec->abs2rel($path, $base);
508 $ret=~s/^// if defined $ret;
512 sub displaytime ($;$) { #{{{
515 if (! defined $format) {
516 $format=$config{timeformat};
519 # strftime doesn't know about encodings, so make sure
520 # its output is properly treated as utf8
521 return decode_utf8(POSIX::strftime($format, localtime($time)));
524 sub beautify_url ($) { #{{{
527 if ($config{usedirs}) {
528 $url =~ s!/index.$config{htmlext}$!/!;
530 $url =~ s!^$!./!; # Browsers don't like empty links...
535 sub urlto ($$) { #{{{
540 return beautify_url(baseurl($from));
543 if (! $destsources{$to}) {
547 my $link = abs2rel($to, dirname(htmlpage($from)));
549 return beautify_url($link);
552 sub htmllink ($$$;@) { #{{{
553 my $lpage=shift; # the page doing the linking
554 my $page=shift; # the page that will contain the link (different for inline)
561 if (! $opts{forcesubpage}) {
562 $bestlink=bestlink($lpage, $link);
565 $bestlink="$lpage/".lc($link);
569 if (defined $opts{linktext}) {
570 $linktext=$opts{linktext};
573 $linktext=pagetitle(basename($link));
576 return "<span class=\"selflink\">$linktext</span>"
577 if length $bestlink && $page eq $bestlink &&
578 ! defined $opts{anchor};
580 if (! $destsources{$bestlink}) {
581 $bestlink=htmlpage($bestlink);
583 if (! $destsources{$bestlink}) {
584 return $linktext unless length $config{cgiurl};
585 return "<span class=\"createlink\"><a href=\"".
588 page => pagetitle(lc($link), 1),
591 "\">?</a>$linktext</span>"
595 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
596 $bestlink=beautify_url($bestlink);
598 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
599 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
602 if (defined $opts{anchor}) {
603 $bestlink.="#".$opts{anchor};
607 if (defined $opts{rel}) {
608 push @attrs, ' rel="'.$opts{rel}.'"';
610 if (defined $opts{class}) {
611 push @attrs, ' class="'.$opts{class}.'"';
614 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
617 sub userlink ($) { #{{{
620 my $oiduser=eval { openiduser($user) };
621 if (defined $oiduser) {
622 return "<a href=\"$user\">$oiduser</a>";
625 eval q{use CGI 'escapeHTML'};
628 return htmllink("", "", escapeHTML(
629 length $config{userdir} ? $config{userdir}."/".$user : $user
630 ), noimageinline => 1);
634 sub htmlize ($$$) { #{{{
639 my $oneline = $content !~ /\n/;
641 if (exists $hooks{htmlize}{$type}) {
642 $content=$hooks{htmlize}{$type}{call}->(
648 error("htmlization of $type not supported");
651 run_hooks(sanitize => sub {
659 # hack to get rid of enclosing junk added by markdown
660 # and other htmlizers
662 $content=~s/<\/p>$//i;
669 sub linkify ($$$) { #{{{
674 run_hooks(linkify => sub {
677 destpage => $destpage,
686 our $preprocess_preview=0;
687 sub preprocess ($$$;$$) { #{{{
688 my $page=shift; # the page the data comes from
689 my $destpage=shift; # the page the data will appear in (different for inline)
694 # Using local because it needs to be set within any nested calls
696 local $preprocess_preview=$preview if defined $preview;
703 if (length $escape) {
704 return "[[$prefix$command $params]]";
706 elsif (exists $hooks{preprocess}{$command}) {
707 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
708 # Note: preserve order of params, some plugins may
709 # consider it significant.
712 (?:([-\w]+)=)? # 1: named parameter key?
714 """(.*?)""" # 2: triple-quoted value
716 "([^"]+)" # 3: single-quoted value
718 (\S+) # 4: unquoted value
720 (?:\s+|$) # delimiter to next param
738 push @params, $key, $val;
741 push @params, $val, '';
744 if ($preprocessing{$page}++ > 3) {
745 # Avoid loops of preprocessed pages preprocessing
746 # other pages that preprocess them, etc.
747 #translators: The first parameter is a
748 #translators: preprocessor directive name,
749 #translators: the second a page name, the
750 #translators: third a number.
751 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
752 $command, $page, $preprocessing{$page}).
757 $ret=$hooks{preprocess}{$command}{call}->(
760 destpage => $destpage,
761 preview => $preprocess_preview,
765 # use void context during scan pass
766 $hooks{preprocess}{$command}{call}->(
769 destpage => $destpage,
770 preview => $preprocess_preview,
774 $preprocessing{$page}--;
778 return "[[$prefix$command $params]]";
783 if ($config{prefix_directives}) {
786 \[\[(!) # directive open; 2: prefix
787 ([-\w]+) # 3: command
788 ( # 4: the parameters..
789 \s+ # Must have space if parameters present
791 (?:[-\w]+=)? # named parameter key?
793 """.*?""" # triple-quoted value
795 "[^"]+" # single-quoted value
797 [^\s\]]+ # unquoted value
799 \s* # whitespace or end
802 *)? # 0 or more parameters
803 \]\] # directive closed
808 \[\[(!?) # directive open; 2: optional prefix
809 ([-\w]+) # 3: command
811 ( # 4: the parameters..
813 (?:[-\w]+=)? # named parameter key?
815 """.*?""" # triple-quoted value
817 "[^"]+" # single-quoted value
819 [^\s\]]+ # unquoted value
821 \s* # whitespace or end
824 *) # 0 or more parameters
825 \]\] # directive closed
829 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
833 sub filter ($$$) { #{{{
838 run_hooks(filter => sub {
839 $content=shift->(page => $page, destpage => $destpage,
840 content => $content);
846 sub indexlink () { #{{{
847 return "<a href=\"$config{url}\">$config{wikiname}</a>";
852 sub lockwiki (;$) { #{{{
853 my $wait=@_ ? shift : 1;
854 # Take an exclusive lock on the wiki to prevent multiple concurrent
855 # run issues. The lock will be dropped on program exit.
856 if (! -d $config{wikistatedir}) {
857 mkdir($config{wikistatedir});
859 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
860 error ("cannot write to $config{wikistatedir}/lockfile: $!");
861 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
863 debug("wiki seems to be locked, waiting for lock");
864 my $wait=600; # arbitrary, but don't hang forever to
865 # prevent process pileup
867 return if flock($wikilock, 2 | 4);
870 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
879 sub unlockwiki () { #{{{
880 return close($wikilock) if $wikilock;
886 sub commit_hook_enabled () { #{{{
887 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
888 error("cannot write to $config{wikistatedir}/commitlock: $!");
889 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
890 close($commitlock) || error("failed closing commitlock: $!");
893 close($commitlock) || error("failed closing commitlock: $!");
897 sub disable_commit_hook () { #{{{
898 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
899 error("cannot write to $config{wikistatedir}/commitlock: $!");
900 if (! flock($commitlock, 2)) { # LOCK_EX
901 error("failed to get commit lock");
906 sub enable_commit_hook () { #{{{
907 return close($commitlock) if $commitlock;
911 sub loadindex () { #{{{
912 %oldrenderedfiles=%pagectime=();
913 if (! $config{rebuild}) {
914 %pagesources=%pagemtime=%oldlinks=%links=%depends=
915 %destsources=%renderedfiles=%pagecase=%pagestate=();
918 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
919 if (-e "$config{wikistatedir}/index") {
920 system("ikiwiki-transition", "indexdb", $config{srcdir});
921 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
927 my $ret=Storable::fd_retrieve($in);
928 if (! defined $ret) {
932 foreach my $src (keys %index) {
933 my %d=%{$index{$src}};
934 my $page=pagename($src);
935 $pagectime{$page}=$d{ctime};
936 if (! $config{rebuild}) {
937 $pagesources{$page}=$src;
938 $pagemtime{$page}=$d{mtime};
939 $renderedfiles{$page}=$d{dest};
940 if (exists $d{links} && ref $d{links}) {
941 $links{$page}=$d{links};
942 $oldlinks{$page}=[@{$d{links}}];
944 if (exists $d{depends}) {
945 $depends{$page}=$d{depends};
947 if (exists $d{state}) {
948 $pagestate{$page}=$d{state};
951 $oldrenderedfiles{$page}=[@{$d{dest}}];
953 foreach my $page (keys %pagesources) {
954 $pagecase{lc $page}=$page;
956 foreach my $page (keys %renderedfiles) {
957 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
962 sub saveindex () { #{{{
963 run_hooks(savestate => sub { shift->() });
966 foreach my $type (keys %hooks) {
967 $hookids{$_}=1 foreach keys %{$hooks{$type}};
969 my @hookids=keys %hookids;
971 if (! -d $config{wikistatedir}) {
972 mkdir($config{wikistatedir});
974 my $newfile="$config{wikistatedir}/indexdb.new";
975 my $cleanup = sub { unlink($newfile) };
976 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
978 foreach my $page (keys %pagemtime) {
979 next unless $pagemtime{$page};
980 my $src=$pagesources{$page};
983 ctime => $pagectime{$page},
984 mtime => $pagemtime{$page},
985 dest => $renderedfiles{$page},
986 links => $links{$page},
989 if (exists $depends{$page}) {
990 $index{$src}{depends} = $depends{$page};
993 if (exists $pagestate{$page}) {
994 foreach my $id (@hookids) {
995 foreach my $key (keys %{$pagestate{$page}{$id}}) {
996 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1001 my $ret=Storable::nstore_fd(\%index, $out);
1002 return if ! defined $ret || ! $ret;
1003 close $out || error("failed saving to $newfile: $!", $cleanup);
1004 rename($newfile, "$config{wikistatedir}/indexdb") ||
1005 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1010 sub template_file ($) { #{{{
1013 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1014 return "$dir/$template" if -e "$dir/$template";
1019 sub template_params (@) { #{{{
1020 my $filename=template_file(shift);
1022 if (! defined $filename) {
1023 return if wantarray;
1029 my $text_ref = shift;
1030 ${$text_ref} = decode_utf8(${$text_ref});
1032 filename => $filename,
1033 loop_context_vars => 1,
1034 die_on_bad_params => 0,
1037 return wantarray ? @ret : {@ret};
1040 sub template ($;@) { #{{{
1041 require HTML::Template;
1042 return HTML::Template->new(template_params(@_));
1045 sub misctemplate ($$;@) { #{{{
1049 my $template=template("misc.tmpl");
1052 indexlink => indexlink(),
1053 wikiname => $config{wikiname},
1054 pagebody => $pagebody,
1055 baseurl => baseurl(),
1058 run_hooks(pagetemplate => sub {
1059 shift->(page => "", destpage => "", template => $template);
1061 return $template->output;
1064 sub hook (@) { # {{{
1067 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1068 error 'hook requires type, call, and id parameters';
1071 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1073 $hooks{$param{type}}{$param{id}}=\%param;
1077 sub run_hooks ($$) { # {{{
1078 # Calls the given sub for each hook of the given type,
1079 # passing it the hook function to call.
1083 if (exists $hooks{$type}) {
1085 foreach my $id (keys %{$hooks{$type}}) {
1086 if ($hooks{$type}{$id}{last}) {
1087 push @deferred, $id;
1090 $sub->($hooks{$type}{$id}{call});
1092 foreach my $id (@deferred) {
1093 $sub->($hooks{$type}{$id}{call});
1100 sub globlist_to_pagespec ($) { #{{{
1101 my @globlist=split(' ', shift);
1104 foreach my $glob (@globlist) {
1105 if ($glob=~/^!(.*)/) {
1113 my $spec=join(' or ', @spec);
1115 my $skip=join(' and ', @skip);
1117 $spec="$skip and ($spec)";
1126 sub is_globlist ($) { #{{{
1128 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1131 sub safequote ($) { #{{{
1137 sub add_depends ($$) { #{{{
1141 return unless pagespec_valid($pagespec);
1143 if (! exists $depends{$page}) {
1144 $depends{$page}=$pagespec;
1147 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1153 sub file_pruned ($$) { #{{{
1155 my $file=File::Spec->canonpath(shift);
1156 my $base=File::Spec->canonpath(shift);
1157 $file =~ s#^\Q$base\E/+##;
1159 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1160 return $file =~ m/$regexp/ && $file ne $base;
1164 # Only use gettext in the rare cases it's needed.
1165 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1166 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1167 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1168 if (! $gettext_obj) {
1169 $gettext_obj=eval q{
1170 use Locale::gettext q{textdomain};
1171 Locale::gettext->domain('ikiwiki')
1179 return $gettext_obj->get(shift);
1186 sub pagespec_merge ($$) { #{{{
1190 return $a if $a eq $b;
1192 # Support for old-style GlobLists.
1193 if (is_globlist($a)) {
1194 $a=globlist_to_pagespec($a);
1196 if (is_globlist($b)) {
1197 $b=globlist_to_pagespec($b);
1200 return "($a) or ($b)";
1203 sub pagespec_translate ($) { #{{{
1206 # Support for old-style GlobLists.
1207 if (is_globlist($spec)) {
1208 $spec=globlist_to_pagespec($spec);
1211 # Convert spec to perl code.
1214 \s* # ignore whitespace
1215 ( # 1: match a single word
1222 \w+\([^\)]*\) # command(params)
1224 [^\s()]+ # any other text
1226 \s* # ignore whitespace
1229 if (lc $word eq 'and') {
1232 elsif (lc $word eq 'or') {
1235 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1238 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1239 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1240 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1247 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1251 if (! length $code) {
1255 return eval 'sub { my $page=shift; '.$code.' }';
1258 sub pagespec_match ($$;@) { #{{{
1263 # Backwards compatability with old calling convention.
1265 unshift @params, 'location';
1268 my $sub=pagespec_translate($spec);
1269 return IkiWiki::FailReason->new('syntax error') if $@;
1270 return $sub->($page, @params);
1273 sub pagespec_valid ($) { #{{{
1276 my $sub=pagespec_translate($spec);
1280 package IkiWiki::FailReason;
1283 '""' => sub { ${$_[0]} },
1285 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1290 return bless \$_[1], $_[0];
1293 package IkiWiki::SuccessReason;
1296 '""' => sub { ${$_[0]} },
1298 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1303 return bless \$_[1], $_[0];
1306 package IkiWiki::PageSpec;
1308 sub match_glob ($$;@) { #{{{
1313 my $from=exists $params{location} ? $params{location} : '';
1316 if ($glob =~ m!^\./!) {
1317 $from=~s#/?[^/]+$##;
1319 $glob="$from/$glob" if length $from;
1322 # turn glob into safe regexp
1323 $glob=quotemeta($glob);
1327 if ($page=~/^$glob$/i) {
1328 if (! IkiWiki::isinternal($page) || $params{internal}) {
1329 return IkiWiki::SuccessReason->new("$glob matches $page");
1332 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1336 return IkiWiki::FailReason->new("$glob does not match $page");
1340 sub match_internal ($$;@) { #{{{
1341 return match_glob($_[0], $_[1], @_, internal => 1)
1344 sub match_link ($$;@) { #{{{
1349 my $from=exists $params{location} ? $params{location} : '';
1352 if ($link =~ m!^\.! && defined $from) {
1353 $from=~s#/?[^/]+$##;
1355 $link="$from/$link" if length $from;
1358 my $links = $IkiWiki::links{$page};
1359 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1360 my $bestlink = IkiWiki::bestlink($from, $link);
1361 foreach my $p (@{$links}) {
1362 if (length $bestlink) {
1363 return IkiWiki::SuccessReason->new("$page links to $link")
1364 if $bestlink eq IkiWiki::bestlink($page, $p);
1367 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1368 if match_glob($p, $link, %params);
1371 return IkiWiki::FailReason->new("$page does not link to $link");
1374 sub match_backlink ($$;@) { #{{{
1375 return match_link($_[1], $_[0], @_);
1378 sub match_created_before ($$;@) { #{{{
1382 if (exists $IkiWiki::pagectime{$testpage}) {
1383 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1384 return IkiWiki::SuccessReason->new("$page created before $testpage");
1387 return IkiWiki::FailReason->new("$page not created before $testpage");
1391 return IkiWiki::FailReason->new("$testpage has no ctime");
1395 sub match_created_after ($$;@) { #{{{
1399 if (exists $IkiWiki::pagectime{$testpage}) {
1400 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1401 return IkiWiki::SuccessReason->new("$page created after $testpage");
1404 return IkiWiki::FailReason->new("$page not created after $testpage");
1408 return IkiWiki::FailReason->new("$testpage has no ctime");
1412 sub match_creation_day ($$;@) { #{{{
1413 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1414 return IkiWiki::SuccessReason->new('creation_day matched');
1417 return IkiWiki::FailReason->new('creation_day did not match');
1421 sub match_creation_month ($$;@) { #{{{
1422 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1423 return IkiWiki::SuccessReason->new('creation_month matched');
1426 return IkiWiki::FailReason->new('creation_month did not match');
1430 sub match_creation_year ($$;@) { #{{{
1431 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1432 return IkiWiki::SuccessReason->new('creation_year matched');
1435 return IkiWiki::FailReason->new('creation_year did not match');