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 %wikistate %renderedfiles %oldrenderedfiles
15 %pagesources %delpagesources %destsources %depends %depends_simple
16 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17 %oldtypedlinks %autofiles};
19 use Exporter
q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21 deptype add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link add_autofile
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
40 memoize("sortspec_translate");
41 memoize("pagespec_translate");
42 memoize("template_file");
48 description => "name of the wiki",
55 example => 'me@example.com',
56 description => "contact email for wiki",
63 description => "users who are wiki admins",
70 description => "users who are banned from the wiki",
77 example => "$ENV{HOME}/wiki",
78 description => "where the source of the wiki is located",
85 example => "/var/www/wiki",
86 description => "where to build the wiki",
93 example => "http://example.com/wiki",
94 description => "base url to the wiki",
101 example => "http://example.com/wiki/ikiwiki.cgi",
102 description => "url to the ikiwiki.cgi",
109 example => "/var/www/wiki/ikiwiki.cgi",
110 description => "filename of cgi wrapper to generate",
117 description => "mode for cgi_wrapper (can safely be made suid)",
124 description => "rcs backend to use",
125 safe => 0, # don't allow overriding
130 default => [qw{mdwn link inline meta htmlscrubber passwordauth
131 openid signinedit lockedit conditional
132 recentchanges parentlinks editpage}],
133 description => "plugins to enable by default",
140 description => "plugins to add to the default configuration",
147 description => "plugins to disable",
153 default => "$installdir/share/ikiwiki/templates",
154 description => "additional directory to search for template files",
161 default => "$installdir/share/ikiwiki/basewiki",
162 description => "base wiki source location",
169 default => "$installdir/share/ikiwiki",
170 description => "parent directory containing additional underlays",
177 description => "wrappers to generate",
184 description => "additional underlays to use",
191 description => "display verbose messages?",
198 description => "log to syslog?",
205 description => "create output files named page/index.html?",
206 safe => 0, # changing requires manual transition
209 prefix_directives => {
212 description => "use '!'-prefixed preprocessor directives?",
213 safe => 0, # changing requires manual transition
219 description => "use page/index.mdwn source files",
226 description => "enable Discussion pages?",
232 default => gettext("Discussion"),
233 description => "name of Discussion pages",
240 description => "generate HTML5? (experimental)",
248 description => "only send cookies over SSL connections?",
256 description => "extension to use for new pages",
257 safe => 0, # not sanitized
263 description => "extension to use for html files",
264 safe => 0, # not sanitized
270 description => "strftime format string to display date",
278 example => "en_US.UTF-8",
279 description => "UTF-8 locale to use",
288 description => "put user pages below specified page",
295 description => "how many backlinks to show before hiding excess (0 to show all)",
302 description => "attempt to hardlink source files? (optimisation for large files)",
304 safe => 0, # paranoia
310 description => "force ikiwiki to use a particular umask",
312 safe => 0, # paranoia
317 example => "ikiwiki",
318 description => "group for wrappers to run in",
320 safe => 0, # paranoia
326 example => "$ENV{HOME}/.ikiwiki/",
327 description => "extra library and plugin directory",
329 safe => 0, # directory
335 description => "environment variables",
336 safe => 0, # paranoia
342 example => '^\.htaccess$',
343 description => "regexp of normally excluded files to include",
351 example => '^(*\.private|Makefile)$',
352 description => "regexp of files that should be skipped",
357 wiki_file_prune_regexps => {
359 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
360 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
361 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
362 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
363 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
364 description => "regexps of source files to ignore",
370 description => "specifies the characters that are allowed in source filenames",
371 default => "-[:alnum:]+/.:_",
375 wiki_file_regexp => {
377 description => "regexp of legal source files",
381 web_commit_regexp => {
383 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
384 description => "regexp to parse web commits from logs",
391 description => "run as a cgi",
395 cgi_disable_uploads => {
398 description => "whether CGI should accept file uploads",
405 description => "run as a post-commit hook",
412 description => "running in rebuild mode",
419 description => "running in setup mode",
426 description => "running in clean mode",
433 description => "running in refresh mode",
440 description => "running in receive test mode",
444 wrapper_background_command => {
447 description => "background shell command to run",
453 description => "running in gettime mode",
460 description => "running in w3mmode",
467 description => "path to the .ikiwiki directory holding ikiwiki state",
474 description => "path to setup file",
480 default => "Standard",
481 description => "perl class to use to dump setup file",
485 allow_symlinks_before_srcdir => {
488 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
494 sub defaultconfig () {
497 foreach my $key (keys %s) {
498 push @ret, $key, $s{$key}->{default};
504 # URL to top of wiki as a path starting with /, valid from any wiki page or
505 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
507 # URL to CGI script, similar to $local_url
511 # locale stuff; avoid LC_ALL since it overrides everything
512 if (defined $ENV{LC_ALL}) {
513 $ENV{LANG} = $ENV{LC_ALL};
516 if (defined $config{locale}) {
517 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
518 $ENV{LANG}=$config{locale};
523 if (! defined $config{wiki_file_regexp}) {
524 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
527 if (ref $config{ENV} eq 'HASH') {
528 foreach my $val (keys %{$config{ENV}}) {
529 $ENV{$val}=$config{ENV}{$val};
533 if ($config{w3mmode}) {
534 eval q{use Cwd q{abs_path}};
536 $config{srcdir
}=possibly_foolish_untaint
(abs_path
($config{srcdir
}));
537 $config{destdir
}=possibly_foolish_untaint
(abs_path
($config{destdir
}));
538 $config{cgiurl
}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl
}
539 unless $config{cgiurl
} =~ m!file:///!;
540 $config{url
}="file://".$config{destdir
};
543 if ($config{cgi
} && ! length $config{url
}) {
544 error
(gettext
("Must specify url to wiki with --url when using --cgi"));
547 if (defined $config{url
} && length $config{url
}) {
549 my $baseurl = URI
->new($config{url
});
551 $local_url = $baseurl->path . "/";
552 $local_cgiurl = undef;
554 if (length $config{cgiurl
}) {
555 my $cgiurl = URI
->new($config{cgiurl
});
557 $local_cgiurl = $cgiurl->path;
559 if ($cgiurl->scheme ne $baseurl->scheme or
560 $cgiurl->authority ne $baseurl->authority) {
561 # too far apart, fall back to absolute URLs
562 $local_url = "$config{url}/";
563 $local_cgiurl = $config{cgiurl
};
567 $local_url =~ s{//$}{/};
570 $local_cgiurl = $config{cgiurl
};
573 $config{wikistatedir
}="$config{srcdir}/.ikiwiki"
574 unless exists $config{wikistatedir
} && defined $config{wikistatedir
};
576 if (defined $config{umask}) {
577 umask(possibly_foolish_untaint
($config{umask}));
580 run_hooks
(checkconfig
=> sub { shift->() });
588 foreach my $dir (@INC, $config{libdir
}) {
589 next unless defined $dir && length $dir;
590 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
591 my ($plugin)=$file=~/.*\/(.*)\
.pm
$/;
595 foreach my $dir ($config{libdir
}, "$installdir/lib/ikiwiki") {
596 next unless defined $dir && length $dir;
597 foreach my $file (glob("$dir/plugins/*")) {
598 $ret{basename
($file)}=1 if -x
$file;
606 if (defined $config{libdir
} && length $config{libdir
}) {
607 unshift @INC, possibly_foolish_untaint
($config{libdir
});
610 foreach my $plugin (@
{$config{default_plugins
}}, @
{$config{add_plugins
}}) {
615 if (exists $hooks{rcs
}) {
616 error
(gettext
("cannot use multiple rcs plugins"));
618 loadplugin
($config{rcs
});
620 if (! exists $hooks{rcs
}) {
624 run_hooks
(getopt
=> sub { shift->() });
625 if (grep /^-/, @ARGV) {
626 print STDERR
"Unknown option (or missing parameter): $_\n"
627 foreach grep /^-/, @ARGV;
634 sub loadplugin
($;$) {
638 return if ! $force && grep { $_ eq $plugin} @
{$config{disable_plugins
}};
640 foreach my $dir (defined $config{libdir
} ? possibly_foolish_untaint
($config{libdir
}) : undef,
641 "$installdir/lib/ikiwiki") {
642 if (defined $dir && -x
"$dir/plugins/$plugin") {
643 eval { require IkiWiki
::Plugin
::external
};
646 error
(sprintf(gettext
("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
648 import IkiWiki
::Plugin
::external
"$dir/plugins/$plugin";
649 $loaded_plugins{$plugin}=1;
654 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint
($plugin);
657 error
("Failed to load plugin $mod: $@");
659 $loaded_plugins{$plugin}=1;
666 log_message
('err' => $message) if $config{syslog
};
667 if (defined $cleaner) {
674 return unless $config{verbose
};
675 return log_message
(debug
=> @_);
679 sub log_message
($$) {
682 if ($config{syslog
}) {
685 Sys
::Syslog
::setlogsock
('unix');
686 Sys
::Syslog
::openlog
('ikiwiki', '', 'user');
690 Sys
::Syslog
::syslog
($type, "[$config{wikiname}] %s", join(" ", @_));
693 elsif (! $config{cgi
}) {
697 return print STDERR
"@_\n";
701 sub possibly_foolish_untaint
($) {
703 my ($untainted)=$tainted=~/(.*)/s;
723 return exists $pagesources{$page} &&
724 $pagesources{$page} =~ /\._([^.]+)$/;
730 if ($file =~ /\.([^.]+)$/) {
731 return $1 if exists $hooks{htmlize
}{$1};
733 my $base=basename
($file);
734 if (exists $hooks{htmlize
}{$base} &&
735 $hooks{htmlize
}{$base}{noextension
}) {
746 if (exists $pagename_cache{$file}) {
747 return $pagename_cache{$file};
750 my $type=pagetype
($file);
752 $page=~s/\Q.$type\E*$//
753 if defined $type && !$hooks{htmlize
}{$type}{keepextension
}
754 && !$hooks{htmlize
}{$type}{noextension
};
755 if ($config{indexpages
} && $page=~/(.*)\/index
$/) {
759 $pagename_cache{$file} = $page;
763 sub newpagefile
($$) {
767 if (! $config{indexpages
} || $page eq 'index') {
768 return $page.".".$type;
771 return $page."/index.".$type;
775 sub targetpage
($$;$) {
780 if (defined $filename) {
781 return $page."/".$filename.".".$ext;
783 elsif (! $config{usedirs
} || $page eq 'index') {
784 return $page.".".$ext;
787 return $page."/index.".$ext;
794 return targetpage
($page, $config{htmlext
});
801 return "$config{srcdir}/$file", stat(_
) if -e
"$config{srcdir}/$file";
802 foreach my $dir (@
{$config{underlaydirs
}}, $config{underlaydir
}) {
803 return "$dir/$file", stat(_
) if -e
"$dir/$file";
805 error
("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
810 return (srcfile_stat
(@_))[0];
813 sub add_underlay
($) {
817 $dir="$config{underlaydirbase}/$dir";
820 if (! grep { $_ eq $dir } @
{$config{underlaydirs
}}) {
821 unshift @
{$config{underlaydirs
}}, $dir;
827 sub readfile
($;$$) {
833 error
("cannot read a symlink ($file)");
837 open (my $in, "<", $file) || error
("failed to read $file: $!");
838 binmode($in) if ($binary);
839 return \
*$in if $wantfd;
841 # check for invalid utf-8, and toss it back to avoid crashes
842 if (! utf8
::valid
($ret)) {
843 $ret=encode_utf8
($ret);
845 close $in || error
("failed to read $file: $!");
849 sub prep_writefile
($$) {
854 while (length $test) {
855 if (-l
"$destdir/$test") {
856 error
("cannot write to a symlink ($test)");
858 if (-f _
&& $test ne $file) {
859 # Remove conflicting file.
860 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
861 foreach my $f (@
{$renderedfiles{$p}}, @
{$oldrenderedfiles{$p}}) {
863 unlink("$destdir/$test");
869 $test=dirname
($test);
872 my $dir=dirname
("$destdir/$file");
875 foreach my $s (split(m!/+!, $dir)) {
878 mkdir($d) || error
("failed to create directory $d: $!");
886 sub writefile
($$$;$$) {
887 my $file=shift; # can include subdirs
888 my $destdir=shift; # directory to put file in
893 prep_writefile
($file, $destdir);
895 my $newfile="$destdir/$file.ikiwiki-new";
897 error
("cannot write to a symlink ($newfile)");
900 my $cleanup = sub { unlink($newfile) };
901 open (my $out, '>', $newfile) || error
("failed to write $newfile: $!", $cleanup);
902 binmode($out) if ($binary);
904 $writer->(\
*$out, $cleanup);
907 print $out $content or error
("failed writing to $newfile: $!", $cleanup);
909 close $out || error
("failed saving $newfile: $!", $cleanup);
910 rename($newfile, "$destdir/$file") ||
911 error
("failed renaming $newfile to $destdir/$file: $!", $cleanup);
917 sub will_render
($$;$) {
922 # Important security check for independently created files.
923 if (-e
"$config{destdir}/$dest" && ! $config{rebuild
} &&
924 ! grep { $_ eq $dest } (@
{$renderedfiles{$page}}, @
{$oldrenderedfiles{$page}}, @
{$wikistate{editpage
}{previews
}})) {
925 my $from_other_page=0;
926 # Expensive, but rarely runs.
927 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
931 } @
{$renderedfiles{$p}}, @
{$oldrenderedfiles{$p}}) {
937 error
("$config{destdir}/$dest independently created, not overwriting with version from $page")
938 unless $from_other_page;
941 # If $dest exists as a directory, remove conflicting files in it
942 # rendered from other pages.
944 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
945 foreach my $f (@
{$renderedfiles{$p}}, @
{$oldrenderedfiles{$p}}) {
946 if (dirname
($f) eq $dest) {
947 unlink("$config{destdir}/$f");
948 rmdir(dirname
("$config{destdir}/$f"));
954 if (! $clear || $cleared{$page}) {
955 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @
{$renderedfiles{$page}}];
958 foreach my $old (@
{$renderedfiles{$page}}) {
959 delete $destsources{$old};
961 $renderedfiles{$page}=[$dest];
964 $destsources{$dest}=$page;
974 if ($link=~s/^\/+//) {
982 $l.="/" if length $l;
985 if (exists $pagesources{$l}) {
988 elsif (exists $pagecase{lc $l}) {
989 return $pagecase{lc $l};
991 } while $cwd=~s{/?[^/]+$}{};
993 if (length $config{userdir
}) {
994 my $l = "$config{userdir}/".lc($link);
995 if (exists $pagesources{$l}) {
998 elsif (exists $pagecase{lc $l}) {
999 return $pagecase{lc $l};
1003 #print STDERR "warning: page $page, broken link: $link\n";
1007 sub isinlinableimage
($) {
1010 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
1013 sub pagetitle
($;$) {
1015 my $unescaped=shift;
1018 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1021 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1029 # support use w/o %config set
1030 my $chars = defined $config{wiki_file_chars
} ?
$config{wiki_file_chars
} : "-[:alnum:]+/.:_";
1031 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1037 my $chars = defined $config{wiki_file_chars
} ?
$config{wiki_file_chars
} : "-[:alnum:]+/.:_";
1038 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1045 my $cgiurl=$local_cgiurl;
1047 if (exists $params{cgiurl
}) {
1048 $cgiurl=$params{cgiurl
};
1049 delete $params{cgiurl
};
1057 join("&", map $_."=".uri_escape_utf8
($params{$_}), keys %params);
1063 return $local_url if ! defined $page;
1065 $page=htmlpage
($page);
1067 $page=~s/[^\/]+\//..\//g
;
1075 return $url unless defined $urlbase && length $urlbase;
1078 URI
->new_abs($url, $urlbase)->as_string;
1082 # Work around very innefficient behavior in File::Spec if abs2rel
1083 # is passed two relative paths. It's much faster if paths are
1084 # absolute! (Debian bug #376658; fixed in debian unstable now)
1089 my $ret=File
::Spec
->abs2rel($path, $base);
1090 $ret=~s/^// if defined $ret;
1094 sub displaytime
($;$$) {
1095 # Plugins can override this function to mark up the time to
1097 my $time=formattime
($_[0], $_[1]);
1098 if ($config{html5
}) {
1099 return '<time datetime="'.date_3339
($_[0]).'"'.
1100 ($_[2] ?
' pubdate="pubdate"' : '').
1101 '>'.$time.'</time>';
1104 return '<span class="date">'.$time.'</span>';
1108 sub formattime
($;$) {
1109 # Plugins can override this function to format the time.
1112 if (! defined $format) {
1113 $format=$config{timeformat
};
1116 # strftime doesn't know about encodings, so make sure
1117 # its output is properly treated as utf8
1118 return decode_utf8
(POSIX
::strftime
($format, localtime($time)));
1124 my $lc_time=POSIX
::setlocale
(&POSIX
::LC_TIME
);
1125 POSIX
::setlocale
(&POSIX
::LC_TIME
, "C");
1126 my $ret=POSIX
::strftime
("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1127 POSIX
::setlocale
(&POSIX
::LC_TIME
, $lc_time);
1131 sub beautify_urlpath
($) {
1134 # Ensure url is not an empty link, and if necessary,
1135 # add ./ to avoid colon confusion.
1136 if ($url !~ /^\// && $url !~ /^\
.\
.?\
//) {
1140 if ($config{usedirs
}) {
1141 $url =~ s!/index.$config{htmlext}$!/!;
1156 if (! $destsources{$to}) {
1161 return $config{url
}.beautify_urlpath
("/".$to);
1164 if (! defined $from) {
1167 return $u.beautify_urlpath
("/".$to);
1170 my $link = abs2rel
($to, dirname
(htmlpage
($from)));
1172 return beautify_urlpath
($link);
1175 sub isselflink
($$) {
1176 # Plugins can override this function to support special types
1181 return $page eq $link;
1184 sub htmllink
($$$;@
) {
1185 my $lpage=shift; # the page doing the linking
1186 my $page=shift; # the page that will contain the link (different for inline)
1193 if (! $opts{forcesubpage
}) {
1194 $bestlink=bestlink
($lpage, $link);
1197 $bestlink="$lpage/".lc($link);
1201 if (defined $opts{linktext
}) {
1202 $linktext=$opts{linktext
};
1205 $linktext=pagetitle
(basename
($link));
1208 return "<span class=\"selflink\">$linktext</span>"
1209 if length $bestlink && isselflink
($page, $bestlink) &&
1210 ! defined $opts{anchor
};
1212 if (! $destsources{$bestlink}) {
1213 $bestlink=htmlpage
($bestlink);
1215 if (! $destsources{$bestlink}) {
1217 if (length $config{cgiurl
}) {
1218 $cgilink = "<a href=\"".
1223 )."\" rel=\"nofollow\">?</a>";
1225 return "<span class=\"createlink\">$cgilink$linktext</span>"
1229 $bestlink=abs2rel
($bestlink, dirname
(htmlpage
($page)));
1230 $bestlink=beautify_urlpath
($bestlink);
1232 if (! $opts{noimageinline
} && isinlinableimage
($bestlink)) {
1233 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1236 if (defined $opts{anchor
}) {
1237 $bestlink.="#".$opts{anchor
};
1241 foreach my $attr (qw{rel
class title
}) {
1242 if (defined $opts{$attr}) {
1243 push @attrs, " $attr=\"$opts{$attr}\"";
1247 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1252 return length $config{userdir
} ?
"$config{userdir}/$user" : $user;
1255 sub openiduser
($) {
1258 if (defined $user && $user =~ m!^https?://! &&
1259 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@
) {
1262 if (Net
::OpenID
::VerifiedIdentity
->can("DisplayOfURL")) {
1263 $display = Net
::OpenID
::VerifiedIdentity
::DisplayOfURL
($user);
1266 # backcompat with old version
1267 my $oid=Net
::OpenID
::VerifiedIdentity
->new(identity
=> $user);
1268 $display=$oid->display;
1271 # Convert "user.somehost.com" to "user [somehost.com]"
1272 # (also "user.somehost.co.uk")
1273 if ($display !~ /\[/) {
1274 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1276 # Convert "http://somehost.com/user" to "user [somehost.com]".
1277 # (also "https://somehost.com/user/")
1278 if ($display !~ /\[/) {
1279 $display=~s/^https?:\/\/(.+)\
/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1281 $display=~s!^https?://!!; # make sure this is removed
1282 eval q{use CGI 'escapeHTML'};
1284 return escapeHTML
($display);
1289 sub htmlize
($$$$) {
1295 my $oneline = $content !~ /\n/;
1297 if (exists $hooks{htmlize
}{$type}) {
1298 $content=$hooks{htmlize
}{$type}{call
}->(
1300 content
=> $content,
1304 error
("htmlization of $type not supported");
1307 run_hooks
(sanitize
=> sub {
1310 destpage
=> $destpage,
1311 content
=> $content,
1316 # hack to get rid of enclosing junk added by markdown
1317 # and other htmlizers/sanitizers
1318 $content=~s/^<p>//i;
1319 $content=~s/<\/p>\n*$//i
;
1330 run_hooks
(linkify
=> sub {
1333 destpage
=> $destpage,
1334 content
=> $content,
1342 our $preprocess_preview=0;
1343 sub preprocess
($$$;$$) {
1344 my $page=shift; # the page the data comes from
1345 my $destpage=shift; # the page the data will appear in (different for inline)
1350 # Using local because it needs to be set within any nested calls
1352 local $preprocess_preview=$preview if defined $preview;
1359 $params="" if ! defined $params;
1361 if (length $escape) {
1362 return "[[$prefix$command $params]]";
1364 elsif (exists $hooks{preprocess
}{$command}) {
1365 return "" if $scan && ! $hooks{preprocess
}{$command}{scan
};
1366 # Note: preserve order of params, some plugins may
1367 # consider it significant.
1369 while ($params =~ m
{
1370 (?
:([-\w
]+)=)?
# 1: named parameter key?
1372 """(.*?)""" # 2: triple-quoted value
1374 "([^"]*?
)" # 3: single-quoted value
1376 (\S+) # 4: unquoted value
1378 (?:\s+|$) # delimiter to next param
1388 elsif (defined $3) {
1391 elsif (defined $4) {
1396 push @params, $key, $val;
1399 push @params, $val, '';
1402 if ($preprocessing{$page}++ > 3) {
1403 # Avoid loops of preprocessed pages preprocessing
1404 # other pages that preprocess them, etc.
1405 return "[[!$command <span
class=\"error
\">".
1406 sprintf(gettext("preprocessing
loop detected on
%s at depth
%i"),
1407 $page, $preprocessing{$page}).
1413 $hooks{preprocess}{$command}{call}->(
1416 destpage => $destpage,
1417 preview => $preprocess_preview,
1423 $ret="[[!$command <span
class=\"error
\">".
1424 gettext("Error
").": $error"."</span
>]]";
1428 # use void context during scan pass
1430 $hooks{preprocess}{$command}{call}->(
1433 destpage => $destpage,
1434 preview => $preprocess_preview,
1439 $preprocessing{$page}--;
1443 return "[[$prefix$command $params]]";
1448 if ($config{prefix_directives}) {
1451 \[\[(!) # directive open; 2: prefix
1452 ([-\w]+) # 3: command
1453 ( # 4: the parameters..
1454 \s+ # Must have space if parameters present
1456 (?:[-\w]+=)? # named parameter key?
1458 """.*?
""" # triple-quoted value
1460 "[^"]*?" # single-quoted value
1462 [^"\s\]]+ # unquoted value
1464 \s* # whitespace or end
1467 *)? # 0 or more parameters
1468 \]\] # directive closed
1474 \[\[(!?) # directive open; 2: optional prefix
1475 ([-\w]+) # 3: command
1477 ( # 4: the parameters..
1479 (?:[-\w]+=)? # named parameter key?
1481 """.*?
""" # triple-quoted value
1483 "[^"]*?" # single-quoted value
1485 [^"\s\]]+ # unquoted value
1487 \s* # whitespace or end
1490 *) # 0 or more parameters
1491 \]\] # directive closed
1495 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1504 run_hooks(filter => sub {
1505 $content=shift->(page => $page, destpage => $destpage,
1506 content => $content);
1512 sub check_canedit ($$$;$) {
1519 run_hooks(canedit => sub {
1520 return if defined $canedit;
1521 my $ret=shift->($page, $q, $session);
1526 elsif (ref $ret eq 'CODE') {
1527 $ret->() unless $nonfatal;
1530 elsif (defined $ret) {
1531 error($ret) unless $nonfatal;
1536 return defined $canedit ? $canedit : 1;
1539 sub check_content (@) {
1542 return 1 if ! exists $hooks{checkcontent}; # optimisation
1544 if (exists $pagesources{$params{page}}) {
1546 my %old=map { $_ => 1 }
1547 split("\n", readfile(srcfile($pagesources{$params{page}})));
1548 foreach my $line (split("\n", $params{content})) {
1549 push @diff, $line if ! exists $old{$line};
1551 $params{diff}=join("\n", @diff);
1555 run_hooks(checkcontent => sub {
1556 return if defined $ok;
1557 my $ret=shift->(%params);
1562 elsif (ref $ret eq 'CODE') {
1563 $ret->() unless $params{nonfatal};
1566 elsif (defined $ret) {
1567 error($ret) unless $params{nonfatal};
1573 return defined $ok ? $ok : 1;
1576 sub check_canchange (@) {
1578 my $cgi = $params{cgi};
1579 my $session = $params{session};
1580 my @changes = @{$params{changes}};
1583 foreach my $change (@changes) {
1584 # This untaint is safe because we check file_pruned and
1586 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1587 $file=possibly_foolish_untaint($file);
1588 if (! defined $file || ! length $file ||
1589 file_pruned($file)) {
1590 error(gettext("bad file name
%s"), $file);
1593 my $type=pagetype($file);
1594 my $page=pagename($file) if defined $type;
1596 if ($change->{action} eq 'add') {
1600 if ($change->{action} eq 'change' ||
1601 $change->{action} eq 'add') {
1602 if (defined $page) {
1603 check_canedit($page, $cgi, $session);
1607 if (IkiWiki::Plugin::attachment->can("check_canattach
")) {
1608 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1609 check_canedit($file, $cgi, $session);
1614 elsif ($change->{action} eq 'remove') {
1615 # check_canremove tests to see if the file is present
1616 # on disk. This will fail when a single commit adds a
1617 # file and then removes it again. Avoid the problem
1618 # by not testing the removal in such pairs of changes.
1619 # (The add is still tested, just to make sure that
1620 # no data is added to the repo that a web edit
1622 next if $newfiles{$file};
1624 if (IkiWiki::Plugin::remove->can("check_canremove
")) {
1625 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1626 check_canedit(defined $page ? $page : $file, $cgi, $session);
1631 error "unknown action
".$change->{action};
1634 error sprintf(gettext("you are
not allowed to change
%s"), $file);
1642 # Take an exclusive lock on the wiki to prevent multiple concurrent
1643 # run issues. The lock will be dropped on program exit.
1644 if (! -d $config{wikistatedir}) {
1645 mkdir($config{wikistatedir});
1647 open($wikilock, '>', "$config{wikistatedir
}/lockfile
") ||
1648 error ("cannot
write to
$config{wikistatedir
}/lockfile
: $!");
1649 if (! flock($wikilock, 2)) { # LOCK_EX
1650 error("failed to get
lock");
1656 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1657 return close($wikilock) if $wikilock;
1663 sub commit_hook_enabled () {
1664 open($commitlock, '+>', "$config{wikistatedir
}/commitlock
") ||
1665 error("cannot
write to
$config{wikistatedir
}/commitlock
: $!");
1666 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1667 close($commitlock) || error("failed closing commitlock
: $!");
1670 close($commitlock) || error("failed closing commitlock
: $!");
1674 sub disable_commit_hook () {
1675 open($commitlock, '>', "$config{wikistatedir
}/commitlock
") ||
1676 error("cannot
write to
$config{wikistatedir
}/commitlock
: $!");
1677 if (! flock($commitlock, 2)) { # LOCK_EX
1678 error("failed to get commit
lock");
1683 sub enable_commit_hook () {
1684 return close($commitlock) if $commitlock;
1689 %oldrenderedfiles=%pagectime=();
1690 if (! $config{rebuild}) {
1691 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1692 %destsources=%renderedfiles=%pagecase=%pagestate=
1693 %depends_simple=%typedlinks=%oldtypedlinks=();
1696 if (! open ($in, "<", "$config{wikistatedir
}/indexdb
")) {
1697 if (-e "$config{wikistatedir
}/index") {
1698 system("ikiwiki
-transition
", "indexdb
", $config{srcdir});
1699 open ($in, "<", "$config{wikistatedir
}/indexdb
") || return;
1702 $config{gettime}=1; # first build
1707 my $index=Storable::fd_retrieve($in);
1708 if (! defined $index) {
1713 if (exists $index->{version} && ! ref $index->{version}) {
1714 $pages=$index->{page};
1715 %wikistate=%{$index->{state}};
1716 # Handle plugins that got disabled by loading a new setup.
1717 if (exists $config{setupfile}) {
1718 require IkiWiki::Setup;
1719 IkiWiki::Setup::disabled_plugins(
1720 grep { ! $loaded_plugins{$_} } keys %wikistate);
1728 foreach my $src (keys %$pages) {
1729 my $d=$pages->{$src};
1730 my $page=pagename($src);
1731 $pagectime{$page}=$d->{ctime};
1732 $pagesources{$page}=$src;
1733 if (! $config{rebuild}) {
1734 $pagemtime{$page}=$d->{mtime};
1735 $renderedfiles{$page}=$d->{dest};
1736 if (exists $d->{links} && ref $d->{links}) {
1737 $links{$page}=$d->{links};
1738 $oldlinks{$page}=[@{$d->{links}}];
1740 if (ref $d->{depends_simple} eq 'ARRAY') {
1742 $depends_simple{$page}={
1743 map { $_ => 1 } @{$d->{depends_simple}}
1746 elsif (exists $d->{depends_simple}) {
1747 $depends_simple{$page}=$d->{depends_simple};
1749 if (exists $d->{dependslist}) {
1752 map { $_ => $DEPEND_CONTENT }
1753 @{$d->{dependslist}}
1756 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1758 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1760 elsif (exists $d->{depends}) {
1761 $depends{$page}=$d->{depends};
1763 if (exists $d->{state}) {
1764 $pagestate{$page}=$d->{state};
1766 if (exists $d->{typedlinks}) {
1767 $typedlinks{$page}=$d->{typedlinks};
1769 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1770 next unless %$links;
1771 $oldtypedlinks{$page}{$type} = {%$links};
1775 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1777 foreach my $page (keys %pagesources) {
1778 $pagecase{lc $page}=$page;
1780 foreach my $page (keys %renderedfiles) {
1781 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1787 run_hooks(savestate => sub { shift->() });
1789 my @plugins=keys %loaded_plugins;
1791 if (! -d $config{wikistatedir}) {
1792 mkdir($config{wikistatedir});
1794 my $newfile="$config{wikistatedir
}/indexdb
.new
";
1795 my $cleanup = sub { unlink($newfile) };
1796 open (my $out, '>', $newfile) || error("cannot
write to
$newfile: $!", $cleanup);
1799 foreach my $page (keys %pagemtime) {
1800 next unless $pagemtime{$page};
1801 my $src=$pagesources{$page};
1803 $index{page}{$src}={
1804 ctime => $pagectime{$page},
1805 mtime => $pagemtime{$page},
1806 dest => $renderedfiles{$page},
1807 links => $links{$page},
1810 if (exists $depends{$page}) {
1811 $index{page}{$src}{depends} = $depends{$page};
1814 if (exists $depends_simple{$page}) {
1815 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1818 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1819 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1822 if (exists $pagestate{$page}) {
1823 foreach my $id (@plugins) {
1824 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1825 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1832 foreach my $id (@plugins) {
1833 $index{state}{$id}={}; # used to detect disabled plugins
1834 foreach my $key (keys %{$wikistate{$id}}) {
1835 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1839 $index{version}="3";
1840 my $ret=Storable::nstore_fd(\%index, $out);
1841 return if ! defined $ret || ! $ret;
1842 close $out || error("failed saving to
$newfile: $!", $cleanup);
1843 rename($newfile, "$config{wikistatedir
}/indexdb
") ||
1844 error("failed renaming
$newfile to
$config{wikistatedir
}/indexdb
", $cleanup);
1849 sub template_file ($) {
1852 my $tpage=($name =~ s/^\///) ? $name : "templates
/$name";
1854 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1855 $template=srcfile($pagesources{$tpage}, 1);
1859 $template=srcfile($tpage, 1);
1862 if (defined $template) {
1863 return $template, $tpage, 1 if wantarray;
1867 $name=~s:/::; # avoid path traversal
1868 foreach my $dir ($config{templatedir},
1869 "$installdir/share/ikiwiki
/templates
") {
1870 if (-e "$dir/$name") {
1871 $template="$dir/$name";
1875 if (defined $template) {
1876 return $template, $tpage if wantarray;
1884 sub template_depends ($$;@) {
1888 my ($filename, $tpage, $untrusted)=template_file($name);
1889 if (! defined $filename) {
1890 error(sprintf(gettext("template
%s not found
"), $name))
1893 if (defined $page && defined $tpage) {
1894 add_depends($page, $tpage);
1899 my $text_ref = shift;
1900 ${$text_ref} = decode_utf8(${$text_ref});
1902 loop_context_vars => 1,
1903 die_on_bad_params => 0,
1904 parent_global_vars => 1,
1905 filename => $filename,
1907 ($untrusted ? (no_includes => 1) : ()),
1909 return @opts if wantarray;
1911 require HTML::Template;
1912 return HTML::Template->new(@opts);
1915 sub template ($;@) {
1916 template_depends(shift, undef, @_);
1919 sub templateactions ($$) {
1925 run_hooks(pageactions => sub {
1926 push @actions, map { { action => $_ } }
1927 grep { defined } shift->(page => $page);
1929 $template->param(actions => \@actions);
1931 if ($config{cgiurl} && exists $hooks{auth}) {
1932 $template->param(prefsurl => cgiurl(do => "prefs
"));
1936 if ($have_actions || @actions) {
1937 $template->param(have_actions => 1);
1944 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1945 error 'hook requires type, call, and id parameters';
1948 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1950 $hooks{$param{type}}{$param{id}}=\%param;
1954 sub run_hooks ($$) {
1955 # Calls the given sub for each hook of the given type,
1956 # passing it the hook function to call.
1960 if (exists $hooks{$type}) {
1961 my (@first, @middle, @last);
1962 foreach my $id (keys %{$hooks{$type}}) {
1963 if ($hooks{$type}{$id}{first}) {
1966 elsif ($hooks{$type}{$id}{last}) {
1973 foreach my $id (@first, @middle, @last) {
1974 $sub->($hooks{$type}{$id}{call});
1982 $hooks{rcs}{rcs_update}{call}->(@_);
1985 sub rcs_prepedit ($) {
1986 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1989 sub rcs_commit (@) {
1990 $hooks{rcs}{rcs_commit}{call}->(@_);
1993 sub rcs_commit_staged (@) {
1994 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1998 $hooks{rcs}{rcs_add}{call}->(@_);
2001 sub rcs_remove ($) {
2002 $hooks{rcs}{rcs_remove}{call}->(@_);
2005 sub rcs_rename ($$) {
2006 $hooks{rcs}{rcs_rename}{call}->(@_);
2009 sub rcs_recentchanges ($) {
2010 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2013 sub rcs_diff ($;$) {
2014 $hooks{rcs}{rcs_diff}{call}->(@_);
2017 sub rcs_getctime ($) {
2018 $hooks{rcs}{rcs_getctime}{call}->(@_);
2021 sub rcs_getmtime ($) {
2022 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2025 sub rcs_receive () {
2026 $hooks{rcs}{rcs_receive}{call}->();
2029 sub add_depends ($$;$) {
2032 my $deptype=shift || $DEPEND_CONTENT;
2034 # Is the pagespec a simple page name?
2035 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2036 $pagespec !~ /[\s*?()!]/) {
2037 $depends_simple{$page}{lc $pagespec} |= $deptype;
2041 # Add explicit dependencies for influences.
2042 my $sub=pagespec_translate($pagespec);
2043 return unless defined $sub;
2044 foreach my $p (keys %pagesources) {
2045 my $r=$sub->($p, location => $page);
2046 my $i=$r->influences;
2047 my $static=$r->influences_static;
2048 foreach my $k (keys %$i) {
2049 next unless $r || $static || $k eq $page;
2050 $depends_simple{$page}{lc $k} |= $i->{$k};
2055 $depends{$page}{$pagespec} |= $deptype;
2061 foreach my $type (@_) {
2062 if ($type eq 'presence') {
2063 $deptype |= $DEPEND_PRESENCE;
2065 elsif ($type eq 'links') {
2066 $deptype |= $DEPEND_LINKS;
2068 elsif ($type eq 'content') {
2069 $deptype |= $DEPEND_CONTENT;
2075 my $file_prune_regexp;
2076 sub file_pruned ($) {
2079 if (defined $config{include} && length $config{include}) {
2080 return 0 if $file =~ m/$config{include}/;
2083 if (! defined $file_prune_regexp) {
2084 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2085 $file_prune_regexp=qr/$file_prune_regexp/;
2087 return $file =~ m/$file_prune_regexp/;
2090 sub define_gettext () {
2091 # If translation is needed, redefine the gettext function to do it.
2092 # Otherwise, it becomes a quick no-op.
2095 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2096 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2097 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2099 $gettext_obj=eval q{
2100 use Locale::gettext q{textdomain};
2101 Locale
::gettext
->domain('ikiwiki')
2106 no warnings
'redefine';
2108 $getobj->() if $getobj;
2110 $gettext_obj->get(shift);
2117 $getobj->() if $getobj;
2119 $gettext_obj->nget(@_);
2122 return ($_[2] == 1 ?
$_[0] : $_[1])
2140 return (defined $val && (lc($val) eq gettext
("yes") || lc($val) eq "yes" || $val eq "1"));
2144 # Injects a new function into the symbol table to replace an
2145 # exported function.
2148 # This is deep ugly perl foo, beware.
2151 if (! defined $params{parent
}) {
2152 $params{parent
}='::';
2153 $params{old
}=\
&{$params{name
}};
2154 $params{name
}=~s/.*:://;
2156 my $parent=$params{parent
};
2157 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2158 $ns = $params{parent
} . $ns;
2159 inject
(%params, parent
=> $ns) unless $ns eq '::main::';
2160 *{$ns . $params{name
}} = $params{call
}
2161 if exists ${$ns}{$params{name
}} &&
2162 \
&{${$ns}{$params{name
}}} == $params{old
};
2168 sub add_link
($$;$) {
2173 push @
{$links{$page}}, $link
2174 unless grep { $_ eq $link } @
{$links{$page}};
2176 if (defined $type) {
2177 $typedlinks{$page}{$type}{$link} = 1;
2181 sub add_autofile
($$$) {
2184 my $generator=shift;
2186 $autofiles{$file}{plugin
}=$plugin;
2187 $autofiles{$file}{generator
}=$generator;
2190 sub sortspec_translate
($$) {
2192 my $reverse = shift;
2198 (-?
) # group 1: perhaps negated
2201 \w
+\
([^\
)]*\
) # command(params)
2203 [^\s
]+ # or anything else
2211 if ($word =~ m/^(\w+)\((.*)\)$/) {
2212 # command with parameters
2216 elsif ($word !~ m/^\w+$/) {
2217 error
(sprintf(gettext
("invalid sort type %s"), $word));
2228 if (exists $IkiWiki::SortSpec
::{"cmp_$word"}) {
2229 if (defined $params) {
2230 push @data, $params;
2231 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2234 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2238 error
(sprintf(gettext
("unknown sort type %s"), $word));
2242 if (! length $code) {
2243 # undefined sorting method... sort arbitrarily
2252 return eval 'sub { '.$code.' }';
2255 sub pagespec_translate
($) {
2258 # Convert spec to perl code.
2262 \s
* # ignore whitespace
2263 ( # 1: match a single word
2270 \w
+\
([^\
)]*\
) # command(params)
2272 [^\s
()]+ # any other text
2274 \s
* # ignore whitespace
2277 if (lc $word eq 'and') {
2280 elsif (lc $word eq 'or') {
2283 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2286 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2287 if (exists $IkiWiki::PageSpec
::{"match_$1"}) {
2289 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2292 push @data, qq{unknown function
in pagespec
"$word"};
2293 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2298 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2302 if (! length $code) {
2303 $code="IkiWiki::FailReason->new('empty pagespec')";
2307 return eval 'sub { my $page=shift; '.$code.' }';
2310 sub pagespec_match
($$;@
) {
2315 # Backwards compatability with old calling convention.
2317 unshift @params, 'location';
2320 my $sub=pagespec_translate
($spec);
2321 return IkiWiki
::ErrorReason
->new("syntax error in pagespec \"$spec\"")
2323 return $sub->($page, @params);
2326 sub pagespec_match_list
($$;@
) {
2331 # Backwards compatability with old calling convention.
2333 print STDERR
"warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2334 $params{list
}=$page;
2335 $page=$params{location
}; # ugh!
2338 my $sub=pagespec_translate
($pagespec);
2339 error
"syntax error in pagespec \"$pagespec\""
2341 my $sort=sortspec_translate
($params{sort}, $params{reverse})
2342 if defined $params{sort};
2345 if (exists $params{list
}) {
2346 @candidates=exists $params{filter
}
2347 ?
grep { ! $params{filter
}->($_) } @
{$params{list
}}
2351 @candidates=exists $params{filter
}
2352 ?
grep { ! $params{filter
}->($_) } keys %pagesources
2353 : keys %pagesources;
2356 # clear params, remainder is passed to pagespec
2357 $depends{$page}{$pagespec} |= ($params{deptype
} || $DEPEND_CONTENT);
2358 my $num=$params{num
};
2359 delete @params{qw{num deptype
reverse sort filter list
}};
2361 # when only the top matches will be returned, it's efficient to
2362 # sort before matching to pagespec,
2363 if (defined $num && defined $sort) {
2364 @candidates=IkiWiki
::SortSpec
::sort_pages
(
2365 $sort, @candidates);
2371 my $accum=IkiWiki
::SuccessReason
->new();
2372 foreach my $p (@candidates) {
2373 my $r=$sub->($p, %params, location
=> $page);
2374 error
(sprintf(gettext
("cannot match pages: %s"), $r))
2375 if $r->isa("IkiWiki::ErrorReason");
2376 unless ($r || $r->influences_static) {
2377 $r->remove_influence($p);
2382 last if defined $num && ++$count == $num;
2386 # Add simple dependencies for accumulated influences.
2387 my $i=$accum->influences;
2388 foreach my $k (keys %$i) {
2389 $depends_simple{$page}{lc $k} |= $i->{$k};
2392 # when all matches will be returned, it's efficient to
2393 # sort after matching
2394 if (! defined $num && defined $sort) {
2395 return IkiWiki
::SortSpec
::sort_pages
(
2403 sub pagespec_valid
($) {
2406 return defined pagespec_translate
($spec);
2410 my $re=quotemeta(shift);
2416 package IkiWiki
::FailReason
;
2419 '""' => sub { $_[0][0] },
2421 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2422 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2423 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2427 our @ISA = 'IkiWiki::SuccessReason';
2429 package IkiWiki
::SuccessReason
;
2432 '""' => sub { $_[0][0] },
2434 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2435 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2436 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2443 return bless [$value, {@_}], $class;
2448 $this->[1]={@_} if @_;
2449 my %i=%{$this->[1]};
2454 sub influences_static
{
2455 return ! $_[0][1]->{""};
2458 sub merge_influences
{
2463 if (! $anded || (($this || %{$this->[1]}) &&
2464 ($other || %{$other->[1]}))) {
2465 foreach my $influence (keys %{$other->[1]}) {
2466 $this->[1]{$influence} |= $other->[1]{$influence};
2475 sub remove_influence
{
2479 delete $this->[1]{$torm};
2482 package IkiWiki
::ErrorReason
;
2484 our @ISA = 'IkiWiki::FailReason';
2486 package IkiWiki
::PageSpec
;
2492 if ($path =~ m!^\.(/|$)!) {
2494 $from=~s
#/?[^/]+$## if defined $from;
2496 $path="$from/$path" if defined $from && length $from;
2500 $path = "" unless defined $path;
2509 sub match_glob
($$;@
) {
2514 $glob=derel
($glob, $params{location
});
2516 # Instead of converting the glob to a regex every time,
2517 # cache the compiled regex to save time.
2518 my $re=$glob_cache{$glob};
2519 unless (defined $re) {
2520 $glob_cache{$glob} = $re = IkiWiki
::glob2re
($glob);
2523 if (! IkiWiki
::isinternal
($page) || $params{internal
}) {
2524 return IkiWiki
::SuccessReason
->new("$glob matches $page");
2527 return IkiWiki
::FailReason
->new("$glob matches $page, but the page is an internal page");
2531 return IkiWiki
::FailReason
->new("$glob does not match $page");
2535 sub match_internal
($$;@
) {
2536 return match_glob
(shift, shift, @_, internal
=> 1)
2539 sub match_page
($$;@
) {
2541 my $match=match_glob
($page, shift, @_);
2543 my $source=exists $IkiWiki::pagesources
{$page} ?
2544 $IkiWiki::pagesources
{$page} :
2545 $IkiWiki::delpagesources
{$page};
2546 my $type=defined $source ? IkiWiki
::pagetype
($source) : undef;
2547 if (! defined $type) {
2548 return IkiWiki
::FailReason
->new("$page is not a page");
2554 sub match_link
($$;@
) {
2559 $link=derel
($link, $params{location
});
2560 my $from=exists $params{location
} ?
$params{location
} : '';
2561 my $linktype=$params{linktype
};
2563 if (defined $linktype) {
2564 $qualifier=" with type $linktype";
2567 my $links = $IkiWiki::links
{$page};
2568 return IkiWiki
::FailReason
->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS
, "" => 1)
2569 unless $links && @
{$links};
2570 my $bestlink = IkiWiki
::bestlink
($from, $link);
2571 foreach my $p (@
{$links}) {
2572 next unless (! defined $linktype || exists $IkiWiki::typedlinks
{$page}{$linktype}{$p});
2574 if (length $bestlink) {
2575 if ($bestlink eq IkiWiki
::bestlink
($page, $p)) {
2576 return IkiWiki
::SuccessReason
->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS
, "" => 1)
2580 if (match_glob
($p, $link, %params)) {
2581 return IkiWiki
::SuccessReason
->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS
, "" => 1)
2583 my ($p_rel)=$p=~/^\/?
(.*)/;
2585 if (match_glob
($p_rel, $link, %params)) {
2586 return IkiWiki
::SuccessReason
->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS
, "" => 1)
2590 return IkiWiki
::FailReason
->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS
, "" => 1);
2593 sub match_backlink
($$;@
) {
2594 my $ret=match_link
($_[1], $_[0], @_);
2595 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS
);
2599 sub match_created_before
($$;@
) {
2604 $testpage=derel
($testpage, $params{location
});
2606 if (exists $IkiWiki::pagectime
{$testpage}) {
2607 if ($IkiWiki::pagectime
{$page} < $IkiWiki::pagectime
{$testpage}) {
2608 return IkiWiki
::SuccessReason
->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2611 return IkiWiki
::FailReason
->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2615 return IkiWiki
::ErrorReason
->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2619 sub match_created_after
($$;@
) {
2624 $testpage=derel
($testpage, $params{location
});
2626 if (exists $IkiWiki::pagectime
{$testpage}) {
2627 if ($IkiWiki::pagectime
{$page} > $IkiWiki::pagectime
{$testpage}) {
2628 return IkiWiki
::SuccessReason
->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2631 return IkiWiki
::FailReason
->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2635 return IkiWiki
::ErrorReason
->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2639 sub match_creation_day
($$;@
) {
2642 if ($d !~ /^\d+$/) {
2643 return IkiWiki
::ErrorReason
->new("invalid day $d");
2645 if ((localtime($IkiWiki::pagectime
{$page}))[3] == $d) {
2646 return IkiWiki
::SuccessReason
->new('creation_day matched');
2649 return IkiWiki
::FailReason
->new('creation_day did not match');
2653 sub match_creation_month
($$;@
) {
2656 if ($m !~ /^\d+$/) {
2657 return IkiWiki
::ErrorReason
->new("invalid month $m");
2659 if ((localtime($IkiWiki::pagectime
{$page}))[4] + 1 == $m) {
2660 return IkiWiki
::SuccessReason
->new('creation_month matched');
2663 return IkiWiki
::FailReason
->new('creation_month did not match');
2667 sub match_creation_year
($$;@
) {
2670 if ($y !~ /^\d+$/) {
2671 return IkiWiki
::ErrorReason
->new("invalid year $y");
2673 if ((localtime($IkiWiki::pagectime
{$page}))[5] + 1900 == $y) {
2674 return IkiWiki
::SuccessReason
->new('creation_year matched');
2677 return IkiWiki
::FailReason
->new('creation_year did not match');
2681 sub match_user
($$;@
) {
2686 my $regexp=IkiWiki
::glob2re
($user);
2688 if (! exists $params{user
}) {
2689 return IkiWiki
::ErrorReason
->new("no user specified");
2692 if (defined $params{user
} && $params{user
}=~$regexp) {
2693 return IkiWiki
::SuccessReason
->new("user is $user");
2695 elsif (! defined $params{user
}) {
2696 return IkiWiki
::FailReason
->new("not logged in");
2699 return IkiWiki
::FailReason
->new("user is $params{user}, not $user");
2703 sub match_admin
($$;@
) {
2708 if (! exists $params{user
}) {
2709 return IkiWiki
::ErrorReason
->new("no user specified");
2712 if (defined $params{user
} && IkiWiki
::is_admin
($params{user
})) {
2713 return IkiWiki
::SuccessReason
->new("user is an admin");
2715 elsif (! defined $params{user
}) {
2716 return IkiWiki
::FailReason
->new("not logged in");
2719 return IkiWiki
::FailReason
->new("user is not an admin");
2723 sub match_ip
($$;@
) {
2728 if (! exists $params{ip
}) {
2729 return IkiWiki
::ErrorReason
->new("no IP specified");
2732 if (defined $params{ip
} && lc $params{ip
} eq lc $ip) {
2733 return IkiWiki
::SuccessReason
->new("IP is $ip");
2736 return IkiWiki
::FailReason
->new("IP is $params{ip}, not $ip");
2740 package IkiWiki
::SortSpec
;
2742 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2743 # are easily available in this namespace, for cmp functions to use them.
2750 IkiWiki
::pagetitle
(IkiWiki
::basename
($a))
2752 IkiWiki
::pagetitle
(IkiWiki
::basename
($b))
2755 sub cmp_mtime
{ $IkiWiki::pagemtime
{$b} <=> $IkiWiki::pagemtime
{$a} }
2756 sub cmp_age
{ $IkiWiki::pagectime
{$b} <=> $IkiWiki::pagectime
{$a} }