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_stat { #{{{
289 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
290 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
291 return "$dir/$file", stat(_) if -e "$dir/$file";
293 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
297 sub srcfile ($;$) { #{{{
298 return (srcfile_stat(@_))[0];
301 sub add_underlay ($) { #{{{
305 unshift @{$config{underlaydirs}}, $dir;
308 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
314 sub readfile ($;$$) { #{{{
320 error("cannot read a symlink ($file)");
324 open (my $in, "<", $file) || error("failed to read $file: $!");
325 binmode($in) if ($binary);
326 return \*$in if $wantfd;
328 close $in || error("failed to read $file: $!");
332 sub prep_writefile ($$) {
337 while (length $test) {
338 if (-l "$destdir/$test") {
339 error("cannot write to a symlink ($test)");
341 $test=dirname($test);
344 my $dir=dirname("$destdir/$file");
347 foreach my $s (split(m!/+!, $dir)) {
350 mkdir($d) || error("failed to create directory $d: $!");
358 sub writefile ($$$;$$) { #{{{
359 my $file=shift; # can include subdirs
360 my $destdir=shift; # directory to put file in
365 prep_writefile($file, $destdir);
367 my $newfile="$destdir/$file.ikiwiki-new";
369 error("cannot write to a symlink ($newfile)");
372 my $cleanup = sub { unlink($newfile) };
373 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
374 binmode($out) if ($binary);
376 $writer->(\*$out, $cleanup);
379 print $out $content or error("failed writing to $newfile: $!", $cleanup);
381 close $out || error("failed saving $newfile: $!", $cleanup);
382 rename($newfile, "$destdir/$file") ||
383 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
389 sub will_render ($$;$) { #{{{
394 # Important security check.
395 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
396 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
397 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
400 if (! $clear || $cleared{$page}) {
401 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
404 foreach my $old (@{$renderedfiles{$page}}) {
405 delete $destsources{$old};
407 $renderedfiles{$page}=[$dest];
410 $destsources{$dest}=$page;
415 sub bestlink ($$) { #{{{
420 if ($link=~s/^\/+//) {
428 $l.="/" if length $l;
431 if (exists $links{$l}) {
434 elsif (exists $pagecase{lc $l}) {
435 return $pagecase{lc $l};
437 } while $cwd=~s!/?[^/]+$!!;
439 if (length $config{userdir}) {
440 my $l = "$config{userdir}/".lc($link);
441 if (exists $links{$l}) {
444 elsif (exists $pagecase{lc $l}) {
445 return $pagecase{lc $l};
449 #print STDERR "warning: page $page, broken link: $link\n";
453 sub isinlinableimage ($) { #{{{
456 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
459 sub pagetitle ($;$) { #{{{
464 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
467 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
473 sub titlepage ($) { #{{{
475 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
479 sub linkpage ($) { #{{{
481 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
485 sub cgiurl (@) { #{{{
488 return $config{cgiurl}."?".
489 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
492 sub baseurl (;$) { #{{{
495 return "$config{url}/" if ! defined $page;
497 $page=htmlpage($page);
499 $page=~s/[^\/]+\//..\//g;
503 sub abs2rel ($$) { #{{{
504 # Work around very innefficient behavior in File::Spec if abs2rel
505 # is passed two relative paths. It's much faster if paths are
506 # absolute! (Debian bug #376658; fixed in debian unstable now)
511 my $ret=File::Spec->abs2rel($path, $base);
512 $ret=~s/^// if defined $ret;
516 sub displaytime ($;$) { #{{{
519 if (! defined $format) {
520 $format=$config{timeformat};
523 # strftime doesn't know about encodings, so make sure
524 # its output is properly treated as utf8
525 return decode_utf8(POSIX::strftime($format, localtime($time)));
528 sub beautify_url ($) { #{{{
531 if ($config{usedirs}) {
532 $url =~ s!/index.$config{htmlext}$!/!;
534 $url =~ s!^$!./!; # Browsers don't like empty links...
539 sub urlto ($$) { #{{{
544 return beautify_url(baseurl($from));
547 if (! $destsources{$to}) {
551 my $link = abs2rel($to, dirname(htmlpage($from)));
553 return beautify_url($link);
556 sub htmllink ($$$;@) { #{{{
557 my $lpage=shift; # the page doing the linking
558 my $page=shift; # the page that will contain the link (different for inline)
565 if (! $opts{forcesubpage}) {
566 $bestlink=bestlink($lpage, $link);
569 $bestlink="$lpage/".lc($link);
573 if (defined $opts{linktext}) {
574 $linktext=$opts{linktext};
577 $linktext=pagetitle(basename($link));
580 return "<span class=\"selflink\">$linktext</span>"
581 if length $bestlink && $page eq $bestlink &&
582 ! defined $opts{anchor};
584 if (! $destsources{$bestlink}) {
585 $bestlink=htmlpage($bestlink);
587 if (! $destsources{$bestlink}) {
588 return $linktext unless length $config{cgiurl};
589 return "<span class=\"createlink\"><a href=\"".
592 page => pagetitle(lc($link), 1),
595 "\">?</a>$linktext</span>"
599 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
600 $bestlink=beautify_url($bestlink);
602 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
603 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
606 if (defined $opts{anchor}) {
607 $bestlink.="#".$opts{anchor};
611 if (defined $opts{rel}) {
612 push @attrs, ' rel="'.$opts{rel}.'"';
614 if (defined $opts{class}) {
615 push @attrs, ' class="'.$opts{class}.'"';
618 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
621 sub userlink ($) { #{{{
624 my $oiduser=eval { openiduser($user) };
625 if (defined $oiduser) {
626 return "<a href=\"$user\">$oiduser</a>";
629 eval q{use CGI 'escapeHTML'};
632 return htmllink("", "", escapeHTML(
633 length $config{userdir} ? $config{userdir}."/".$user : $user
634 ), noimageinline => 1);
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 ($$$) { #{{{
678 run_hooks(linkify => sub {
681 destpage => $destpage,
690 our $preprocess_preview=0;
691 sub preprocess ($$$;$$) { #{{{
692 my $page=shift; # the page the data comes from
693 my $destpage=shift; # the page the data will appear in (different for inline)
698 # Using local because it needs to be set within any nested calls
700 local $preprocess_preview=$preview if defined $preview;
707 if (length $escape) {
708 return "[[$prefix$command $params]]";
710 elsif (exists $hooks{preprocess}{$command}) {
711 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
712 # Note: preserve order of params, some plugins may
713 # consider it significant.
716 (?:([-\w]+)=)? # 1: named parameter key?
718 """(.*?)""" # 2: triple-quoted value
720 "([^"]+)" # 3: single-quoted value
722 (\S+) # 4: unquoted value
724 (?:\s+|$) # delimiter to next param
742 push @params, $key, $val;
745 push @params, $val, '';
748 if ($preprocessing{$page}++ > 3) {
749 # Avoid loops of preprocessed pages preprocessing
750 # other pages that preprocess them, etc.
751 #translators: The first parameter is a
752 #translators: preprocessor directive name,
753 #translators: the second a page name, the
754 #translators: third a number.
755 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
756 $command, $page, $preprocessing{$page}).
761 $ret=$hooks{preprocess}{$command}{call}->(
764 destpage => $destpage,
765 preview => $preprocess_preview,
769 # use void context during scan pass
770 $hooks{preprocess}{$command}{call}->(
773 destpage => $destpage,
774 preview => $preprocess_preview,
778 $preprocessing{$page}--;
782 return "[[$prefix$command $params]]";
787 if ($config{prefix_directives}) {
790 \[\[(!) # directive open; 2: prefix
791 ([-\w]+) # 3: command
792 ( # 4: the parameters..
793 \s+ # Must have space if parameters present
795 (?:[-\w]+=)? # named parameter key?
797 """.*?""" # triple-quoted value
799 "[^"]+" # single-quoted value
801 [^\s\]]+ # unquoted value
803 \s* # whitespace or end
806 *)? # 0 or more parameters
807 \]\] # directive closed
812 \[\[(!?) # directive open; 2: optional prefix
813 ([-\w]+) # 3: command
815 ( # 4: the parameters..
817 (?:[-\w]+=)? # named parameter key?
819 """.*?""" # triple-quoted value
821 "[^"]+" # single-quoted value
823 [^\s\]]+ # unquoted value
825 \s* # whitespace or end
828 *) # 0 or more parameters
829 \]\] # directive closed
833 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
837 sub filter ($$$) { #{{{
842 run_hooks(filter => sub {
843 $content=shift->(page => $page, destpage => $destpage,
844 content => $content);
850 sub indexlink () { #{{{
851 return "<a href=\"$config{url}\">$config{wikiname}</a>";
856 sub lockwiki (;$) { #{{{
857 my $wait=@_ ? shift : 1;
858 # Take an exclusive lock on the wiki to prevent multiple concurrent
859 # run issues. The lock will be dropped on program exit.
860 if (! -d $config{wikistatedir}) {
861 mkdir($config{wikistatedir});
863 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
864 error ("cannot write to $config{wikistatedir}/lockfile: $!");
865 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
867 debug("wiki seems to be locked, waiting for lock");
868 my $wait=600; # arbitrary, but don't hang forever to
869 # prevent process pileup
871 return if flock($wikilock, 2 | 4);
874 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
883 sub unlockwiki () { #{{{
884 return close($wikilock) if $wikilock;
890 sub commit_hook_enabled () { #{{{
891 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
892 error("cannot write to $config{wikistatedir}/commitlock: $!");
893 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
894 close($commitlock) || error("failed closing commitlock: $!");
897 close($commitlock) || error("failed closing commitlock: $!");
901 sub disable_commit_hook () { #{{{
902 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
903 error("cannot write to $config{wikistatedir}/commitlock: $!");
904 if (! flock($commitlock, 2)) { # LOCK_EX
905 error("failed to get commit lock");
910 sub enable_commit_hook () { #{{{
911 return close($commitlock) if $commitlock;
915 sub loadindex () { #{{{
916 %oldrenderedfiles=%pagectime=();
917 if (! $config{rebuild}) {
918 %pagesources=%pagemtime=%oldlinks=%links=%depends=
919 %destsources=%renderedfiles=%pagecase=%pagestate=();
922 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
923 if (-e "$config{wikistatedir}/index") {
924 system("ikiwiki-transition", "indexdb", $config{srcdir});
925 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
931 my $ret=Storable::fd_retrieve($in);
932 if (! defined $ret) {
936 foreach my $src (keys %index) {
937 my %d=%{$index{$src}};
938 my $page=pagename($src);
939 $pagectime{$page}=$d{ctime};
940 if (! $config{rebuild}) {
941 $pagesources{$page}=$src;
942 $pagemtime{$page}=$d{mtime};
943 $renderedfiles{$page}=$d{dest};
944 if (exists $d{links} && ref $d{links}) {
945 $links{$page}=$d{links};
946 $oldlinks{$page}=[@{$d{links}}];
948 if (exists $d{depends}) {
949 $depends{$page}=$d{depends};
951 if (exists $d{state}) {
952 $pagestate{$page}=$d{state};
955 $oldrenderedfiles{$page}=[@{$d{dest}}];
957 foreach my $page (keys %pagesources) {
958 $pagecase{lc $page}=$page;
960 foreach my $page (keys %renderedfiles) {
961 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
966 sub saveindex () { #{{{
967 run_hooks(savestate => sub { shift->() });
970 foreach my $type (keys %hooks) {
971 $hookids{$_}=1 foreach keys %{$hooks{$type}};
973 my @hookids=keys %hookids;
975 if (! -d $config{wikistatedir}) {
976 mkdir($config{wikistatedir});
978 my $newfile="$config{wikistatedir}/indexdb.new";
979 my $cleanup = sub { unlink($newfile) };
980 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
982 foreach my $page (keys %pagemtime) {
983 next unless $pagemtime{$page};
984 my $src=$pagesources{$page};
987 ctime => $pagectime{$page},
988 mtime => $pagemtime{$page},
989 dest => $renderedfiles{$page},
990 links => $links{$page},
993 if (exists $depends{$page}) {
994 $index{$src}{depends} = $depends{$page};
997 if (exists $pagestate{$page}) {
998 foreach my $id (@hookids) {
999 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1000 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1005 my $ret=Storable::nstore_fd(\%index, $out);
1006 return if ! defined $ret || ! $ret;
1007 close $out || error("failed saving to $newfile: $!", $cleanup);
1008 rename($newfile, "$config{wikistatedir}/indexdb") ||
1009 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1014 sub template_file ($) { #{{{
1017 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1018 return "$dir/$template" if -e "$dir/$template";
1023 sub template_params (@) { #{{{
1024 my $filename=template_file(shift);
1026 if (! defined $filename) {
1027 return if wantarray;
1033 my $text_ref = shift;
1034 ${$text_ref} = decode_utf8(${$text_ref});
1036 filename => $filename,
1037 loop_context_vars => 1,
1038 die_on_bad_params => 0,
1041 return wantarray ? @ret : {@ret};
1044 sub template ($;@) { #{{{
1045 require HTML::Template;
1046 return HTML::Template->new(template_params(@_));
1049 sub misctemplate ($$;@) { #{{{
1053 my $template=template("misc.tmpl");
1056 indexlink => indexlink(),
1057 wikiname => $config{wikiname},
1058 pagebody => $pagebody,
1059 baseurl => baseurl(),
1062 run_hooks(pagetemplate => sub {
1063 shift->(page => "", destpage => "", template => $template);
1065 return $template->output;
1068 sub hook (@) { # {{{
1071 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1072 error 'hook requires type, call, and id parameters';
1075 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1077 $hooks{$param{type}}{$param{id}}=\%param;
1081 sub run_hooks ($$) { # {{{
1082 # Calls the given sub for each hook of the given type,
1083 # passing it the hook function to call.
1087 if (exists $hooks{$type}) {
1089 foreach my $id (keys %{$hooks{$type}}) {
1090 if ($hooks{$type}{$id}{last}) {
1091 push @deferred, $id;
1094 $sub->($hooks{$type}{$id}{call});
1096 foreach my $id (@deferred) {
1097 $sub->($hooks{$type}{$id}{call});
1104 sub globlist_to_pagespec ($) { #{{{
1105 my @globlist=split(' ', shift);
1108 foreach my $glob (@globlist) {
1109 if ($glob=~/^!(.*)/) {
1117 my $spec=join(' or ', @spec);
1119 my $skip=join(' and ', @skip);
1121 $spec="$skip and ($spec)";
1130 sub is_globlist ($) { #{{{
1132 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1135 sub safequote ($) { #{{{
1141 sub add_depends ($$) { #{{{
1145 return unless pagespec_valid($pagespec);
1147 if (! exists $depends{$page}) {
1148 $depends{$page}=$pagespec;
1151 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1157 sub file_pruned ($$) { #{{{
1159 my $file=File::Spec->canonpath(shift);
1160 my $base=File::Spec->canonpath(shift);
1161 $file =~ s#^\Q$base\E/+##;
1163 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1164 return $file =~ m/$regexp/ && $file ne $base;
1168 # Only use gettext in the rare cases it's needed.
1169 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1170 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1171 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1172 if (! $gettext_obj) {
1173 $gettext_obj=eval q{
1174 use Locale::gettext q{textdomain};
1175 Locale::gettext->domain('ikiwiki')
1183 return $gettext_obj->get(shift);
1190 sub pagespec_merge ($$) { #{{{
1194 return $a if $a eq $b;
1196 # Support for old-style GlobLists.
1197 if (is_globlist($a)) {
1198 $a=globlist_to_pagespec($a);
1200 if (is_globlist($b)) {
1201 $b=globlist_to_pagespec($b);
1204 return "($a) or ($b)";
1207 sub pagespec_translate ($) { #{{{
1210 # Support for old-style GlobLists.
1211 if (is_globlist($spec)) {
1212 $spec=globlist_to_pagespec($spec);
1215 # Convert spec to perl code.
1218 \s* # ignore whitespace
1219 ( # 1: match a single word
1226 \w+\([^\)]*\) # command(params)
1228 [^\s()]+ # any other text
1230 \s* # ignore whitespace
1233 if (lc $word eq 'and') {
1236 elsif (lc $word eq 'or') {
1239 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1242 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1243 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1244 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1251 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1255 if (! length $code) {
1259 return eval 'sub { my $page=shift; '.$code.' }';
1262 sub pagespec_match ($$;@) { #{{{
1267 # Backwards compatability with old calling convention.
1269 unshift @params, 'location';
1272 my $sub=pagespec_translate($spec);
1273 return IkiWiki::FailReason->new('syntax error') if $@;
1274 return $sub->($page, @params);
1277 sub pagespec_valid ($) { #{{{
1280 my $sub=pagespec_translate($spec);
1284 package IkiWiki::FailReason;
1287 '""' => sub { ${$_[0]} },
1289 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1296 return bless \$value, $class;
1299 package IkiWiki::SuccessReason;
1302 '""' => sub { ${$_[0]} },
1304 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1311 return bless \$value, $class;
1314 package IkiWiki::PageSpec;
1316 sub match_glob ($$;@) { #{{{
1321 my $from=exists $params{location} ? $params{location} : '';
1324 if ($glob =~ m!^\./!) {
1325 $from=~s#/?[^/]+$##;
1327 $glob="$from/$glob" if length $from;
1330 # turn glob into safe regexp
1331 $glob=quotemeta($glob);
1335 if ($page=~/^$glob$/i) {
1336 if (! IkiWiki::isinternal($page) || $params{internal}) {
1337 return IkiWiki::SuccessReason->new("$glob matches $page");
1340 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1344 return IkiWiki::FailReason->new("$glob does not match $page");
1348 sub match_internal ($$;@) { #{{{
1349 return match_glob($_[0], $_[1], @_, internal => 1)
1352 sub match_link ($$;@) { #{{{
1357 my $from=exists $params{location} ? $params{location} : '';
1360 if ($link =~ m!^\.! && defined $from) {
1361 $from=~s#/?[^/]+$##;
1363 $link="$from/$link" if length $from;
1366 my $links = $IkiWiki::links{$page};
1367 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1368 my $bestlink = IkiWiki::bestlink($from, $link);
1369 foreach my $p (@{$links}) {
1370 if (length $bestlink) {
1371 return IkiWiki::SuccessReason->new("$page links to $link")
1372 if $bestlink eq IkiWiki::bestlink($page, $p);
1375 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1376 if match_glob($p, $link, %params);
1379 return IkiWiki::FailReason->new("$page does not link to $link");
1382 sub match_backlink ($$;@) { #{{{
1383 return match_link($_[1], $_[0], @_);
1386 sub match_created_before ($$;@) { #{{{
1390 if (exists $IkiWiki::pagectime{$testpage}) {
1391 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1392 return IkiWiki::SuccessReason->new("$page created before $testpage");
1395 return IkiWiki::FailReason->new("$page not created before $testpage");
1399 return IkiWiki::FailReason->new("$testpage has no ctime");
1403 sub match_created_after ($$;@) { #{{{
1407 if (exists $IkiWiki::pagectime{$testpage}) {
1408 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1409 return IkiWiki::SuccessReason->new("$page created after $testpage");
1412 return IkiWiki::FailReason->new("$page not created after $testpage");
1416 return IkiWiki::FailReason->new("$testpage has no ctime");
1420 sub match_creation_day ($$;@) { #{{{
1421 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1422 return IkiWiki::SuccessReason->new('creation_day matched');
1425 return IkiWiki::FailReason->new('creation_day did not match');
1429 sub match_creation_month ($$;@) { #{{{
1430 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1431 return IkiWiki::SuccessReason->new('creation_month matched');
1434 return IkiWiki::FailReason->new('creation_month did not match');
1438 sub match_creation_year ($$;@) { #{{{
1439 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1440 return IkiWiki::SuccessReason->new('creation_year matched');
1443 return IkiWiki::FailReason->new('creation_year did not match');