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,
92 sub checkconfig () { #{{{
93 # locale stuff; avoid LC_ALL since it overrides everything
94 if (defined $ENV{LC_ALL}) {
95 $ENV{LANG} = $ENV{LC_ALL};
98 if (defined $config{locale}) {
99 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
100 $ENV{LANG}=$config{locale};
105 if ($config{w3mmode}) {
106 eval q{use Cwd q{abs_path}};
108 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
109 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
110 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
111 unless $config{cgiurl} =~ m!file:///!;
112 $config{url}="file://".$config{destdir};
115 if ($config{cgi} && ! length $config{url}) {
116 error(gettext("Must specify url to wiki with --url when using --cgi"));
119 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
120 unless exists $config{wikistatedir};
123 eval qq{use IkiWiki::Rcs::$config{rcs}};
125 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
129 require IkiWiki::Rcs::Stub;
132 if (exists $config{umask}) {
133 umask(possibly_foolish_untaint($config{umask}));
136 run_hooks(checkconfig => sub { shift->() });
141 sub loadplugins () { #{{{
142 if (defined $config{libdir}) {
143 unshift @INC, possibly_foolish_untaint($config{libdir});
146 loadplugin($_) foreach @{$config{plugin}};
148 run_hooks(getopt => sub { shift->() });
149 if (grep /^-/, @ARGV) {
150 print STDERR "Unknown option: $_\n"
151 foreach grep /^-/, @ARGV;
158 sub loadplugin ($) { #{{{
161 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
163 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
164 "$installdir/lib/ikiwiki") {
165 if (defined $dir && -x "$dir/plugins/$plugin") {
166 require IkiWiki::Plugin::external;
167 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
172 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
175 error("Failed to load plugin $mod: $@");
180 sub error ($;$) { #{{{
184 print "Content-type: text/html\n\n";
185 print misctemplate(gettext("Error"),
186 "<p>".gettext("Error").": $message</p>");
188 log_message('err' => $message) if $config{syslog};
189 if (defined $cleaner) {
196 return unless $config{verbose};
197 return log_message(debug => @_);
201 sub log_message ($$) { #{{{
204 if ($config{syslog}) {
207 Sys::Syslog::setlogsock('unix');
208 Sys::Syslog::openlog('ikiwiki', '', 'user');
212 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
215 elsif (! $config{cgi}) {
219 return print STDERR "@_\n";
223 sub possibly_foolish_untaint ($) { #{{{
225 my ($untainted)=$tainted=~/(.*)/s;
229 sub basename ($) { #{{{
236 sub dirname ($) { #{{{
243 sub pagetype ($) { #{{{
246 if ($page =~ /\.([^.]+)$/) {
247 return $1 if exists $hooks{htmlize}{$1};
252 sub isinternal ($) { #{{{
254 return exists $pagesources{$page} &&
255 $pagesources{$page} =~ /\._([^.]+)$/;
258 sub pagename ($) { #{{{
261 my $type=pagetype($file);
263 $page=~s/\Q.$type\E*$// if defined $type;
267 sub targetpage ($$) { #{{{
271 if (! $config{usedirs} || $page =~ /^index$/ ) {
272 return $page.".".$ext;
274 return $page."/index.".$ext;
278 sub htmlpage ($) { #{{{
281 return targetpage($page, $config{htmlext});
284 sub srcfile ($) { #{{{
287 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
288 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
289 return "$dir/$file" if -e "$dir/$file";
291 error("internal error: $file cannot be found in $config{srcdir} or underlay");
295 sub add_underlay ($) { #{{{
299 unshift @{$config{underlaydirs}}, $dir;
302 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
308 sub readfile ($;$$) { #{{{
314 error("cannot read a symlink ($file)");
318 open (my $in, "<", $file) || error("failed to read $file: $!");
319 binmode($in) if ($binary);
320 return \*$in if $wantfd;
322 close $in || error("failed to read $file: $!");
326 sub writefile ($$$;$$) { #{{{
327 my $file=shift; # can include subdirs
328 my $destdir=shift; # directory to put file in
334 while (length $test) {
335 if (-l "$destdir/$test") {
336 error("cannot write to a symlink ($test)");
338 $test=dirname($test);
340 my $newfile="$destdir/$file.ikiwiki-new";
342 error("cannot write to a symlink ($newfile)");
345 my $dir=dirname($newfile);
348 foreach my $s (split(m!/+!, $dir)) {
351 mkdir($d) || error("failed to create directory $d: $!");
356 my $cleanup = sub { unlink($newfile) };
357 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
358 binmode($out) if ($binary);
360 $writer->(\*$out, $cleanup);
363 print $out $content or error("failed writing to $newfile: $!", $cleanup);
365 close $out || error("failed saving $newfile: $!", $cleanup);
366 rename($newfile, "$destdir/$file") ||
367 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
373 sub will_render ($$;$) { #{{{
378 # Important security check.
379 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
380 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
381 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
384 if (! $clear || $cleared{$page}) {
385 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
388 foreach my $old (@{$renderedfiles{$page}}) {
389 delete $destsources{$old};
391 $renderedfiles{$page}=[$dest];
394 $destsources{$dest}=$page;
399 sub bestlink ($$) { #{{{
404 if ($link=~s/^\/+//) {
412 $l.="/" if length $l;
415 if (exists $links{$l}) {
418 elsif (exists $pagecase{lc $l}) {
419 return $pagecase{lc $l};
421 } while $cwd=~s!/?[^/]+$!!;
423 if (length $config{userdir}) {
424 my $l = "$config{userdir}/".lc($link);
425 if (exists $links{$l}) {
428 elsif (exists $pagecase{lc $l}) {
429 return $pagecase{lc $l};
433 #print STDERR "warning: page $page, broken link: $link\n";
437 sub isinlinableimage ($) { #{{{
440 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
443 sub pagetitle ($;$) { #{{{
448 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
451 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
457 sub titlepage ($) { #{{{
459 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
463 sub linkpage ($) { #{{{
465 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
469 sub cgiurl (@) { #{{{
472 return $config{cgiurl}."?".
473 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
476 sub baseurl (;$) { #{{{
479 return "$config{url}/" if ! defined $page;
481 $page=htmlpage($page);
483 $page=~s/[^\/]+\//..\//g;
487 sub abs2rel ($$) { #{{{
488 # Work around very innefficient behavior in File::Spec if abs2rel
489 # is passed two relative paths. It's much faster if paths are
490 # absolute! (Debian bug #376658; fixed in debian unstable now)
495 my $ret=File::Spec->abs2rel($path, $base);
496 $ret=~s/^// if defined $ret;
500 sub displaytime ($;$) { #{{{
503 if (! defined $format) {
504 $format=$config{timeformat};
507 # strftime doesn't know about encodings, so make sure
508 # its output is properly treated as utf8
509 return decode_utf8(POSIX::strftime($format, localtime($time)));
512 sub beautify_url ($) { #{{{
515 if ($config{usedirs}) {
516 $url =~ s!/index.$config{htmlext}$!/!;
518 $url =~ s!^$!./!; # Browsers don't like empty links...
523 sub urlto ($$) { #{{{
528 return beautify_url(baseurl($from));
531 if (! $destsources{$to}) {
535 my $link = abs2rel($to, dirname(htmlpage($from)));
537 return beautify_url($link);
540 sub htmllink ($$$;@) { #{{{
541 my $lpage=shift; # the page doing the linking
542 my $page=shift; # the page that will contain the link (different for inline)
549 if (! $opts{forcesubpage}) {
550 $bestlink=bestlink($lpage, $link);
553 $bestlink="$lpage/".lc($link);
557 if (defined $opts{linktext}) {
558 $linktext=$opts{linktext};
561 $linktext=pagetitle(basename($link));
564 return "<span class=\"selflink\">$linktext</span>"
565 if length $bestlink && $page eq $bestlink &&
566 ! defined $opts{anchor};
568 if (! $destsources{$bestlink}) {
569 $bestlink=htmlpage($bestlink);
571 if (! $destsources{$bestlink}) {
572 return $linktext unless length $config{cgiurl};
573 return "<span class=\"createlink\"><a href=\"".
576 page => pagetitle(lc($link), 1),
579 "\">?</a>$linktext</span>"
583 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
584 $bestlink=beautify_url($bestlink);
586 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
587 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
590 if (defined $opts{anchor}) {
591 $bestlink.="#".$opts{anchor};
595 if (defined $opts{rel}) {
596 push @attrs, ' rel="'.$opts{rel}.'"';
598 if (defined $opts{class}) {
599 push @attrs, ' class="'.$opts{class}.'"';
602 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
605 sub userlink ($) { #{{{
608 my $oiduser=eval { openiduser($user) };
609 if (defined $oiduser) {
610 return "<a href=\"$user\">$oiduser</a>";
613 return htmllink("", "", escapeHTML(
614 length $config{userdir} ? $config{userdir}."/".$user : $user
615 ), noimageinline => 1);
619 sub htmlize ($$$) { #{{{
624 my $oneline = $content !~ /\n/;
626 if (exists $hooks{htmlize}{$type}) {
627 $content=$hooks{htmlize}{$type}{call}->(
633 error("htmlization of $type not supported");
636 run_hooks(sanitize => sub {
644 # hack to get rid of enclosing junk added by markdown
645 # and other htmlizers
647 $content=~s/<\/p>$//i;
654 sub linkify ($$$) { #{{{
659 run_hooks(linkify => sub {
662 destpage => $destpage,
671 our $preprocess_preview=0;
672 sub preprocess ($$$;$$) { #{{{
673 my $page=shift; # the page the data comes from
674 my $destpage=shift; # the page the data will appear in (different for inline)
679 # Using local because it needs to be set within any nested calls
681 local $preprocess_preview=$preview if defined $preview;
688 if (length $escape) {
689 return "[[$prefix$command $params]]";
691 elsif (exists $hooks{preprocess}{$command}) {
692 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
693 # Note: preserve order of params, some plugins may
694 # consider it significant.
697 (?:([-\w]+)=)? # 1: named parameter key?
699 """(.*?)""" # 2: triple-quoted value
701 "([^"]+)" # 3: single-quoted value
703 (\S+) # 4: unquoted value
705 (?:\s+|$) # delimiter to next param
723 push @params, $key, $val;
726 push @params, $val, '';
729 if ($preprocessing{$page}++ > 3) {
730 # Avoid loops of preprocessed pages preprocessing
731 # other pages that preprocess them, etc.
732 #translators: The first parameter is a
733 #translators: preprocessor directive name,
734 #translators: the second a page name, the
735 #translators: third a number.
736 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
737 $command, $page, $preprocessing{$page}).
742 $ret=$hooks{preprocess}{$command}{call}->(
745 destpage => $destpage,
746 preview => $preprocess_preview,
750 # use void context during scan pass
751 $hooks{preprocess}{$command}{call}->(
754 destpage => $destpage,
755 preview => $preprocess_preview,
759 $preprocessing{$page}--;
763 return "[[$prefix$command $params]]";
768 if ($config{prefix_directives}) {
771 \[\[(!) # directive open; 2: prefix
772 ([-\w]+) # 3: command
773 ( # 4: the parameters..
774 \s+ # Must have space if parameters present
776 (?:[-\w]+=)? # named parameter key?
778 """.*?""" # triple-quoted value
780 "[^"]+" # single-quoted value
782 [^\s\]]+ # unquoted value
784 \s* # whitespace or end
787 *)? # 0 or more parameters
788 \]\] # directive closed
793 \[\[(!?) # directive open; 2: optional prefix
794 ([-\w]+) # 3: command
796 ( # 4: the parameters..
798 (?:[-\w]+=)? # named parameter key?
800 """.*?""" # triple-quoted value
802 "[^"]+" # single-quoted value
804 [^\s\]]+ # unquoted value
806 \s* # whitespace or end
809 *) # 0 or more parameters
810 \]\] # directive closed
814 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
818 sub filter ($$$) { #{{{
823 run_hooks(filter => sub {
824 $content=shift->(page => $page, destpage => $destpage,
825 content => $content);
831 sub indexlink () { #{{{
832 return "<a href=\"$config{url}\">$config{wikiname}</a>";
837 sub lockwiki (;$) { #{{{
838 my $wait=@_ ? shift : 1;
839 # Take an exclusive lock on the wiki to prevent multiple concurrent
840 # run issues. The lock will be dropped on program exit.
841 if (! -d $config{wikistatedir}) {
842 mkdir($config{wikistatedir});
844 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
845 error ("cannot write to $config{wikistatedir}/lockfile: $!");
846 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
848 debug("wiki seems to be locked, waiting for lock");
849 my $wait=600; # arbitrary, but don't hang forever to
850 # prevent process pileup
852 return if flock($wikilock, 2 | 4);
855 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
864 sub unlockwiki () { #{{{
865 return close($wikilock) if $wikilock;
871 sub commit_hook_enabled () { #{{{
872 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
873 error("cannot write to $config{wikistatedir}/commitlock: $!");
874 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
875 close($commitlock) || error("failed closing commitlock: $!");
878 close($commitlock) || error("failed closing commitlock: $!");
882 sub disable_commit_hook () { #{{{
883 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
884 error("cannot write to $config{wikistatedir}/commitlock: $!");
885 if (! flock($commitlock, 2)) { # LOCK_EX
886 error("failed to get commit lock");
891 sub enable_commit_hook () { #{{{
892 return close($commitlock) if $commitlock;
896 sub loadindex () { #{{{
897 %oldrenderedfiles=%pagectime=();
898 if (! $config{rebuild}) {
899 %pagesources=%pagemtime=%oldlinks=%links=%depends=
900 %destsources=%renderedfiles=%pagecase=%pagestate=();
903 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
904 if (-e "$config{wikistatedir}/index") {
905 system("ikiwiki-transition", "indexdb", $config{srcdir});
906 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
912 my $ret=Storable::fd_retrieve($in);
913 if (! defined $ret) {
917 foreach my $src (keys %index) {
918 my %d=%{$index{$src}};
919 my $page=pagename($src);
920 $pagectime{$page}=$d{ctime};
921 if (! $config{rebuild}) {
922 $pagesources{$page}=$src;
923 $pagemtime{$page}=$d{mtime};
924 $renderedfiles{$page}=$d{dest};
925 if (exists $d{links} && ref $d{links}) {
926 $links{$page}=$d{links};
927 $oldlinks{$page}=[@{$d{links}}];
929 if (exists $d{depends}) {
930 $depends{$page}=$d{depends};
932 if (exists $d{state}) {
933 $pagestate{$page}=$d{state};
936 $oldrenderedfiles{$page}=[@{$d{dest}}];
938 foreach my $page (keys %pagesources) {
939 $pagecase{lc $page}=$page;
941 foreach my $page (keys %renderedfiles) {
942 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
947 sub saveindex () { #{{{
948 run_hooks(savestate => sub { shift->() });
951 foreach my $type (keys %hooks) {
952 $hookids{$_}=1 foreach keys %{$hooks{$type}};
954 my @hookids=keys %hookids;
956 if (! -d $config{wikistatedir}) {
957 mkdir($config{wikistatedir});
959 my $newfile="$config{wikistatedir}/indexdb.new";
960 my $cleanup = sub { unlink($newfile) };
961 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
963 foreach my $page (keys %pagemtime) {
964 next unless $pagemtime{$page};
965 my $src=$pagesources{$page};
968 ctime => $pagectime{$page},
969 mtime => $pagemtime{$page},
970 dest => $renderedfiles{$page},
971 links => $links{$page},
974 if (exists $depends{$page}) {
975 $index{$src}{depends} = $depends{$page};
978 if (exists $pagestate{$page}) {
979 foreach my $id (@hookids) {
980 foreach my $key (keys %{$pagestate{$page}{$id}}) {
981 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
986 my $ret=Storable::nstore_fd(\%index, $out);
987 return if ! defined $ret || ! $ret;
988 close $out || error("failed saving to $newfile: $!", $cleanup);
989 rename($newfile, "$config{wikistatedir}/indexdb") ||
990 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
995 sub template_file ($) { #{{{
998 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
999 return "$dir/$template" if -e "$dir/$template";
1004 sub template_params (@) { #{{{
1005 my $filename=template_file(shift);
1007 if (! defined $filename) {
1008 return if wantarray;
1014 my $text_ref = shift;
1015 ${$text_ref} = decode_utf8(${$text_ref});
1017 filename => $filename,
1018 loop_context_vars => 1,
1019 die_on_bad_params => 0,
1022 return wantarray ? @ret : {@ret};
1025 sub template ($;@) { #{{{
1026 require HTML::Template;
1027 return HTML::Template->new(template_params(@_));
1030 sub misctemplate ($$;@) { #{{{
1034 my $template=template("misc.tmpl");
1037 indexlink => indexlink(),
1038 wikiname => $config{wikiname},
1039 pagebody => $pagebody,
1040 baseurl => baseurl(),
1043 run_hooks(pagetemplate => sub {
1044 shift->(page => "", destpage => "", template => $template);
1046 return $template->output;
1049 sub hook (@) { # {{{
1052 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1053 error 'hook requires type, call, and id parameters';
1056 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1058 $hooks{$param{type}}{$param{id}}=\%param;
1062 sub run_hooks ($$) { # {{{
1063 # Calls the given sub for each hook of the given type,
1064 # passing it the hook function to call.
1068 if (exists $hooks{$type}) {
1070 foreach my $id (keys %{$hooks{$type}}) {
1071 if ($hooks{$type}{$id}{last}) {
1072 push @deferred, $id;
1075 $sub->($hooks{$type}{$id}{call});
1077 foreach my $id (@deferred) {
1078 $sub->($hooks{$type}{$id}{call});
1085 sub globlist_to_pagespec ($) { #{{{
1086 my @globlist=split(' ', shift);
1089 foreach my $glob (@globlist) {
1090 if ($glob=~/^!(.*)/) {
1098 my $spec=join(' or ', @spec);
1100 my $skip=join(' and ', @skip);
1102 $spec="$skip and ($spec)";
1111 sub is_globlist ($) { #{{{
1113 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1116 sub safequote ($) { #{{{
1122 sub add_depends ($$) { #{{{
1126 return unless pagespec_valid($pagespec);
1128 if (! exists $depends{$page}) {
1129 $depends{$page}=$pagespec;
1132 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1138 sub file_pruned ($$) { #{{{
1140 my $file=File::Spec->canonpath(shift);
1141 my $base=File::Spec->canonpath(shift);
1142 $file =~ s#^\Q$base\E/+##;
1144 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1145 return $file =~ m/$regexp/ && $file ne $base;
1149 # Only use gettext in the rare cases it's needed.
1150 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1151 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1152 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1153 if (! $gettext_obj) {
1154 $gettext_obj=eval q{
1155 use Locale::gettext q{textdomain};
1156 Locale::gettext->domain('ikiwiki')
1164 return $gettext_obj->get(shift);
1171 sub pagespec_merge ($$) { #{{{
1175 return $a if $a eq $b;
1177 # Support for old-style GlobLists.
1178 if (is_globlist($a)) {
1179 $a=globlist_to_pagespec($a);
1181 if (is_globlist($b)) {
1182 $b=globlist_to_pagespec($b);
1185 return "($a) or ($b)";
1188 sub pagespec_translate ($) { #{{{
1191 # Support for old-style GlobLists.
1192 if (is_globlist($spec)) {
1193 $spec=globlist_to_pagespec($spec);
1196 # Convert spec to perl code.
1199 \s* # ignore whitespace
1200 ( # 1: match a single word
1207 \w+\([^\)]*\) # command(params)
1209 [^\s()]+ # any other text
1211 \s* # ignore whitespace
1214 if (lc $word eq 'and') {
1217 elsif (lc $word eq 'or') {
1220 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1223 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1224 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1225 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1232 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1236 return eval 'sub { my $page=shift; '.$code.' }';
1239 sub pagespec_match ($$;@) { #{{{
1244 # Backwards compatability with old calling convention.
1246 unshift @params, 'location';
1249 my $sub=pagespec_translate($spec);
1250 return IkiWiki::FailReason->new('syntax error') if $@;
1251 return $sub->($page, @params);
1254 sub pagespec_valid ($) { #{{{
1257 my $sub=pagespec_translate($spec);
1261 package IkiWiki::FailReason;
1264 '""' => sub { ${$_[0]} },
1266 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1271 return bless \$_[1], $_[0];
1274 package IkiWiki::SuccessReason;
1277 '""' => sub { ${$_[0]} },
1279 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1284 return bless \$_[1], $_[0];
1287 package IkiWiki::PageSpec;
1289 sub match_glob ($$;@) { #{{{
1294 my $from=exists $params{location} ? $params{location} : '';
1297 if ($glob =~ m!^\./!) {
1298 $from=~s#/?[^/]+$##;
1300 $glob="$from/$glob" if length $from;
1303 # turn glob into safe regexp
1304 $glob=quotemeta($glob);
1308 if ($page=~/^$glob$/i) {
1309 if (! IkiWiki::isinternal($page) || $params{internal}) {
1310 return IkiWiki::SuccessReason->new("$glob matches $page");
1313 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1317 return IkiWiki::FailReason->new("$glob does not match $page");
1321 sub match_internal ($$;@) { #{{{
1322 return match_glob($_[0], $_[1], @_, internal => 1)
1325 sub match_link ($$;@) { #{{{
1330 my $from=exists $params{location} ? $params{location} : '';
1333 if ($link =~ m!^\.! && defined $from) {
1334 $from=~s#/?[^/]+$##;
1336 $link="$from/$link" if length $from;
1339 my $links = $IkiWiki::links{$page};
1340 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1341 my $bestlink = IkiWiki::bestlink($from, $link);
1342 foreach my $p (@{$links}) {
1343 if (length $bestlink) {
1344 return IkiWiki::SuccessReason->new("$page links to $link")
1345 if $bestlink eq IkiWiki::bestlink($page, $p);
1348 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1349 if match_glob($p, $link, %params);
1352 return IkiWiki::FailReason->new("$page does not link to $link");
1355 sub match_backlink ($$;@) { #{{{
1356 return match_link($_[1], $_[0], @_);
1359 sub match_created_before ($$;@) { #{{{
1363 if (exists $IkiWiki::pagectime{$testpage}) {
1364 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1365 return IkiWiki::SuccessReason->new("$page created before $testpage");
1368 return IkiWiki::FailReason->new("$page not created before $testpage");
1372 return IkiWiki::FailReason->new("$testpage has no ctime");
1376 sub match_created_after ($$;@) { #{{{
1380 if (exists $IkiWiki::pagectime{$testpage}) {
1381 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1382 return IkiWiki::SuccessReason->new("$page created after $testpage");
1385 return IkiWiki::FailReason->new("$page not created after $testpage");
1389 return IkiWiki::FailReason->new("$testpage has no ctime");
1393 sub match_creation_day ($$;@) { #{{{
1394 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1395 return IkiWiki::SuccessReason->new('creation_day matched');
1398 return IkiWiki::FailReason->new('creation_day did not match');
1402 sub match_creation_month ($$;@) { #{{{
1403 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1404 return IkiWiki::SuccessReason->new('creation_month matched');
1407 return IkiWiki::FailReason->new('creation_month did not match');
1411 sub match_creation_year ($$;@) { #{{{
1412 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1413 return IkiWiki::SuccessReason->new('creation_year matched');
1416 return IkiWiki::FailReason->new('creation_year did not match');