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 return htmllink("", "", escapeHTML(
625 length $config{userdir} ? $config{userdir}."/".$user : $user
626 ), noimageinline => 1);
630 sub htmlize ($$$) { #{{{
635 my $oneline = $content !~ /\n/;
637 if (exists $hooks{htmlize}{$type}) {
638 $content=$hooks{htmlize}{$type}{call}->(
644 error("htmlization of $type not supported");
647 run_hooks(sanitize => sub {
655 # hack to get rid of enclosing junk added by markdown
656 # and other htmlizers
658 $content=~s/<\/p>$//i;
665 sub linkify ($$$) { #{{{
670 run_hooks(linkify => sub {
673 destpage => $destpage,
682 our $preprocess_preview=0;
683 sub preprocess ($$$;$$) { #{{{
684 my $page=shift; # the page the data comes from
685 my $destpage=shift; # the page the data will appear in (different for inline)
690 # Using local because it needs to be set within any nested calls
692 local $preprocess_preview=$preview if defined $preview;
699 if (length $escape) {
700 return "[[$prefix$command $params]]";
702 elsif (exists $hooks{preprocess}{$command}) {
703 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
704 # Note: preserve order of params, some plugins may
705 # consider it significant.
708 (?:([-\w]+)=)? # 1: named parameter key?
710 """(.*?)""" # 2: triple-quoted value
712 "([^"]+)" # 3: single-quoted value
714 (\S+) # 4: unquoted value
716 (?:\s+|$) # delimiter to next param
734 push @params, $key, $val;
737 push @params, $val, '';
740 if ($preprocessing{$page}++ > 3) {
741 # Avoid loops of preprocessed pages preprocessing
742 # other pages that preprocess them, etc.
743 #translators: The first parameter is a
744 #translators: preprocessor directive name,
745 #translators: the second a page name, the
746 #translators: third a number.
747 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
748 $command, $page, $preprocessing{$page}).
753 $ret=$hooks{preprocess}{$command}{call}->(
756 destpage => $destpage,
757 preview => $preprocess_preview,
761 # use void context during scan pass
762 $hooks{preprocess}{$command}{call}->(
765 destpage => $destpage,
766 preview => $preprocess_preview,
770 $preprocessing{$page}--;
774 return "[[$prefix$command $params]]";
779 if ($config{prefix_directives}) {
782 \[\[(!) # directive open; 2: prefix
783 ([-\w]+) # 3: command
784 ( # 4: the parameters..
785 \s+ # Must have space if parameters present
787 (?:[-\w]+=)? # named parameter key?
789 """.*?""" # triple-quoted value
791 "[^"]+" # single-quoted value
793 [^\s\]]+ # unquoted value
795 \s* # whitespace or end
798 *)? # 0 or more parameters
799 \]\] # directive closed
804 \[\[(!?) # directive open; 2: optional prefix
805 ([-\w]+) # 3: command
807 ( # 4: the parameters..
809 (?:[-\w]+=)? # named parameter key?
811 """.*?""" # triple-quoted value
813 "[^"]+" # single-quoted value
815 [^\s\]]+ # unquoted value
817 \s* # whitespace or end
820 *) # 0 or more parameters
821 \]\] # directive closed
825 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
829 sub filter ($$$) { #{{{
834 run_hooks(filter => sub {
835 $content=shift->(page => $page, destpage => $destpage,
836 content => $content);
842 sub indexlink () { #{{{
843 return "<a href=\"$config{url}\">$config{wikiname}</a>";
848 sub lockwiki (;$) { #{{{
849 my $wait=@_ ? shift : 1;
850 # Take an exclusive lock on the wiki to prevent multiple concurrent
851 # run issues. The lock will be dropped on program exit.
852 if (! -d $config{wikistatedir}) {
853 mkdir($config{wikistatedir});
855 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
856 error ("cannot write to $config{wikistatedir}/lockfile: $!");
857 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
859 debug("wiki seems to be locked, waiting for lock");
860 my $wait=600; # arbitrary, but don't hang forever to
861 # prevent process pileup
863 return if flock($wikilock, 2 | 4);
866 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
875 sub unlockwiki () { #{{{
876 return close($wikilock) if $wikilock;
882 sub commit_hook_enabled () { #{{{
883 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
884 error("cannot write to $config{wikistatedir}/commitlock: $!");
885 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
886 close($commitlock) || error("failed closing commitlock: $!");
889 close($commitlock) || error("failed closing commitlock: $!");
893 sub disable_commit_hook () { #{{{
894 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
895 error("cannot write to $config{wikistatedir}/commitlock: $!");
896 if (! flock($commitlock, 2)) { # LOCK_EX
897 error("failed to get commit lock");
902 sub enable_commit_hook () { #{{{
903 return close($commitlock) if $commitlock;
907 sub loadindex () { #{{{
908 %oldrenderedfiles=%pagectime=();
909 if (! $config{rebuild}) {
910 %pagesources=%pagemtime=%oldlinks=%links=%depends=
911 %destsources=%renderedfiles=%pagecase=%pagestate=();
914 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
915 if (-e "$config{wikistatedir}/index") {
916 system("ikiwiki-transition", "indexdb", $config{srcdir});
917 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
923 my $ret=Storable::fd_retrieve($in);
924 if (! defined $ret) {
928 foreach my $src (keys %index) {
929 my %d=%{$index{$src}};
930 my $page=pagename($src);
931 $pagectime{$page}=$d{ctime};
932 if (! $config{rebuild}) {
933 $pagesources{$page}=$src;
934 $pagemtime{$page}=$d{mtime};
935 $renderedfiles{$page}=$d{dest};
936 if (exists $d{links} && ref $d{links}) {
937 $links{$page}=$d{links};
938 $oldlinks{$page}=[@{$d{links}}];
940 if (exists $d{depends}) {
941 $depends{$page}=$d{depends};
943 if (exists $d{state}) {
944 $pagestate{$page}=$d{state};
947 $oldrenderedfiles{$page}=[@{$d{dest}}];
949 foreach my $page (keys %pagesources) {
950 $pagecase{lc $page}=$page;
952 foreach my $page (keys %renderedfiles) {
953 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
958 sub saveindex () { #{{{
959 run_hooks(savestate => sub { shift->() });
962 foreach my $type (keys %hooks) {
963 $hookids{$_}=1 foreach keys %{$hooks{$type}};
965 my @hookids=keys %hookids;
967 if (! -d $config{wikistatedir}) {
968 mkdir($config{wikistatedir});
970 my $newfile="$config{wikistatedir}/indexdb.new";
971 my $cleanup = sub { unlink($newfile) };
972 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
974 foreach my $page (keys %pagemtime) {
975 next unless $pagemtime{$page};
976 my $src=$pagesources{$page};
979 ctime => $pagectime{$page},
980 mtime => $pagemtime{$page},
981 dest => $renderedfiles{$page},
982 links => $links{$page},
985 if (exists $depends{$page}) {
986 $index{$src}{depends} = $depends{$page};
989 if (exists $pagestate{$page}) {
990 foreach my $id (@hookids) {
991 foreach my $key (keys %{$pagestate{$page}{$id}}) {
992 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
997 my $ret=Storable::nstore_fd(\%index, $out);
998 return if ! defined $ret || ! $ret;
999 close $out || error("failed saving to $newfile: $!", $cleanup);
1000 rename($newfile, "$config{wikistatedir}/indexdb") ||
1001 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1006 sub template_file ($) { #{{{
1009 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1010 return "$dir/$template" if -e "$dir/$template";
1015 sub template_params (@) { #{{{
1016 my $filename=template_file(shift);
1018 if (! defined $filename) {
1019 return if wantarray;
1025 my $text_ref = shift;
1026 ${$text_ref} = decode_utf8(${$text_ref});
1028 filename => $filename,
1029 loop_context_vars => 1,
1030 die_on_bad_params => 0,
1033 return wantarray ? @ret : {@ret};
1036 sub template ($;@) { #{{{
1037 require HTML::Template;
1038 return HTML::Template->new(template_params(@_));
1041 sub misctemplate ($$;@) { #{{{
1045 my $template=template("misc.tmpl");
1048 indexlink => indexlink(),
1049 wikiname => $config{wikiname},
1050 pagebody => $pagebody,
1051 baseurl => baseurl(),
1054 run_hooks(pagetemplate => sub {
1055 shift->(page => "", destpage => "", template => $template);
1057 return $template->output;
1060 sub hook (@) { # {{{
1063 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1064 error 'hook requires type, call, and id parameters';
1067 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1069 $hooks{$param{type}}{$param{id}}=\%param;
1073 sub run_hooks ($$) { # {{{
1074 # Calls the given sub for each hook of the given type,
1075 # passing it the hook function to call.
1079 if (exists $hooks{$type}) {
1081 foreach my $id (keys %{$hooks{$type}}) {
1082 if ($hooks{$type}{$id}{last}) {
1083 push @deferred, $id;
1086 $sub->($hooks{$type}{$id}{call});
1088 foreach my $id (@deferred) {
1089 $sub->($hooks{$type}{$id}{call});
1096 sub globlist_to_pagespec ($) { #{{{
1097 my @globlist=split(' ', shift);
1100 foreach my $glob (@globlist) {
1101 if ($glob=~/^!(.*)/) {
1109 my $spec=join(' or ', @spec);
1111 my $skip=join(' and ', @skip);
1113 $spec="$skip and ($spec)";
1122 sub is_globlist ($) { #{{{
1124 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1127 sub safequote ($) { #{{{
1133 sub add_depends ($$) { #{{{
1137 return unless pagespec_valid($pagespec);
1139 if (! exists $depends{$page}) {
1140 $depends{$page}=$pagespec;
1143 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1149 sub file_pruned ($$) { #{{{
1151 my $file=File::Spec->canonpath(shift);
1152 my $base=File::Spec->canonpath(shift);
1153 $file =~ s#^\Q$base\E/+##;
1155 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1156 return $file =~ m/$regexp/ && $file ne $base;
1160 # Only use gettext in the rare cases it's needed.
1161 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1162 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1163 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1164 if (! $gettext_obj) {
1165 $gettext_obj=eval q{
1166 use Locale::gettext q{textdomain};
1167 Locale::gettext->domain('ikiwiki')
1175 return $gettext_obj->get(shift);
1182 sub pagespec_merge ($$) { #{{{
1186 return $a if $a eq $b;
1188 # Support for old-style GlobLists.
1189 if (is_globlist($a)) {
1190 $a=globlist_to_pagespec($a);
1192 if (is_globlist($b)) {
1193 $b=globlist_to_pagespec($b);
1196 return "($a) or ($b)";
1199 sub pagespec_translate ($) { #{{{
1202 # Support for old-style GlobLists.
1203 if (is_globlist($spec)) {
1204 $spec=globlist_to_pagespec($spec);
1207 # Convert spec to perl code.
1210 \s* # ignore whitespace
1211 ( # 1: match a single word
1218 \w+\([^\)]*\) # command(params)
1220 [^\s()]+ # any other text
1222 \s* # ignore whitespace
1225 if (lc $word eq 'and') {
1228 elsif (lc $word eq 'or') {
1231 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1234 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1235 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1236 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1243 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1247 return eval 'sub { my $page=shift; '.$code.' }';
1250 sub pagespec_match ($$;@) { #{{{
1255 # Backwards compatability with old calling convention.
1257 unshift @params, 'location';
1260 my $sub=pagespec_translate($spec);
1261 return IkiWiki::FailReason->new('syntax error') if $@;
1262 return $sub->($page, @params);
1265 sub pagespec_valid ($) { #{{{
1268 my $sub=pagespec_translate($spec);
1272 package IkiWiki::FailReason;
1275 '""' => sub { ${$_[0]} },
1277 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1282 return bless \$_[1], $_[0];
1285 package IkiWiki::SuccessReason;
1288 '""' => sub { ${$_[0]} },
1290 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1295 return bless \$_[1], $_[0];
1298 package IkiWiki::PageSpec;
1300 sub match_glob ($$;@) { #{{{
1305 my $from=exists $params{location} ? $params{location} : '';
1308 if ($glob =~ m!^\./!) {
1309 $from=~s#/?[^/]+$##;
1311 $glob="$from/$glob" if length $from;
1314 # turn glob into safe regexp
1315 $glob=quotemeta($glob);
1319 if ($page=~/^$glob$/i) {
1320 if (! IkiWiki::isinternal($page) || $params{internal}) {
1321 return IkiWiki::SuccessReason->new("$glob matches $page");
1324 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1328 return IkiWiki::FailReason->new("$glob does not match $page");
1332 sub match_internal ($$;@) { #{{{
1333 return match_glob($_[0], $_[1], @_, internal => 1)
1336 sub match_link ($$;@) { #{{{
1341 my $from=exists $params{location} ? $params{location} : '';
1344 if ($link =~ m!^\.! && defined $from) {
1345 $from=~s#/?[^/]+$##;
1347 $link="$from/$link" if length $from;
1350 my $links = $IkiWiki::links{$page};
1351 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1352 my $bestlink = IkiWiki::bestlink($from, $link);
1353 foreach my $p (@{$links}) {
1354 if (length $bestlink) {
1355 return IkiWiki::SuccessReason->new("$page links to $link")
1356 if $bestlink eq IkiWiki::bestlink($page, $p);
1359 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1360 if match_glob($p, $link, %params);
1363 return IkiWiki::FailReason->new("$page does not link to $link");
1366 sub match_backlink ($$;@) { #{{{
1367 return match_link($_[1], $_[0], @_);
1370 sub match_created_before ($$;@) { #{{{
1374 if (exists $IkiWiki::pagectime{$testpage}) {
1375 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1376 return IkiWiki::SuccessReason->new("$page created before $testpage");
1379 return IkiWiki::FailReason->new("$page not created before $testpage");
1383 return IkiWiki::FailReason->new("$testpage has no ctime");
1387 sub match_created_after ($$;@) { #{{{
1391 if (exists $IkiWiki::pagectime{$testpage}) {
1392 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1393 return IkiWiki::SuccessReason->new("$page created after $testpage");
1396 return IkiWiki::FailReason->new("$page not created after $testpage");
1400 return IkiWiki::FailReason->new("$testpage has no ctime");
1404 sub match_creation_day ($$;@) { #{{{
1405 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1406 return IkiWiki::SuccessReason->new('creation_day matched');
1409 return IkiWiki::FailReason->new('creation_day did not match');
1413 sub match_creation_month ($$;@) { #{{{
1414 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1415 return IkiWiki::SuccessReason->new('creation_month matched');
1418 return IkiWiki::FailReason->new('creation_month did not match');
1422 sub match_creation_year ($$;@) { #{{{
1423 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1424 return IkiWiki::SuccessReason->new('creation_year matched');
1427 return IkiWiki::FailReason->new('creation_year did not match');