8 use URI::Escape q{uri_escape_utf8};
10 use open qw{:utf8 :std};
12 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
13 %pagestate %renderedfiles %oldrenderedfiles %pagesources
14 %destsources %depends %hooks %forcerebuild $gettext_obj};
16 use Exporter q{import};
17 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
18 bestlink htmllink readfile writefile pagetype srcfile pagename
19 displaytime will_render gettext urlto targetpage
21 %config %links %pagestate %renderedfiles
22 %pagesources %destsources);
23 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
24 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
25 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
30 memoize("pagespec_translate");
31 memoize("file_pruned");
33 sub defaultconfig () { #{{{
35 wiki_file_prune_regexps => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
36 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
37 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
40 wiki_link_regexp => qr{
41 \[\[ # beginning of link
43 ([^\]\|\n\s]+) # 1: link text
47 ([^\s\]#]+) # 2: page to link to
49 \# # '#', beginning of anchor
50 ([^\s\]]+) # 3: anchor text
55 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
56 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
60 default_pageext => "mdwn",
79 gitorigin_branch => "origin",
80 gitmaster_branch => "master",
84 templatedir => "$installdir/share/ikiwiki/templates",
85 underlaydir => "$installdir/share/ikiwiki/basewiki",
90 plugin => [qw{mdwn inline htmlscrubber passwordauth openid signinedit
91 lockedit conditional recentchanges}],
100 account_creation_password => "",
103 sub checkconfig () { #{{{
104 # locale stuff; avoid LC_ALL since it overrides everything
105 if (defined $ENV{LC_ALL}) {
106 $ENV{LANG} = $ENV{LC_ALL};
109 if (defined $config{locale}) {
110 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
111 $ENV{LANG}=$config{locale};
116 if ($config{w3mmode}) {
117 eval q{use Cwd q{abs_path}};
119 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
120 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
121 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
122 unless $config{cgiurl} =~ m!file:///!;
123 $config{url}="file://".$config{destdir};
126 if ($config{cgi} && ! length $config{url}) {
127 error(gettext("Must specify url to wiki with --url when using --cgi"));
130 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
131 unless exists $config{wikistatedir};
134 eval qq{use IkiWiki::Rcs::$config{rcs}};
136 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
140 require IkiWiki::Rcs::Stub;
143 if (exists $config{umask}) {
144 umask(possibly_foolish_untaint($config{umask}));
147 run_hooks(checkconfig => sub { shift->() });
152 sub loadplugins () { #{{{
153 if (defined $config{libdir}) {
154 unshift @INC, possibly_foolish_untaint($config{libdir});
157 loadplugin($_) foreach @{$config{plugin}};
159 run_hooks(getopt => sub { shift->() });
160 if (grep /^-/, @ARGV) {
161 print STDERR "Unknown option: $_\n"
162 foreach grep /^-/, @ARGV;
169 sub loadplugin ($) { #{{{
172 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
174 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
175 "$installdir/lib/ikiwiki") {
176 if (defined $dir && -x "$dir/plugins/$plugin") {
177 require IkiWiki::Plugin::external;
178 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
183 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
186 error("Failed to load plugin $mod: $@");
191 sub error ($;$) { #{{{
195 print "Content-type: text/html\n\n";
196 print misctemplate(gettext("Error"),
197 "<p>".gettext("Error").": $message</p>");
199 log_message('err' => $message) if $config{syslog};
200 if (defined $cleaner) {
207 return unless $config{verbose};
208 return log_message(debug => @_);
212 sub log_message ($$) { #{{{
215 if ($config{syslog}) {
218 Sys::Syslog::setlogsock('unix');
219 Sys::Syslog::openlog('ikiwiki', '', 'user');
223 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
226 elsif (! $config{cgi}) {
230 return print STDERR "@_\n";
234 sub possibly_foolish_untaint ($) { #{{{
236 my ($untainted)=$tainted=~/(.*)/s;
240 sub basename ($) { #{{{
247 sub dirname ($) { #{{{
254 sub pagetype ($) { #{{{
257 if ($page =~ /\.([^.]+)$/) {
258 return $1 if exists $hooks{htmlize}{$1};
263 sub isinternal ($) { #{{{
265 return exists $pagesources{$page} &&
266 $pagesources{$page} =~ /\._([^.]+)$/;
269 sub pagename ($) { #{{{
272 my $type=pagetype($file);
274 $page=~s/\Q.$type\E*$// if defined $type;
278 sub targetpage ($$) { #{{{
282 if (! $config{usedirs} || $page =~ /^index$/ ) {
283 return $page.".".$ext;
285 return $page."/index.".$ext;
289 sub htmlpage ($) { #{{{
292 return targetpage($page, $config{htmlext});
295 sub srcfile ($) { #{{{
298 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
299 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
300 return "$dir/$file" if -e "$dir/$file";
302 error("internal error: $file cannot be found in $config{srcdir} or underlay");
306 sub add_underlay ($) { #{{{
310 unshift @{$config{underlaydirs}}, $dir;
313 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
319 sub readfile ($;$$) { #{{{
325 error("cannot read a symlink ($file)");
329 open (my $in, "<", $file) || error("failed to read $file: $!");
330 binmode($in) if ($binary);
331 return \*$in if $wantfd;
333 close $in || error("failed to read $file: $!");
337 sub writefile ($$$;$$) { #{{{
338 my $file=shift; # can include subdirs
339 my $destdir=shift; # directory to put file in
345 while (length $test) {
346 if (-l "$destdir/$test") {
347 error("cannot write to a symlink ($test)");
349 $test=dirname($test);
351 my $newfile="$destdir/$file.ikiwiki-new";
353 error("cannot write to a symlink ($newfile)");
356 my $dir=dirname($newfile);
359 foreach my $s (split(m!/+!, $dir)) {
362 mkdir($d) || error("failed to create directory $d: $!");
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 ($$$) { #{{{
666 my $lpage=shift; # the page containing the links
667 my $page=shift; # the page the link will end up on (different for inline)
670 $content =~ s{(\\?)$config{wiki_link_regexp}}{
673 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
674 : htmllink($lpage, $page, linkpage($3),
675 anchor => $4, linktext => pagetitle($2)))
677 ? "[[$3".($4 ? "#$4" : "")."]]"
678 : htmllink($lpage, $page, linkpage($3),
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;
702 if (length $escape) {
703 return "[[$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 "[[$command $params]]";
783 \[\[ # directive open
784 ([-\w]+) # 2: command
786 ( # 3: the parameters..
788 (?:[-\w]+=)? # named parameter key?
790 """.*?""" # triple-quoted value
792 "[^"]+" # single-quoted value
794 [^\s\]]+ # unquoted value
796 \s* # whitespace or end
799 *) # 0 or more parameters
800 \]\] # directive closed
801 }{$handle->($1, $2, $3)}sexg;
805 sub filter ($$$) { #{{{
810 run_hooks(filter => sub {
811 $content=shift->(page => $page, destpage => $destpage,
812 content => $content);
818 sub indexlink () { #{{{
819 return "<a href=\"$config{url}\">$config{wikiname}</a>";
824 sub lockwiki (;$) { #{{{
825 my $wait=@_ ? shift : 1;
826 # Take an exclusive lock on the wiki to prevent multiple concurrent
827 # run issues. The lock will be dropped on program exit.
828 if (! -d $config{wikistatedir}) {
829 mkdir($config{wikistatedir});
831 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
832 error ("cannot write to $config{wikistatedir}/lockfile: $!");
833 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
835 debug("wiki seems to be locked, waiting for lock");
836 my $wait=600; # arbitrary, but don't hang forever to
837 # prevent process pileup
839 return if flock($wikilock, 2 | 4);
842 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
851 sub unlockwiki () { #{{{
852 return close($wikilock) if $wikilock;
858 sub commit_hook_enabled () { #{{{
859 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
860 error("cannot write to $config{wikistatedir}/commitlock: $!");
861 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
862 close($commitlock) || error("failed closing commitlock: $!");
865 close($commitlock) || error("failed closing commitlock: $!");
869 sub disable_commit_hook () { #{{{
870 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
871 error("cannot write to $config{wikistatedir}/commitlock: $!");
872 if (! flock($commitlock, 2)) { # LOCK_EX
873 error("failed to get commit lock");
878 sub enable_commit_hook () { #{{{
879 return close($commitlock) if $commitlock;
883 sub loadindex () { #{{{
884 %oldrenderedfiles=%pagectime=();
885 if (! $config{rebuild}) {
886 %pagesources=%pagemtime=%oldlinks=%links=%depends=
887 %destsources=%renderedfiles=%pagecase=();
889 open (my $in, "<", "$config{wikistatedir}/index") || return;
891 $_=possibly_foolish_untaint($_);
896 foreach my $i (split(/ /, $_)) {
897 my ($item, $val)=split(/=/, $i, 2);
898 push @{$items{$item}}, decode_entities($val);
901 next unless exists $items{src}; # skip bad lines for now
903 my $page=pagename($items{src}[0]);
904 if (! $config{rebuild}) {
905 $pagesources{$page}=$items{src}[0];
906 $pagemtime{$page}=$items{mtime}[0];
907 $oldlinks{$page}=[@{$items{link}}];
908 $links{$page}=[@{$items{link}}];
909 $depends{$page}=$items{depends}[0] if exists $items{depends};
910 $destsources{$_}=$page foreach @{$items{dest}};
911 $renderedfiles{$page}=[@{$items{dest}}];
912 $pagecase{lc $page}=$page;
913 foreach my $k (grep /_/, keys %items) {
914 my ($id, $key)=split(/_/, $k, 2);
915 $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
918 $oldrenderedfiles{$page}=[@{$items{dest}}];
919 $pagectime{$page}=$items{ctime}[0];
924 sub saveindex () { #{{{
925 run_hooks(savestate => sub { shift->() });
928 foreach my $type (keys %hooks) {
929 $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
931 my @hookids=sort keys %hookids;
933 if (! -d $config{wikistatedir}) {
934 mkdir($config{wikistatedir});
936 my $newfile="$config{wikistatedir}/index.new";
937 my $cleanup = sub { unlink($newfile) };
938 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
939 foreach my $page (keys %pagemtime) {
940 next unless $pagemtime{$page};
941 my $line="mtime=$pagemtime{$page} ".
942 "ctime=$pagectime{$page} ".
943 "src=$pagesources{$page}";
944 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
946 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
947 if (exists $depends{$page}) {
948 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
950 if (exists $pagestate{$page}) {
951 foreach my $id (@hookids) {
952 foreach my $key (keys %{$pagestate{$page}{$id}}) {
953 $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key}, " \t\n");
957 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
959 close $out || error("failed saving to $newfile: $!", $cleanup);
960 rename($newfile, "$config{wikistatedir}/index") ||
961 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
966 sub template_file ($) { #{{{
969 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
970 return "$dir/$template" if -e "$dir/$template";
975 sub template_params (@) { #{{{
976 my $filename=template_file(shift);
978 if (! defined $filename) {
985 my $text_ref = shift;
986 ${$text_ref} = decode_utf8(${$text_ref});
988 filename => $filename,
989 loop_context_vars => 1,
990 die_on_bad_params => 0,
993 return wantarray ? @ret : {@ret};
996 sub template ($;@) { #{{{
997 require HTML::Template;
998 return HTML::Template->new(template_params(@_));
1001 sub misctemplate ($$;@) { #{{{
1005 my $template=template("misc.tmpl");
1008 indexlink => indexlink(),
1009 wikiname => $config{wikiname},
1010 pagebody => $pagebody,
1011 baseurl => baseurl(),
1014 run_hooks(pagetemplate => sub {
1015 shift->(page => "", destpage => "", template => $template);
1017 return $template->output;
1020 sub hook (@) { # {{{
1023 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1024 error 'hook requires type, call, and id parameters';
1027 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1029 $hooks{$param{type}}{$param{id}}=\%param;
1033 sub run_hooks ($$) { # {{{
1034 # Calls the given sub for each hook of the given type,
1035 # passing it the hook function to call.
1039 if (exists $hooks{$type}) {
1041 foreach my $id (keys %{$hooks{$type}}) {
1042 if ($hooks{$type}{$id}{last}) {
1043 push @deferred, $id;
1046 $sub->($hooks{$type}{$id}{call});
1048 foreach my $id (@deferred) {
1049 $sub->($hooks{$type}{$id}{call});
1056 sub globlist_to_pagespec ($) { #{{{
1057 my @globlist=split(' ', shift);
1060 foreach my $glob (@globlist) {
1061 if ($glob=~/^!(.*)/) {
1069 my $spec=join(' or ', @spec);
1071 my $skip=join(' and ', @skip);
1073 $spec="$skip and ($spec)";
1082 sub is_globlist ($) { #{{{
1084 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1087 sub safequote ($) { #{{{
1093 sub add_depends ($$) { #{{{
1097 if (! exists $depends{$page}) {
1098 $depends{$page}=$pagespec;
1101 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1107 sub file_pruned ($$) { #{{{
1109 my $file=File::Spec->canonpath(shift);
1110 my $base=File::Spec->canonpath(shift);
1111 $file =~ s#^\Q$base\E/+##;
1113 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1114 return $file =~ m/$regexp/ && $file ne $base;
1118 # Only use gettext in the rare cases it's needed.
1119 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1120 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1121 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1122 if (! $gettext_obj) {
1123 $gettext_obj=eval q{
1124 use Locale::gettext q{textdomain};
1125 Locale::gettext->domain('ikiwiki')
1133 return $gettext_obj->get(shift);
1140 sub pagespec_merge ($$) { #{{{
1144 return $a if $a eq $b;
1146 # Support for old-style GlobLists.
1147 if (is_globlist($a)) {
1148 $a=globlist_to_pagespec($a);
1150 if (is_globlist($b)) {
1151 $b=globlist_to_pagespec($b);
1154 return "($a) or ($b)";
1157 sub pagespec_translate ($) { #{{{
1158 # This assumes that $page is in scope in the function
1159 # that evalulates the translated pagespec code.
1162 # Support for old-style GlobLists.
1163 if (is_globlist($spec)) {
1164 $spec=globlist_to_pagespec($spec);
1167 # Convert spec to perl code.
1170 \s* # ignore whitespace
1171 ( # 1: match a single word
1178 \w+\([^\)]*\) # command(params)
1180 [^\s()]+ # any other text
1182 \s* # ignore whitespace
1185 if (lc $word eq 'and') {
1188 elsif (lc $word eq 'or') {
1191 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1194 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1195 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1196 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1203 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1210 sub pagespec_match ($$;@) { #{{{
1215 # Backwards compatability with old calling convention.
1217 unshift @params, 'location';
1220 my $ret=eval pagespec_translate($spec);
1221 return IkiWiki::FailReason->new('syntax error') if $@;
1225 package IkiWiki::FailReason;
1228 '""' => sub { ${$_[0]} },
1230 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1235 return bless \$_[1], $_[0];
1238 package IkiWiki::SuccessReason;
1241 '""' => sub { ${$_[0]} },
1243 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1248 return bless \$_[1], $_[0];
1251 package IkiWiki::PageSpec;
1253 sub match_glob ($$;@) { #{{{
1258 my $from=exists $params{location} ? $params{location} : '';
1261 if ($glob =~ m!^\./!) {
1262 $from=~s#/?[^/]+$##;
1264 $glob="$from/$glob" if length $from;
1267 # turn glob into safe regexp
1268 $glob=quotemeta($glob);
1272 if ($page=~/^$glob$/i) {
1273 if (! IkiWiki::isinternal($page) || $params{internal}) {
1274 return IkiWiki::SuccessReason->new("$glob matches $page");
1277 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1281 return IkiWiki::FailReason->new("$glob does not match $page");
1285 sub match_internal ($$;@) { #{{{
1286 return match_glob($_[0], $_[1], @_, internal => 1)
1289 sub match_link ($$;@) { #{{{
1294 my $from=exists $params{location} ? $params{location} : '';
1297 if ($link =~ m!^\.! && defined $from) {
1298 $from=~s#/?[^/]+$##;
1300 $link="$from/$link" if length $from;
1303 my $links = $IkiWiki::links{$page};
1304 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1305 my $bestlink = IkiWiki::bestlink($from, $link);
1306 foreach my $p (@{$links}) {
1307 if (length $bestlink) {
1308 return IkiWiki::SuccessReason->new("$page links to $link")
1309 if $bestlink eq IkiWiki::bestlink($page, $p);
1312 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1313 if match_glob($p, $link, %params);
1316 return IkiWiki::FailReason->new("$page does not link to $link");
1319 sub match_backlink ($$;@) { #{{{
1320 return match_link($_[1], $_[0], @_);
1323 sub match_created_before ($$;@) { #{{{
1327 if (exists $IkiWiki::pagectime{$testpage}) {
1328 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1329 return IkiWiki::SuccessReason->new("$page created before $testpage");
1332 return IkiWiki::FailReason->new("$page not created before $testpage");
1336 return IkiWiki::FailReason->new("$testpage has no ctime");
1340 sub match_created_after ($$;@) { #{{{
1344 if (exists $IkiWiki::pagectime{$testpage}) {
1345 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1346 return IkiWiki::SuccessReason->new("$page created after $testpage");
1349 return IkiWiki::FailReason->new("$page not created after $testpage");
1353 return IkiWiki::FailReason->new("$testpage has no ctime");
1357 sub match_creation_day ($$;@) { #{{{
1358 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1359 return IkiWiki::SuccessReason->new('creation_day matched');
1362 return IkiWiki::FailReason->new('creation_day did not match');
1366 sub match_creation_month ($$;@) { #{{{
1367 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1368 return IkiWiki::SuccessReason->new('creation_month matched');
1371 return IkiWiki::FailReason->new('creation_month did not match');
1375 sub match_creation_year ($$;@) { #{{{
1376 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1377 return IkiWiki::SuccessReason->new('creation_year matched');
1380 return IkiWiki::FailReason->new('creation_year did not match');