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_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
41 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
45 default_pageext => "mdwn",
66 gitorigin_branch => "origin",
67 gitmaster_branch => "master",
71 templatedir => "$installdir/share/ikiwiki/templates",
72 underlaydir => "$installdir/share/ikiwiki/basewiki",
77 plugin => [qw{mdwn link inline htmlscrubber passwordauth openid
78 signinedit lockedit conditional recentchanges}],
87 account_creation_password => "",
88 prefix_directives => 0,
91 sub checkconfig () { #{{{
92 # locale stuff; avoid LC_ALL since it overrides everything
93 if (defined $ENV{LC_ALL}) {
94 $ENV{LANG} = $ENV{LC_ALL};
97 if (defined $config{locale}) {
98 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
99 $ENV{LANG}=$config{locale};
104 if ($config{w3mmode}) {
105 eval q{use Cwd q{abs_path}};
107 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
108 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
109 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
110 unless $config{cgiurl} =~ m!file:///!;
111 $config{url}="file://".$config{destdir};
114 if ($config{cgi} && ! length $config{url}) {
115 error(gettext("Must specify url to wiki with --url when using --cgi"));
118 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
119 unless exists $config{wikistatedir};
122 eval qq{use IkiWiki::Rcs::$config{rcs}};
124 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
128 require IkiWiki::Rcs::Stub;
131 if (exists $config{umask}) {
132 umask(possibly_foolish_untaint($config{umask}));
135 run_hooks(checkconfig => sub { shift->() });
140 sub loadplugins () { #{{{
141 if (defined $config{libdir}) {
142 unshift @INC, possibly_foolish_untaint($config{libdir});
145 loadplugin($_) foreach @{$config{plugin}};
147 run_hooks(getopt => sub { shift->() });
148 if (grep /^-/, @ARGV) {
149 print STDERR "Unknown option: $_\n"
150 foreach grep /^-/, @ARGV;
157 sub loadplugin ($) { #{{{
160 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
162 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
163 "$installdir/lib/ikiwiki") {
164 if (defined $dir && -x "$dir/plugins/$plugin") {
165 require IkiWiki::Plugin::external;
166 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
171 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
174 error("Failed to load plugin $mod: $@");
179 sub error ($;$) { #{{{
183 print "Content-type: text/html\n\n";
184 print misctemplate(gettext("Error"),
185 "<p>".gettext("Error").": $message</p>");
187 log_message('err' => $message) if $config{syslog};
188 if (defined $cleaner) {
195 return unless $config{verbose};
196 return log_message(debug => @_);
200 sub log_message ($$) { #{{{
203 if ($config{syslog}) {
206 Sys::Syslog::setlogsock('unix');
207 Sys::Syslog::openlog('ikiwiki', '', 'user');
211 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
214 elsif (! $config{cgi}) {
218 return print STDERR "@_\n";
222 sub possibly_foolish_untaint ($) { #{{{
224 my ($untainted)=$tainted=~/(.*)/s;
228 sub basename ($) { #{{{
235 sub dirname ($) { #{{{
242 sub pagetype ($) { #{{{
245 if ($page =~ /\.([^.]+)$/) {
246 return $1 if exists $hooks{htmlize}{$1};
251 sub isinternal ($) { #{{{
253 return exists $pagesources{$page} &&
254 $pagesources{$page} =~ /\._([^.]+)$/;
257 sub pagename ($) { #{{{
260 my $type=pagetype($file);
262 $page=~s/\Q.$type\E*$// if defined $type;
266 sub targetpage ($$) { #{{{
270 if (! $config{usedirs} || $page =~ /^index$/ ) {
271 return $page.".".$ext;
273 return $page."/index.".$ext;
277 sub htmlpage ($) { #{{{
280 return targetpage($page, $config{htmlext});
283 sub srcfile ($) { #{{{
286 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
287 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
288 return "$dir/$file" if -e "$dir/$file";
290 error("internal error: $file cannot be found in $config{srcdir} or underlay");
294 sub add_underlay ($) { #{{{
298 unshift @{$config{underlaydirs}}, $dir;
301 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
307 sub readfile ($;$$) { #{{{
313 error("cannot read a symlink ($file)");
317 open (my $in, "<", $file) || error("failed to read $file: $!");
318 binmode($in) if ($binary);
319 return \*$in if $wantfd;
321 close $in || error("failed to read $file: $!");
325 sub writefile ($$$;$$) { #{{{
326 my $file=shift; # can include subdirs
327 my $destdir=shift; # directory to put file in
333 while (length $test) {
334 if (-l "$destdir/$test") {
335 error("cannot write to a symlink ($test)");
337 $test=dirname($test);
339 my $newfile="$destdir/$file.ikiwiki-new";
341 error("cannot write to a symlink ($newfile)");
344 my $dir=dirname($newfile);
347 foreach my $s (split(m!/+!, $dir)) {
350 mkdir($d) || error("failed to create directory $d: $!");
355 my $cleanup = sub { unlink($newfile) };
356 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
357 binmode($out) if ($binary);
359 $writer->(\*$out, $cleanup);
362 print $out $content or error("failed writing to $newfile: $!", $cleanup);
364 close $out || error("failed saving $newfile: $!", $cleanup);
365 rename($newfile, "$destdir/$file") ||
366 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
372 sub will_render ($$;$) { #{{{
377 # Important security check.
378 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
379 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
380 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
383 if (! $clear || $cleared{$page}) {
384 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
387 foreach my $old (@{$renderedfiles{$page}}) {
388 delete $destsources{$old};
390 $renderedfiles{$page}=[$dest];
393 $destsources{$dest}=$page;
398 sub bestlink ($$) { #{{{
403 if ($link=~s/^\/+//) {
411 $l.="/" if length $l;
414 if (exists $links{$l}) {
417 elsif (exists $pagecase{lc $l}) {
418 return $pagecase{lc $l};
420 } while $cwd=~s!/?[^/]+$!!;
422 if (length $config{userdir}) {
423 my $l = "$config{userdir}/".lc($link);
424 if (exists $links{$l}) {
427 elsif (exists $pagecase{lc $l}) {
428 return $pagecase{lc $l};
432 #print STDERR "warning: page $page, broken link: $link\n";
436 sub isinlinableimage ($) { #{{{
439 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
442 sub pagetitle ($;$) { #{{{
447 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
450 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
456 sub titlepage ($) { #{{{
458 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
462 sub linkpage ($) { #{{{
464 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
468 sub cgiurl (@) { #{{{
471 return $config{cgiurl}."?".
472 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
475 sub baseurl (;$) { #{{{
478 return "$config{url}/" if ! defined $page;
480 $page=htmlpage($page);
482 $page=~s/[^\/]+\//..\//g;
486 sub abs2rel ($$) { #{{{
487 # Work around very innefficient behavior in File::Spec if abs2rel
488 # is passed two relative paths. It's much faster if paths are
489 # absolute! (Debian bug #376658; fixed in debian unstable now)
494 my $ret=File::Spec->abs2rel($path, $base);
495 $ret=~s/^// if defined $ret;
499 sub displaytime ($;$) { #{{{
502 if (! defined $format) {
503 $format=$config{timeformat};
506 # strftime doesn't know about encodings, so make sure
507 # its output is properly treated as utf8
508 return decode_utf8(POSIX::strftime($format, localtime($time)));
511 sub beautify_url ($) { #{{{
514 if ($config{usedirs}) {
515 $url =~ s!/index.$config{htmlext}$!/!;
517 $url =~ s!^$!./!; # Browsers don't like empty links...
522 sub urlto ($$) { #{{{
527 return beautify_url(baseurl($from));
530 if (! $destsources{$to}) {
534 my $link = abs2rel($to, dirname(htmlpage($from)));
536 return beautify_url($link);
539 sub htmllink ($$$;@) { #{{{
540 my $lpage=shift; # the page doing the linking
541 my $page=shift; # the page that will contain the link (different for inline)
548 if (! $opts{forcesubpage}) {
549 $bestlink=bestlink($lpage, $link);
552 $bestlink="$lpage/".lc($link);
556 if (defined $opts{linktext}) {
557 $linktext=$opts{linktext};
560 $linktext=pagetitle(basename($link));
563 return "<span class=\"selflink\">$linktext</span>"
564 if length $bestlink && $page eq $bestlink &&
565 ! defined $opts{anchor};
567 if (! $destsources{$bestlink}) {
568 $bestlink=htmlpage($bestlink);
570 if (! $destsources{$bestlink}) {
571 return $linktext unless length $config{cgiurl};
572 return "<span class=\"createlink\"><a href=\"".
575 page => pagetitle(lc($link), 1),
578 "\">?</a>$linktext</span>"
582 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
583 $bestlink=beautify_url($bestlink);
585 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
586 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
589 if (defined $opts{anchor}) {
590 $bestlink.="#".$opts{anchor};
594 if (defined $opts{rel}) {
595 push @attrs, ' rel="'.$opts{rel}.'"';
597 if (defined $opts{class}) {
598 push @attrs, ' class="'.$opts{class}.'"';
601 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
604 sub userlink ($) { #{{{
607 my $oiduser=eval { openiduser($user) };
608 if (defined $oiduser) {
609 return "<a href=\"$user\">$oiduser</a>";
612 return htmllink("", "", escapeHTML(
613 length $config{userdir} ? $config{userdir}."/".$user : $user
614 ), noimageinline => 1);
618 sub htmlize ($$$) { #{{{
623 my $oneline = $content !~ /\n/;
625 if (exists $hooks{htmlize}{$type}) {
626 $content=$hooks{htmlize}{$type}{call}->(
632 error("htmlization of $type not supported");
635 run_hooks(sanitize => sub {
643 # hack to get rid of enclosing junk added by markdown
644 # and other htmlizers
646 $content=~s/<\/p>$//i;
653 sub linkify ($$$) { #{{{
658 run_hooks(linkify => sub {
661 destpage => $destpage,
670 our $preprocess_preview=0;
671 sub preprocess ($$$;$$) { #{{{
672 my $page=shift; # the page the data comes from
673 my $destpage=shift; # the page the data will appear in (different for inline)
678 # Using local because it needs to be set within any nested calls
680 local $preprocess_preview=$preview if defined $preview;
687 if (length $escape) {
688 return "[[$prefix$command $params]]";
690 elsif (exists $hooks{preprocess}{$command}) {
691 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
692 # Note: preserve order of params, some plugins may
693 # consider it significant.
696 (?:([-\w]+)=)? # 1: named parameter key?
698 """(.*?)""" # 2: triple-quoted value
700 "([^"]+)" # 3: single-quoted value
702 (\S+) # 4: unquoted value
704 (?:\s+|$) # delimiter to next param
722 push @params, $key, $val;
725 push @params, $val, '';
728 if ($preprocessing{$page}++ > 3) {
729 # Avoid loops of preprocessed pages preprocessing
730 # other pages that preprocess them, etc.
731 #translators: The first parameter is a
732 #translators: preprocessor directive name,
733 #translators: the second a page name, the
734 #translators: third a number.
735 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
736 $command, $page, $preprocessing{$page}).
741 $ret=$hooks{preprocess}{$command}{call}->(
744 destpage => $destpage,
745 preview => $preprocess_preview,
749 # use void context during scan pass
750 $hooks{preprocess}{$command}{call}->(
753 destpage => $destpage,
754 preview => $preprocess_preview,
758 $preprocessing{$page}--;
762 return "[[$prefix$command $params]]";
767 if ($config{prefix_directives}) {
770 \[\[(!) # directive open; 2: prefix
771 ([-\w]+) # 3: command
772 ( # 4: the parameters..
773 \s+ # Must have space if parameters present
775 (?:[-\w]+=)? # named parameter key?
777 """.*?""" # triple-quoted value
779 "[^"]+" # single-quoted value
781 [^\s\]]+ # unquoted value
783 \s* # whitespace or end
786 *)? # 0 or more parameters
787 \]\] # directive closed
792 \[\[(!?) # directive open; 2: optional prefix
793 ([-\w]+) # 3: command
795 ( # 4: the parameters..
797 (?:[-\w]+=)? # named parameter key?
799 """.*?""" # triple-quoted value
801 "[^"]+" # single-quoted value
803 [^\s\]]+ # unquoted value
805 \s* # whitespace or end
808 *) # 0 or more parameters
809 \]\] # directive closed
813 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
817 sub filter ($$$) { #{{{
822 run_hooks(filter => sub {
823 $content=shift->(page => $page, destpage => $destpage,
824 content => $content);
830 sub indexlink () { #{{{
831 return "<a href=\"$config{url}\">$config{wikiname}</a>";
836 sub lockwiki (;$) { #{{{
837 my $wait=@_ ? shift : 1;
838 # Take an exclusive lock on the wiki to prevent multiple concurrent
839 # run issues. The lock will be dropped on program exit.
840 if (! -d $config{wikistatedir}) {
841 mkdir($config{wikistatedir});
843 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
844 error ("cannot write to $config{wikistatedir}/lockfile: $!");
845 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
847 debug("wiki seems to be locked, waiting for lock");
848 my $wait=600; # arbitrary, but don't hang forever to
849 # prevent process pileup
851 return if flock($wikilock, 2 | 4);
854 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
863 sub unlockwiki () { #{{{
864 return close($wikilock) if $wikilock;
870 sub commit_hook_enabled () { #{{{
871 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
872 error("cannot write to $config{wikistatedir}/commitlock: $!");
873 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
874 close($commitlock) || error("failed closing commitlock: $!");
877 close($commitlock) || error("failed closing commitlock: $!");
881 sub disable_commit_hook () { #{{{
882 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
883 error("cannot write to $config{wikistatedir}/commitlock: $!");
884 if (! flock($commitlock, 2)) { # LOCK_EX
885 error("failed to get commit lock");
890 sub enable_commit_hook () { #{{{
891 return close($commitlock) if $commitlock;
895 sub loadindex () { #{{{
896 %oldrenderedfiles=%pagectime=();
897 if (! $config{rebuild}) {
898 %pagesources=%pagemtime=%oldlinks=%links=%depends=
899 %destsources=%renderedfiles=%pagecase=%pagestate=();
901 open (my $in, "<", "$config{wikistatedir}/index") || return;
903 $_=possibly_foolish_untaint($_);
908 foreach my $i (split(/ /, $_)) {
909 my ($item, $val)=split(/=/, $i, 2);
910 push @{$items{$item}}, decode_entities($val);
913 next unless exists $items{src}; # skip bad lines for now
915 my $page=pagename($items{src}[0]);
916 if (! $config{rebuild}) {
917 $pagesources{$page}=$items{src}[0];
918 $pagemtime{$page}=$items{mtime}[0];
919 $oldlinks{$page}=[@{$items{link}}];
920 $links{$page}=[@{$items{link}}];
921 $depends{$page}=$items{depends}[0] if exists $items{depends};
922 $destsources{$_}=$page foreach @{$items{dest}};
923 $renderedfiles{$page}=[@{$items{dest}}];
924 $pagecase{lc $page}=$page;
925 foreach my $k (grep /_/, keys %items) {
926 my ($id, $key)=split(/_/, $k, 2);
927 $pagestate{$page}{decode_entities($id)}{decode_entities($key)}=$items{$k}[0];
930 $oldrenderedfiles{$page}=[@{$items{dest}}];
931 $pagectime{$page}=$items{ctime}[0];
936 sub saveindex () { #{{{
937 run_hooks(savestate => sub { shift->() });
940 foreach my $type (keys %hooks) {
941 $hookids{encode_entities($_)}=1 foreach keys %{$hooks{$type}};
943 my @hookids=sort keys %hookids;
945 if (! -d $config{wikistatedir}) {
946 mkdir($config{wikistatedir});
948 my $newfile="$config{wikistatedir}/index.new";
949 my $cleanup = sub { unlink($newfile) };
950 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
951 foreach my $page (keys %pagemtime) {
952 next unless $pagemtime{$page};
953 my $line="mtime=$pagemtime{$page} ".
954 "ctime=$pagectime{$page} ".
955 "src=$pagesources{$page}";
956 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
958 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
959 if (exists $depends{$page}) {
960 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
962 if (exists $pagestate{$page}) {
963 foreach my $id (@hookids) {
964 foreach my $key (keys %{$pagestate{$page}{$id}}) {
965 $line.=' '.$id.'_'.encode_entities($key)."=".encode_entities($pagestate{$page}{$id}{$key}, " \t\n");
969 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
971 close $out || error("failed saving to $newfile: $!", $cleanup);
972 rename($newfile, "$config{wikistatedir}/index") ||
973 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
978 sub template_file ($) { #{{{
981 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
982 return "$dir/$template" if -e "$dir/$template";
987 sub template_params (@) { #{{{
988 my $filename=template_file(shift);
990 if (! defined $filename) {
997 my $text_ref = shift;
998 ${$text_ref} = decode_utf8(${$text_ref});
1000 filename => $filename,
1001 loop_context_vars => 1,
1002 die_on_bad_params => 0,
1005 return wantarray ? @ret : {@ret};
1008 sub template ($;@) { #{{{
1009 require HTML::Template;
1010 return HTML::Template->new(template_params(@_));
1013 sub misctemplate ($$;@) { #{{{
1017 my $template=template("misc.tmpl");
1020 indexlink => indexlink(),
1021 wikiname => $config{wikiname},
1022 pagebody => $pagebody,
1023 baseurl => baseurl(),
1026 run_hooks(pagetemplate => sub {
1027 shift->(page => "", destpage => "", template => $template);
1029 return $template->output;
1032 sub hook (@) { # {{{
1035 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1036 error 'hook requires type, call, and id parameters';
1039 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1041 $hooks{$param{type}}{$param{id}}=\%param;
1045 sub run_hooks ($$) { # {{{
1046 # Calls the given sub for each hook of the given type,
1047 # passing it the hook function to call.
1051 if (exists $hooks{$type}) {
1053 foreach my $id (keys %{$hooks{$type}}) {
1054 if ($hooks{$type}{$id}{last}) {
1055 push @deferred, $id;
1058 $sub->($hooks{$type}{$id}{call});
1060 foreach my $id (@deferred) {
1061 $sub->($hooks{$type}{$id}{call});
1068 sub globlist_to_pagespec ($) { #{{{
1069 my @globlist=split(' ', shift);
1072 foreach my $glob (@globlist) {
1073 if ($glob=~/^!(.*)/) {
1081 my $spec=join(' or ', @spec);
1083 my $skip=join(' and ', @skip);
1085 $spec="$skip and ($spec)";
1094 sub is_globlist ($) { #{{{
1096 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1099 sub safequote ($) { #{{{
1105 sub add_depends ($$) { #{{{
1109 if (! exists $depends{$page}) {
1110 $depends{$page}=$pagespec;
1113 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1119 sub file_pruned ($$) { #{{{
1121 my $file=File::Spec->canonpath(shift);
1122 my $base=File::Spec->canonpath(shift);
1123 $file =~ s#^\Q$base\E/+##;
1125 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1126 return $file =~ m/$regexp/ && $file ne $base;
1130 # Only use gettext in the rare cases it's needed.
1131 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1132 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1133 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1134 if (! $gettext_obj) {
1135 $gettext_obj=eval q{
1136 use Locale::gettext q{textdomain};
1137 Locale::gettext->domain('ikiwiki')
1145 return $gettext_obj->get(shift);
1152 sub pagespec_merge ($$) { #{{{
1156 return $a if $a eq $b;
1158 # Support for old-style GlobLists.
1159 if (is_globlist($a)) {
1160 $a=globlist_to_pagespec($a);
1162 if (is_globlist($b)) {
1163 $b=globlist_to_pagespec($b);
1166 return "($a) or ($b)";
1169 sub pagespec_translate ($) { #{{{
1170 # This assumes that $page is in scope in the function
1171 # that evalulates the translated pagespec code.
1174 # Support for old-style GlobLists.
1175 if (is_globlist($spec)) {
1176 $spec=globlist_to_pagespec($spec);
1179 # Convert spec to perl code.
1182 \s* # ignore whitespace
1183 ( # 1: match a single word
1190 \w+\([^\)]*\) # command(params)
1192 [^\s()]+ # any other text
1194 \s* # ignore whitespace
1197 if (lc $word eq 'and') {
1200 elsif (lc $word eq 'or') {
1203 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1206 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1207 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1208 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1215 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1222 sub pagespec_match ($$;@) { #{{{
1227 # Backwards compatability with old calling convention.
1229 unshift @params, 'location';
1232 my $ret=eval pagespec_translate($spec);
1233 return IkiWiki::FailReason->new('syntax error') if $@;
1237 package IkiWiki::FailReason;
1240 '""' => sub { ${$_[0]} },
1242 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1247 return bless \$_[1], $_[0];
1250 package IkiWiki::SuccessReason;
1253 '""' => sub { ${$_[0]} },
1255 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1260 return bless \$_[1], $_[0];
1263 package IkiWiki::PageSpec;
1265 sub match_glob ($$;@) { #{{{
1270 my $from=exists $params{location} ? $params{location} : '';
1273 if ($glob =~ m!^\./!) {
1274 $from=~s#/?[^/]+$##;
1276 $glob="$from/$glob" if length $from;
1279 # turn glob into safe regexp
1280 $glob=quotemeta($glob);
1284 if ($page=~/^$glob$/i) {
1285 if (! IkiWiki::isinternal($page) || $params{internal}) {
1286 return IkiWiki::SuccessReason->new("$glob matches $page");
1289 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1293 return IkiWiki::FailReason->new("$glob does not match $page");
1297 sub match_internal ($$;@) { #{{{
1298 return match_glob($_[0], $_[1], @_, internal => 1)
1301 sub match_link ($$;@) { #{{{
1306 my $from=exists $params{location} ? $params{location} : '';
1309 if ($link =~ m!^\.! && defined $from) {
1310 $from=~s#/?[^/]+$##;
1312 $link="$from/$link" if length $from;
1315 my $links = $IkiWiki::links{$page};
1316 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1317 my $bestlink = IkiWiki::bestlink($from, $link);
1318 foreach my $p (@{$links}) {
1319 if (length $bestlink) {
1320 return IkiWiki::SuccessReason->new("$page links to $link")
1321 if $bestlink eq IkiWiki::bestlink($page, $p);
1324 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1325 if match_glob($p, $link, %params);
1328 return IkiWiki::FailReason->new("$page does not link to $link");
1331 sub match_backlink ($$;@) { #{{{
1332 return match_link($_[1], $_[0], @_);
1335 sub match_created_before ($$;@) { #{{{
1339 if (exists $IkiWiki::pagectime{$testpage}) {
1340 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1341 return IkiWiki::SuccessReason->new("$page created before $testpage");
1344 return IkiWiki::FailReason->new("$page not created before $testpage");
1348 return IkiWiki::FailReason->new("$testpage has no ctime");
1352 sub match_created_after ($$;@) { #{{{
1356 if (exists $IkiWiki::pagectime{$testpage}) {
1357 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1358 return IkiWiki::SuccessReason->new("$page created after $testpage");
1361 return IkiWiki::FailReason->new("$page not created after $testpage");
1365 return IkiWiki::FailReason->new("$testpage has no ctime");
1369 sub match_creation_day ($$;@) { #{{{
1370 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1371 return IkiWiki::SuccessReason->new('creation_day matched');
1374 return IkiWiki::FailReason->new('creation_day did not match');
1378 sub match_creation_month ($$;@) { #{{{
1379 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1380 return IkiWiki::SuccessReason->new('creation_month matched');
1383 return IkiWiki::FailReason->new('creation_month did not match');
1387 sub match_creation_year ($$;@) { #{{{
1388 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1389 return IkiWiki::SuccessReason->new('creation_year matched');
1392 return IkiWiki::FailReason->new('creation_year did not match');