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 strftime_utf8 will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link add_autofile useragent
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)",
121 cgi_overload_delay => {
125 description => "number of seconds to delay CGI requests when overloaded",
129 cgi_overload_message => {
132 example => "Please wait",
133 description => "message to display when overloaded (may contain html)",
140 description => "rcs backend to use",
141 safe => 0, # don't allow overriding
146 default => [qw{mdwn link inline meta htmlscrubber passwordauth
147 openid signinedit lockedit conditional
148 recentchanges parentlinks editpage}],
149 description => "plugins to enable by default",
156 description => "plugins to add to the default configuration",
163 description => "plugins to disable",
169 default => "$installdir/share/ikiwiki/templates",
170 description => "additional directory to search for template files",
177 default => "$installdir/share/ikiwiki/basewiki",
178 description => "base wiki source location",
185 default => "$installdir/share/ikiwiki",
186 description => "parent directory containing additional underlays",
193 description => "wrappers to generate",
200 description => "additional underlays to use",
207 description => "display verbose messages?",
214 description => "log to syslog?",
221 description => "create output files named page/index.html?",
222 safe => 0, # changing requires manual transition
225 prefix_directives => {
228 description => "use '!'-prefixed preprocessor directives?",
229 safe => 0, # changing requires manual transition
235 description => "use page/index.mdwn source files",
242 description => "enable Discussion pages?",
248 default => gettext("Discussion"),
249 description => "name of Discussion pages",
256 description => "generate HTML5?",
264 description => "only send cookies over SSL connections?",
272 description => "extension to use for new pages",
273 safe => 0, # not sanitized
279 description => "extension to use for html files",
280 safe => 0, # not sanitized
286 description => "strftime format string to display date",
294 example => "en_US.UTF-8",
295 description => "UTF-8 locale to use",
304 description => "put user pages below specified page",
311 description => "how many backlinks to show before hiding excess (0 to show all)",
318 description => "attempt to hardlink source files? (optimisation for large files)",
320 safe => 0, # paranoia
326 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
328 safe => 0, # paranoia
333 example => "ikiwiki",
334 description => "group for wrappers to run in",
336 safe => 0, # paranoia
342 example => "$ENV{HOME}/.ikiwiki/",
343 description => "extra library and plugin directory",
345 safe => 0, # directory
351 description => "environment variables",
352 safe => 0, # paranoia
358 example => "US/Eastern",
359 description => "time zone name",
366 example => '^\.htaccess$',
367 description => "regexp of normally excluded files to include",
375 example => '^(*\.private|Makefile)$',
376 description => "regexp of files that should be skipped",
381 wiki_file_prune_regexps => {
383 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
384 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
385 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
386 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
387 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
388 description => "regexps of source files to ignore",
394 description => "specifies the characters that are allowed in source filenames",
395 default => "-[:alnum:]+/.:_",
399 wiki_file_regexp => {
401 description => "regexp of legal source files",
405 web_commit_regexp => {
407 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
408 description => "regexp to parse web commits from logs",
415 description => "run as a cgi",
419 cgi_disable_uploads => {
422 description => "whether CGI should accept file uploads",
429 description => "run as a post-commit hook",
436 description => "running in rebuild mode",
443 description => "running in setup mode",
450 description => "running in clean mode",
457 description => "running in refresh mode",
464 description => "running in receive test mode",
468 wrapper_background_command => {
471 description => "background shell command to run",
477 description => "running in gettime mode",
484 description => "running in w3mmode",
491 description => "path to the .ikiwiki directory holding ikiwiki state",
498 description => "path to setup file",
505 description => "perl class to use to dump setup file",
509 allow_symlinks_before_srcdir => {
512 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
518 default => "$ENV{HOME}/.ikiwiki/cookies",
519 description => "cookie control",
520 example => { file => "$ENV{HOME}/.ikiwiki/cookies" },
521 safe => 0, # hooks into perl module internals
526 sub defaultconfig () {
529 foreach my $key (keys %s) {
530 push @ret, $key, $s{$key}->{default};
535 # URL to top of wiki as a path starting with /, valid from any wiki page or
536 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
538 # URL to CGI script, similar to $local_url
542 # locale stuff; avoid LC_ALL since it overrides everything
543 if (defined $ENV{LC_ALL}) {
544 $ENV{LANG} = $ENV{LC_ALL};
547 if (defined $config{locale}) {
548 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
549 $ENV{LANG}=$config{locale};
554 if (! defined $config{wiki_file_regexp}) {
555 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
558 if (ref $config{ENV} eq 'HASH') {
559 foreach my $val (keys %{$config{ENV}}) {
560 $ENV{$val}=$config{ENV}{$val};
563 if (defined $config{timezone} && length $config{timezone}) {
564 $ENV{TZ}=$config{timezone};
567 $config{timezone}=$ENV{TZ};
570 if ($config{w3mmode}) {
571 eval q{use Cwd q{abs_path}};
573 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
574 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
575 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
576 unless $config{cgiurl} =~ m!file:///!;
577 $config{url}="file://".$config{destdir};
580 if ($config{cgi} && ! length $config{url}) {
581 error(gettext("Must specify url to wiki with --url when using --cgi"));
584 if (defined $config{url} && length $config{url}) {
586 my $baseurl = URI->new($config{url});
588 $local_url = $baseurl->path . "/";
589 $local_cgiurl = undef;
591 if (length $config{cgiurl}) {
592 my $cgiurl = URI->new($config{cgiurl});
594 $local_cgiurl = $cgiurl->path;
596 if ($cgiurl->scheme ne $baseurl->scheme or
597 $cgiurl->authority ne $baseurl->authority) {
598 # too far apart, fall back to absolute URLs
599 $local_url = "$config{url}/";
600 $local_cgiurl = $config{cgiurl};
604 $local_url =~ s{//$}{/};
607 $local_cgiurl = $config{cgiurl};
610 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
611 unless exists $config{wikistatedir} && defined $config{wikistatedir};
613 if (defined $config{umask}) {
614 my $u = possibly_foolish_untaint($config{umask});
616 if ($u =~ m/^\d+$/) {
619 elsif ($u eq 'private') {
622 elsif ($u eq 'group') {
625 elsif ($u eq 'public') {
629 error(sprintf(gettext("unsupported umask setting %s"), $u));
633 run_hooks(checkconfig => sub { shift->() });
641 foreach my $dir (@INC, $config{libdir}) {
642 next unless defined $dir && length $dir;
643 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
644 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
648 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
649 next unless defined $dir && length $dir;
650 foreach my $file (glob("$dir/plugins/*")) {
651 $ret{basename($file)}=1 if -x $file;
659 if (defined $config{libdir} && length $config{libdir}) {
660 unshift @INC, possibly_foolish_untaint($config{libdir});
663 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
668 if (exists $hooks{rcs}) {
669 error(gettext("cannot use multiple rcs plugins"));
671 loadplugin($config{rcs});
673 if (! exists $hooks{rcs}) {
677 run_hooks(getopt => sub { shift->() });
678 if (grep /^-/, @ARGV) {
679 print STDERR "Unknown option (or missing parameter): $_\n"
680 foreach grep /^-/, @ARGV;
687 sub loadplugin ($;$) {
691 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
693 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
694 "$installdir/lib/ikiwiki") {
695 if (defined $dir && -x "$dir/plugins/$plugin") {
696 eval { require IkiWiki::Plugin::external };
699 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
701 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
702 $loaded_plugins{$plugin}=1;
707 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
710 error("Failed to load plugin $mod: $@");
712 $loaded_plugins{$plugin}=1;
719 log_message('err' => $message) if $config{syslog};
720 if (defined $cleaner) {
727 return unless $config{verbose};
728 return log_message(debug => @_);
732 sub log_message ($$) {
735 if ($config{syslog}) {
738 Sys::Syslog::setlogsock('unix');
739 Sys::Syslog::openlog('ikiwiki', '', 'user');
743 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
746 elsif (! $config{cgi}) {
750 return print STDERR "@_\n";
754 sub possibly_foolish_untaint ($) {
756 my ($untainted)=$tainted=~/(.*)/s;
776 return exists $pagesources{$page} &&
777 $pagesources{$page} =~ /\._([^.]+)$/;
783 if ($file =~ /\.([^.]+)$/) {
784 return $1 if exists $hooks{htmlize}{$1};
786 my $base=basename($file);
787 if (exists $hooks{htmlize}{$base} &&
788 $hooks{htmlize}{$base}{noextension}) {
799 if (exists $pagename_cache{$file}) {
800 return $pagename_cache{$file};
803 my $type=pagetype($file);
805 $page=~s/\Q.$type\E*$//
806 if defined $type && !$hooks{htmlize}{$type}{keepextension}
807 && !$hooks{htmlize}{$type}{noextension};
808 if ($config{indexpages} && $page=~/(.*)\/index$/) {
812 $pagename_cache{$file} = $page;
816 sub newpagefile ($$) {
820 if (! $config{indexpages} || $page eq 'index') {
821 return $page.".".$type;
824 return $page."/index.".$type;
828 sub targetpage ($$;$) {
833 if (defined $filename) {
834 return $page."/".$filename.".".$ext;
836 elsif (! $config{usedirs} || $page eq 'index') {
837 return $page.".".$ext;
840 return $page."/index.".$ext;
847 return targetpage($page, $config{htmlext});
854 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
855 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
856 return "$dir/$file", stat(_) if -e "$dir/$file";
858 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
863 return (srcfile_stat(@_))[0];
866 sub add_literal_underlay ($) {
869 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
870 unshift @{$config{underlaydirs}}, $dir;
874 sub add_underlay ($) {
878 $dir="$config{underlaydirbase}/$dir";
881 add_literal_underlay($dir);
882 # why does it return 1? we just don't know
886 sub readfile ($;$$) {
892 error("cannot read a symlink ($file)");
896 open (my $in, "<", $file) || error("failed to read $file: $!");
897 binmode($in) if ($binary);
898 return \*$in if $wantfd;
900 # check for invalid utf-8, and toss it back to avoid crashes
901 if (! utf8::valid($ret)) {
902 $ret=encode_utf8($ret);
904 close $in || error("failed to read $file: $!");
908 sub prep_writefile ($$) {
913 while (length $test) {
914 if (-l "$destdir/$test") {
915 error("cannot write to a symlink ($test)");
917 if (-f _ && $test ne $file) {
918 # Remove conflicting file.
919 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
920 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
922 unlink("$destdir/$test");
928 $test=dirname($test);
931 my $dir=dirname("$destdir/$file");
934 foreach my $s (split(m!/+!, $dir)) {
937 mkdir($d) || error("failed to create directory $d: $!");
945 sub writefile ($$$;$$) {
946 my $file=shift; # can include subdirs
947 my $destdir=shift; # directory to put file in
952 prep_writefile($file, $destdir);
954 my $newfile="$destdir/$file.ikiwiki-new";
956 error("cannot write to a symlink ($newfile)");
959 my $cleanup = sub { unlink($newfile) };
960 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
961 binmode($out) if ($binary);
963 $writer->(\*$out, $cleanup);
966 print $out $content or error("failed writing to $newfile: $!", $cleanup);
968 close $out || error("failed saving $newfile: $!", $cleanup);
969 rename($newfile, "$destdir/$file") ||
970 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
976 sub will_render ($$;$) {
981 # Important security check for independently created files.
982 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
983 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
984 my $from_other_page=0;
985 # Expensive, but rarely runs.
986 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
990 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
996 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
997 unless $from_other_page;
1000 # If $dest exists as a directory, remove conflicting files in it
1001 # rendered from other pages.
1003 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1004 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1005 if (dirname($f) eq $dest) {
1006 unlink("$config{destdir}/$f");
1007 rmdir(dirname("$config{destdir}/$f"));
1013 if (! $clear || $cleared{$page}) {
1014 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1017 foreach my $old (@{$renderedfiles{$page}}) {
1018 delete $destsources{$old};
1020 $renderedfiles{$page}=[$dest];
1023 $destsources{$dest}=$page;
1033 if ($link=~s/^\/+//) {
1041 $l.="/" if length $l;
1044 if (exists $pagesources{$l}) {
1047 elsif (exists $pagecase{lc $l}) {
1048 return $pagecase{lc $l};
1050 } while $cwd=~s{/?[^/]+$}{};
1052 if (length $config{userdir}) {
1053 my $l = "$config{userdir}/".lc($link);
1054 if (exists $pagesources{$l}) {
1057 elsif (exists $pagecase{lc $l}) {
1058 return $pagecase{lc $l};
1062 #print STDERR "warning: page $page, broken link: $link\n";
1066 sub isinlinableimage ($) {
1069 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1072 sub pagetitle ($;$) {
1074 my $unescaped=shift;
1077 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1080 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1088 # support use w/o %config set
1089 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1090 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1096 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1097 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1104 my $cgiurl=$local_cgiurl;
1106 if (exists $params{cgiurl}) {
1107 $cgiurl=$params{cgiurl};
1108 delete $params{cgiurl};
1116 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1119 sub cgiurl_abs (@) {
1121 URI->new_abs(cgiurl(@_), $config{cgiurl});
1127 return $local_url if ! defined $page;
1129 $page=htmlpage($page);
1131 $page=~s/[^\/]+\//..\//g;
1139 return $url unless defined $urlbase && length $urlbase;
1142 URI->new_abs($url, $urlbase)->as_string;
1146 # Work around very innefficient behavior in File::Spec if abs2rel
1147 # is passed two relative paths. It's much faster if paths are
1148 # absolute! (Debian bug #376658; fixed in debian unstable now)
1153 my $ret=File::Spec->abs2rel($path, $base);
1154 $ret=~s/^// if defined $ret;
1158 sub displaytime ($;$$) {
1159 # Plugins can override this function to mark up the time to
1161 my $time=formattime($_[0], $_[1]);
1162 if ($config{html5}) {
1163 return '<time datetime="'.date_3339($_[0]).'"'.
1164 ($_[2] ? ' pubdate="pubdate"' : '').
1165 '>'.$time.'</time>';
1168 return '<span class="date">'.$time.'</span>';
1172 sub formattime ($;$) {
1173 # Plugins can override this function to format the time.
1176 if (! defined $format) {
1177 $format=$config{timeformat};
1180 return strftime_utf8($format, localtime($time));
1183 my $strftime_encoding;
1185 # strftime doesn't know about encodings, so make sure
1186 # its output is properly treated as utf8.
1187 # Note that this does not handle utf-8 in the format string.
1188 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1189 unless defined $strftime_encoding;
1191 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1192 : POSIX::strftime(@_);
1198 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1199 POSIX::setlocale(&POSIX::LC_TIME, "C");
1200 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1201 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1205 sub beautify_urlpath ($) {
1208 # Ensure url is not an empty link, and if necessary,
1209 # add ./ to avoid colon confusion.
1210 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1214 if ($config{usedirs}) {
1215 $url =~ s!/index.$config{htmlext}$!/!;
1230 if (! $destsources{$to}) {
1235 return $config{url}.beautify_urlpath("/".$to);
1238 if (! defined $from) {
1239 my $u = $local_url || '';
1241 return $u.beautify_urlpath("/".$to);
1244 my $link = abs2rel($to, dirname(htmlpage($from)));
1246 return beautify_urlpath($link);
1249 sub isselflink ($$) {
1250 # Plugins can override this function to support special types
1255 return $page eq $link;
1258 sub htmllink ($$$;@) {
1259 my $lpage=shift; # the page doing the linking
1260 my $page=shift; # the page that will contain the link (different for inline)
1267 if (! $opts{forcesubpage}) {
1268 $bestlink=bestlink($lpage, $link);
1271 $bestlink="$lpage/".lc($link);
1275 if (defined $opts{linktext}) {
1276 $linktext=$opts{linktext};
1279 $linktext=pagetitle(basename($link));
1282 return "<span class=\"selflink\">$linktext</span>"
1283 if length $bestlink && isselflink($page, $bestlink) &&
1284 ! defined $opts{anchor};
1286 if (! $destsources{$bestlink}) {
1287 $bestlink=htmlpage($bestlink);
1289 if (! $destsources{$bestlink}) {
1291 if (length $config{cgiurl}) {
1292 $cgilink = "<a href=\"".
1297 )."\" rel=\"nofollow\">?</a>";
1299 return "<span class=\"createlink\">$cgilink$linktext</span>"
1303 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1304 $bestlink=beautify_urlpath($bestlink);
1306 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1307 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1310 if (defined $opts{anchor}) {
1311 $bestlink.="#".$opts{anchor};
1315 foreach my $attr (qw{rel class title}) {
1316 if (defined $opts{$attr}) {
1317 push @attrs, " $attr=\"$opts{$attr}\"";
1321 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1326 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1329 sub openiduser ($) {
1332 if (defined $user && $user =~ m!^https?://! &&
1333 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1336 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1337 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1340 # backcompat with old version
1341 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1342 $display=$oid->display;
1345 # Convert "user.somehost.com" to "user [somehost.com]"
1346 # (also "user.somehost.co.uk")
1347 if ($display !~ /\[/) {
1348 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1350 # Convert "http://somehost.com/user" to "user [somehost.com]".
1351 # (also "https://somehost.com/user/")
1352 if ($display !~ /\[/) {
1353 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1355 $display=~s!^https?://!!; # make sure this is removed
1356 eval q{use CGI 'escapeHTML'};
1358 return escapeHTML($display);
1363 sub htmlize ($$$$) {
1369 my $oneline = $content !~ /\n/;
1371 if (exists $hooks{htmlize}{$type}) {
1372 $content=$hooks{htmlize}{$type}{call}->(
1374 content => $content,
1378 error("htmlization of $type not supported");
1381 run_hooks(sanitize => sub {
1384 destpage => $destpage,
1385 content => $content,
1390 # hack to get rid of enclosing junk added by markdown
1391 # and other htmlizers/sanitizers
1392 $content=~s/^<p>//i;
1393 $content=~s/<\/p>\n*$//i;
1404 run_hooks(linkify => sub {
1407 destpage => $destpage,
1408 content => $content,
1416 our $preprocess_preview=0;
1417 sub preprocess ($$$;$$) {
1418 my $page=shift; # the page the data comes from
1419 my $destpage=shift; # the page the data will appear in (different for inline)
1424 # Using local because it needs to be set within any nested calls
1426 local $preprocess_preview=$preview if defined $preview;
1433 $params="" if ! defined $params;
1435 if (length $escape) {
1436 return "[[$prefix$command $params]]";
1438 elsif (exists $hooks{preprocess}{$command}) {
1439 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1440 # Note: preserve order of params, some plugins may
1441 # consider it significant.
1443 while ($params =~ m{
1444 (?:([-.\w]+)=)? # 1: named parameter key?
1446 """(.*?)""" # 2: triple-quoted value
1448 "([^"]*?)" # 3: single-quoted value
1450 '''(.*?)''' # 4: triple-single-quote
1452 <<([a-zA-Z]+)\n # 5: heredoc start
1453 (.*?)\n\5 # 6: heredoc value
1455 (\S+) # 7: unquoted value
1457 (?:\s+|$) # delimiter to next param
1467 elsif (defined $3) {
1470 elsif (defined $4) {
1473 elsif (defined $7) {
1476 elsif (defined $6) {
1481 push @params, $key, $val;
1484 push @params, $val, '';
1487 if ($preprocessing{$page}++ > 3) {
1488 # Avoid loops of preprocessed pages preprocessing
1489 # other pages that preprocess them, etc.
1490 return "[[!$command <span class=\"error\">".
1491 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1492 $page, $preprocessing{$page}).
1498 $hooks{preprocess}{$command}{call}->(
1501 destpage => $destpage,
1502 preview => $preprocess_preview,
1508 $ret="[[!$command <span class=\"error\">".
1509 gettext("Error").": $error"."</span>]]";
1513 # use void context during scan pass
1515 $hooks{preprocess}{$command}{call}->(
1518 destpage => $destpage,
1519 preview => $preprocess_preview,
1524 $preprocessing{$page}--;
1528 return "[[$prefix$command $params]]";
1533 if ($config{prefix_directives}) {
1536 \[\[(!) # directive open; 2: prefix
1537 ([-\w]+) # 3: command
1538 ( # 4: the parameters..
1539 \s+ # Must have space if parameters present
1541 (?:[-.\w]+=)? # named parameter key?
1543 """.*?""" # triple-quoted value
1545 "[^"]*?" # single-quoted value
1547 '''.*?''' # triple-single-quote
1549 <<([a-zA-Z]+)\n # 5: heredoc start
1550 (?:.*?)\n\5 # heredoc value
1552 [^"\s\]]+ # unquoted value
1554 \s* # whitespace or end
1557 *)? # 0 or more parameters
1558 \]\] # directive closed
1564 \[\[(!?) # directive open; 2: optional prefix
1565 ([-\w]+) # 3: command
1567 ( # 4: the parameters..
1569 (?:[-.\w]+=)? # named parameter key?
1571 """.*?""" # triple-quoted value
1573 "[^"]*?" # single-quoted value
1575 '''.*?''' # triple-single-quote
1577 <<([a-zA-Z]+)\n # 5: heredoc start
1578 (?:.*?)\n\5 # heredoc value
1580 [^"\s\]]+ # unquoted value
1582 \s* # whitespace or end
1585 *) # 0 or more parameters
1586 \]\] # directive closed
1590 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1599 run_hooks(filter => sub {
1600 $content=shift->(page => $page, destpage => $destpage,
1601 content => $content);
1607 sub check_canedit ($$$;$) {
1614 run_hooks(canedit => sub {
1615 return if defined $canedit;
1616 my $ret=shift->($page, $q, $session);
1621 elsif (ref $ret eq 'CODE') {
1622 $ret->() unless $nonfatal;
1625 elsif (defined $ret) {
1626 error($ret) unless $nonfatal;
1631 return defined $canedit ? $canedit : 1;
1634 sub check_content (@) {
1637 return 1 if ! exists $hooks{checkcontent}; # optimisation
1639 if (exists $pagesources{$params{page}}) {
1641 my %old=map { $_ => 1 }
1642 split("\n", readfile(srcfile($pagesources{$params{page}})));
1643 foreach my $line (split("\n", $params{content})) {
1644 push @diff, $line if ! exists $old{$line};
1646 $params{diff}=join("\n", @diff);
1650 run_hooks(checkcontent => sub {
1651 return if defined $ok;
1652 my $ret=shift->(%params);
1657 elsif (ref $ret eq 'CODE') {
1658 $ret->() unless $params{nonfatal};
1661 elsif (defined $ret) {
1662 error($ret) unless $params{nonfatal};
1668 return defined $ok ? $ok : 1;
1671 sub check_canchange (@) {
1673 my $cgi = $params{cgi};
1674 my $session = $params{session};
1675 my @changes = @{$params{changes}};
1678 foreach my $change (@changes) {
1679 # This untaint is safe because we check file_pruned and
1681 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1682 $file=possibly_foolish_untaint($file);
1683 if (! defined $file || ! length $file ||
1684 file_pruned($file)) {
1685 error(gettext("bad file name %s"), $file);
1688 my $type=pagetype($file);
1689 my $page=pagename($file) if defined $type;
1691 if ($change->{action} eq 'add') {
1695 if ($change->{action} eq 'change' ||
1696 $change->{action} eq 'add') {
1697 if (defined $page) {
1698 check_canedit($page, $cgi, $session);
1702 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1703 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1704 check_canedit($file, $cgi, $session);
1709 elsif ($change->{action} eq 'remove') {
1710 # check_canremove tests to see if the file is present
1711 # on disk. This will fail when a single commit adds a
1712 # file and then removes it again. Avoid the problem
1713 # by not testing the removal in such pairs of changes.
1714 # (The add is still tested, just to make sure that
1715 # no data is added to the repo that a web edit
1717 next if $newfiles{$file};
1719 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1720 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1721 check_canedit(defined $page ? $page : $file, $cgi, $session);
1726 error "unknown action ".$change->{action};
1729 error sprintf(gettext("you are not allowed to change %s"), $file);
1737 # Take an exclusive lock on the wiki to prevent multiple concurrent
1738 # run issues. The lock will be dropped on program exit.
1739 if (! -d $config{wikistatedir}) {
1740 mkdir($config{wikistatedir});
1742 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1743 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1744 if (! flock($wikilock, 2)) { # LOCK_EX
1745 error("failed to get lock");
1751 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1752 return close($wikilock) if $wikilock;
1758 sub commit_hook_enabled () {
1759 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1760 error("cannot write to $config{wikistatedir}/commitlock: $!");
1761 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1762 close($commitlock) || error("failed closing commitlock: $!");
1765 close($commitlock) || error("failed closing commitlock: $!");
1769 sub disable_commit_hook () {
1770 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1771 error("cannot write to $config{wikistatedir}/commitlock: $!");
1772 if (! flock($commitlock, 2)) { # LOCK_EX
1773 error("failed to get commit lock");
1778 sub enable_commit_hook () {
1779 return close($commitlock) if $commitlock;
1784 %oldrenderedfiles=%pagectime=();
1785 if (! $config{rebuild}) {
1786 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1787 %destsources=%renderedfiles=%pagecase=%pagestate=
1788 %depends_simple=%typedlinks=%oldtypedlinks=();
1791 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1792 if (-e "$config{wikistatedir}/index") {
1793 system("ikiwiki-transition", "indexdb", $config{srcdir});
1794 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1797 $config{gettime}=1; # first build
1802 my $index=Storable::fd_retrieve($in);
1803 if (! defined $index) {
1808 if (exists $index->{version} && ! ref $index->{version}) {
1809 $pages=$index->{page};
1810 %wikistate=%{$index->{state}};
1811 # Handle plugins that got disabled by loading a new setup.
1812 if (exists $config{setupfile}) {
1813 require IkiWiki::Setup;
1814 IkiWiki::Setup::disabled_plugins(
1815 grep { ! $loaded_plugins{$_} } keys %wikistate);
1823 foreach my $src (keys %$pages) {
1824 my $d=$pages->{$src};
1825 my $page=pagename($src);
1826 $pagectime{$page}=$d->{ctime};
1827 $pagesources{$page}=$src;
1828 if (! $config{rebuild}) {
1829 $pagemtime{$page}=$d->{mtime};
1830 $renderedfiles{$page}=$d->{dest};
1831 if (exists $d->{links} && ref $d->{links}) {
1832 $links{$page}=$d->{links};
1833 $oldlinks{$page}=[@{$d->{links}}];
1835 if (ref $d->{depends_simple} eq 'ARRAY') {
1837 $depends_simple{$page}={
1838 map { $_ => 1 } @{$d->{depends_simple}}
1841 elsif (exists $d->{depends_simple}) {
1842 $depends_simple{$page}=$d->{depends_simple};
1844 if (exists $d->{dependslist}) {
1847 map { $_ => $DEPEND_CONTENT }
1848 @{$d->{dependslist}}
1851 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1853 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1855 elsif (exists $d->{depends}) {
1856 $depends{$page}=$d->{depends};
1858 if (exists $d->{state}) {
1859 $pagestate{$page}=$d->{state};
1861 if (exists $d->{typedlinks}) {
1862 $typedlinks{$page}=$d->{typedlinks};
1864 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1865 next unless %$links;
1866 $oldtypedlinks{$page}{$type} = {%$links};
1870 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1872 foreach my $page (keys %pagesources) {
1873 $pagecase{lc $page}=$page;
1875 foreach my $page (keys %renderedfiles) {
1876 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1882 run_hooks(savestate => sub { shift->() });
1884 my @plugins=keys %loaded_plugins;
1886 if (! -d $config{wikistatedir}) {
1887 mkdir($config{wikistatedir});
1889 my $newfile="$config{wikistatedir}/indexdb.new";
1890 my $cleanup = sub { unlink($newfile) };
1891 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1894 foreach my $page (keys %pagemtime) {
1895 next unless $pagemtime{$page};
1896 my $src=$pagesources{$page};
1898 $index{page}{$src}={
1899 ctime => $pagectime{$page},
1900 mtime => $pagemtime{$page},
1901 dest => $renderedfiles{$page},
1902 links => $links{$page},
1905 if (exists $depends{$page}) {
1906 $index{page}{$src}{depends} = $depends{$page};
1909 if (exists $depends_simple{$page}) {
1910 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1913 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1914 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1917 if (exists $pagestate{$page}) {
1918 foreach my $id (@plugins) {
1919 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1920 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1927 foreach my $id (@plugins) {
1928 $index{state}{$id}={}; # used to detect disabled plugins
1929 foreach my $key (keys %{$wikistate{$id}}) {
1930 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1934 $index{version}="3";
1935 my $ret=Storable::nstore_fd(\%index, $out);
1936 return if ! defined $ret || ! $ret;
1937 close $out || error("failed saving to $newfile: $!", $cleanup);
1938 rename($newfile, "$config{wikistatedir}/indexdb") ||
1939 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1944 sub template_file ($) {
1947 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1949 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1950 $template=srcfile($pagesources{$tpage}, 1);
1954 $template=srcfile($tpage, 1);
1957 if (defined $template) {
1958 return $template, $tpage, 1 if wantarray;
1962 $name=~s:/::; # avoid path traversal
1963 foreach my $dir ($config{templatedir},
1964 "$installdir/share/ikiwiki/templates") {
1965 if (-e "$dir/$name") {
1966 $template="$dir/$name";
1970 if (defined $template) {
1971 return $template, $tpage if wantarray;
1979 sub template_depends ($$;@) {
1983 my ($filename, $tpage, $untrusted)=template_file($name);
1984 if (! defined $filename) {
1985 error(sprintf(gettext("template %s not found"), $name))
1988 if (defined $page && defined $tpage) {
1989 add_depends($page, $tpage);
1994 my $text_ref = shift;
1995 ${$text_ref} = decode_utf8(${$text_ref});
1997 loop_context_vars => 1,
1998 die_on_bad_params => 0,
1999 parent_global_vars => 1,
2000 filename => $filename,
2002 ($untrusted ? (no_includes => 1) : ()),
2004 return @opts if wantarray;
2006 require HTML::Template;
2007 return HTML::Template->new(@opts);
2010 sub template ($;@) {
2011 template_depends(shift, undef, @_);
2014 sub templateactions ($$) {
2020 run_hooks(pageactions => sub {
2021 push @actions, map { { action => $_ } }
2022 grep { defined } shift->(page => $page);
2024 $template->param(actions => \@actions);
2026 if ($config{cgiurl} && exists $hooks{auth}) {
2027 $template->param(prefsurl => cgiurl(do => "prefs"));
2031 if ($have_actions || @actions) {
2032 $template->param(have_actions => 1);
2039 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2040 error 'hook requires type, call, and id parameters';
2043 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2045 $hooks{$param{type}}{$param{id}}=\%param;
2049 sub run_hooks ($$) {
2050 # Calls the given sub for each hook of the given type,
2051 # passing it the hook function to call.
2055 if (exists $hooks{$type}) {
2056 my (@first, @middle, @last);
2057 foreach my $id (keys %{$hooks{$type}}) {
2058 if ($hooks{$type}{$id}{first}) {
2061 elsif ($hooks{$type}{$id}{last}) {
2068 foreach my $id (@first, @middle, @last) {
2069 $sub->($hooks{$type}{$id}{call});
2077 $hooks{rcs}{rcs_update}{call}->(@_);
2080 sub rcs_prepedit ($) {
2081 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2084 sub rcs_commit (@) {
2085 $hooks{rcs}{rcs_commit}{call}->(@_);
2088 sub rcs_commit_staged (@) {
2089 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2093 $hooks{rcs}{rcs_add}{call}->(@_);
2096 sub rcs_remove ($) {
2097 $hooks{rcs}{rcs_remove}{call}->(@_);
2100 sub rcs_rename ($$) {
2101 $hooks{rcs}{rcs_rename}{call}->(@_);
2104 sub rcs_recentchanges ($) {
2105 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2108 sub rcs_diff ($;$) {
2109 $hooks{rcs}{rcs_diff}{call}->(@_);
2112 sub rcs_getctime ($) {
2113 $hooks{rcs}{rcs_getctime}{call}->(@_);
2116 sub rcs_getmtime ($) {
2117 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2120 sub rcs_receive () {
2121 $hooks{rcs}{rcs_receive}{call}->();
2124 sub add_depends ($$;$) {
2127 my $deptype=shift || $DEPEND_CONTENT;
2129 # Is the pagespec a simple page name?
2130 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2131 $pagespec !~ /[\s*?()!]/) {
2132 $depends_simple{$page}{lc $pagespec} |= $deptype;
2136 # Add explicit dependencies for influences.
2137 my $sub=pagespec_translate($pagespec);
2138 return unless defined $sub;
2139 foreach my $p (keys %pagesources) {
2140 my $r=$sub->($p, location => $page);
2141 my $i=$r->influences;
2142 my $static=$r->influences_static;
2143 foreach my $k (keys %$i) {
2144 next unless $r || $static || $k eq $page;
2145 $depends_simple{$page}{lc $k} |= $i->{$k};
2150 $depends{$page}{$pagespec} |= $deptype;
2156 foreach my $type (@_) {
2157 if ($type eq 'presence') {
2158 $deptype |= $DEPEND_PRESENCE;
2160 elsif ($type eq 'links') {
2161 $deptype |= $DEPEND_LINKS;
2163 elsif ($type eq 'content') {
2164 $deptype |= $DEPEND_CONTENT;
2170 my $file_prune_regexp;
2171 sub file_pruned ($) {
2174 if (defined $config{include} && length $config{include}) {
2175 return 0 if $file =~ m/$config{include}/;
2178 if (! defined $file_prune_regexp) {
2179 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2180 $file_prune_regexp=qr/$file_prune_regexp/;
2182 return $file =~ m/$file_prune_regexp/;
2185 sub define_gettext () {
2186 # If translation is needed, redefine the gettext function to do it.
2187 # Otherwise, it becomes a quick no-op.
2190 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2191 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2192 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2194 $gettext_obj=eval q{
2195 use Locale::gettext q{textdomain};
2196 Locale::gettext->domain('ikiwiki')
2201 no warnings 'redefine';
2203 $getobj->() if $getobj;
2205 $gettext_obj->get(shift);
2212 $getobj->() if $getobj;
2214 $gettext_obj->nget(@_);
2217 return ($_[2] == 1 ? $_[0] : $_[1])
2235 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2239 # Injects a new function into the symbol table to replace an
2240 # exported function.
2243 # This is deep ugly perl foo, beware.
2246 if (! defined $params{parent}) {
2247 $params{parent}='::';
2248 $params{old}=\&{$params{name}};
2249 $params{name}=~s/.*:://;
2251 my $parent=$params{parent};
2252 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2253 $ns = $params{parent} . $ns;
2254 inject(%params, parent => $ns) unless $ns eq '::main::';
2255 *{$ns . $params{name}} = $params{call}
2256 if exists ${$ns}{$params{name}} &&
2257 \&{${$ns}{$params{name}}} == $params{old};
2263 sub add_link ($$;$) {
2268 push @{$links{$page}}, $link
2269 unless grep { $_ eq $link } @{$links{$page}};
2271 if (defined $type) {
2272 $typedlinks{$page}{$type}{$link} = 1;
2276 sub add_autofile ($$$) {
2279 my $generator=shift;
2281 $autofiles{$file}{plugin}=$plugin;
2282 $autofiles{$file}{generator}=$generator;
2286 return LWP::UserAgent->new(
2287 cookie_jar => $config{cookiejar},
2288 env_proxy => 1, # respect proxy env vars
2292 sub sortspec_translate ($$) {
2294 my $reverse = shift;
2300 (-?) # group 1: perhaps negated
2303 \w+\([^\)]*\) # command(params)
2305 [^\s]+ # or anything else
2313 if ($word =~ m/^(\w+)\((.*)\)$/) {
2314 # command with parameters
2318 elsif ($word !~ m/^\w+$/) {
2319 error(sprintf(gettext("invalid sort type %s"), $word));
2330 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2331 if (defined $params) {
2332 push @data, $params;
2333 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2336 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2340 error(sprintf(gettext("unknown sort type %s"), $word));
2344 if (! length $code) {
2345 # undefined sorting method... sort arbitrarily
2354 return eval 'sub { '.$code.' }';
2357 sub pagespec_translate ($) {
2360 # Convert spec to perl code.
2364 \s* # ignore whitespace
2365 ( # 1: match a single word
2372 \w+\([^\)]*\) # command(params)
2374 [^\s()]+ # any other text
2376 \s* # ignore whitespace
2379 if (lc $word eq 'and') {
2382 elsif (lc $word eq 'or') {
2385 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2388 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2389 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2391 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2394 push @data, qq{unknown function in pagespec "$word"};
2395 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2400 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2404 if (! length $code) {
2405 $code="IkiWiki::FailReason->new('empty pagespec')";
2409 return eval 'sub { my $page=shift; '.$code.' }';
2412 sub pagespec_match ($$;@) {
2417 # Backwards compatability with old calling convention.
2419 unshift @params, 'location';
2422 my $sub=pagespec_translate($spec);
2423 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2425 return $sub->($page, @params);
2428 sub pagespec_match_list ($$;@) {
2433 # Backwards compatability with old calling convention.
2435 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2436 $params{list}=$page;
2437 $page=$params{location}; # ugh!
2440 my $sub=pagespec_translate($pagespec);
2441 error "syntax error in pagespec \"$pagespec\""
2443 my $sort=sortspec_translate($params{sort}, $params{reverse})
2444 if defined $params{sort};
2447 if (exists $params{list}) {
2448 @candidates=exists $params{filter}
2449 ? grep { ! $params{filter}->($_) } @{$params{list}}
2453 @candidates=exists $params{filter}
2454 ? grep { ! $params{filter}->($_) } keys %pagesources
2455 : keys %pagesources;
2458 # clear params, remainder is passed to pagespec
2459 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2460 my $num=$params{num};
2461 delete @params{qw{num deptype reverse sort filter list}};
2463 # when only the top matches will be returned, it's efficient to
2464 # sort before matching to pagespec,
2465 if (defined $num && defined $sort) {
2466 @candidates=IkiWiki::SortSpec::sort_pages(
2467 $sort, @candidates);
2473 my $accum=IkiWiki::SuccessReason->new();
2474 foreach my $p (@candidates) {
2475 my $r=$sub->($p, %params, location => $page);
2476 error(sprintf(gettext("cannot match pages: %s"), $r))
2477 if $r->isa("IkiWiki::ErrorReason");
2478 unless ($r || $r->influences_static) {
2479 $r->remove_influence($p);
2484 last if defined $num && ++$count == $num;
2488 # Add simple dependencies for accumulated influences.
2489 my $i=$accum->influences;
2490 foreach my $k (keys %$i) {
2491 $depends_simple{$page}{lc $k} |= $i->{$k};
2494 # when all matches will be returned, it's efficient to
2495 # sort after matching
2496 if (! defined $num && defined $sort) {
2497 return IkiWiki::SortSpec::sort_pages(
2505 sub pagespec_valid ($) {
2508 return defined pagespec_translate($spec);
2512 my $re=quotemeta(shift);
2518 package IkiWiki::FailReason;
2521 '""' => sub { $_[0][0] },
2523 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2524 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2525 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2529 our @ISA = 'IkiWiki::SuccessReason';
2531 package IkiWiki::SuccessReason;
2534 '""' => sub { $_[0][0] },
2536 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2537 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2538 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2545 return bless [$value, {@_}], $class;
2550 $this->[1]={@_} if @_;
2551 my %i=%{$this->[1]};
2556 sub influences_static {
2557 return ! $_[0][1]->{""};
2560 sub merge_influences {
2565 if (! $anded || (($this || %{$this->[1]}) &&
2566 ($other || %{$other->[1]}))) {
2567 foreach my $influence (keys %{$other->[1]}) {
2568 $this->[1]{$influence} |= $other->[1]{$influence};
2577 sub remove_influence {
2581 delete $this->[1]{$torm};
2584 package IkiWiki::ErrorReason;
2586 our @ISA = 'IkiWiki::FailReason';
2588 package IkiWiki::PageSpec;
2594 if ($path =~ m!^\.(/|$)!) {
2596 $from=~s#/?[^/]+$## if defined $from;
2598 $path="$from/$path" if defined $from && length $from;
2602 $path = "" unless defined $path;
2611 sub match_glob ($$;@) {
2616 $glob=derel($glob, $params{location});
2618 # Instead of converting the glob to a regex every time,
2619 # cache the compiled regex to save time.
2620 my $re=$glob_cache{$glob};
2621 unless (defined $re) {
2622 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2625 if (! IkiWiki::isinternal($page) || $params{internal}) {
2626 return IkiWiki::SuccessReason->new("$glob matches $page");
2629 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2633 return IkiWiki::FailReason->new("$glob does not match $page");
2637 sub match_internal ($$;@) {
2638 return match_glob(shift, shift, @_, internal => 1)
2641 sub match_page ($$;@) {
2643 my $match=match_glob($page, shift, @_);
2645 my $source=exists $IkiWiki::pagesources{$page} ?
2646 $IkiWiki::pagesources{$page} :
2647 $IkiWiki::delpagesources{$page};
2648 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2649 if (! defined $type) {
2650 return IkiWiki::FailReason->new("$page is not a page");
2656 sub match_link ($$;@) {
2661 $link=derel($link, $params{location});
2662 my $from=exists $params{location} ? $params{location} : '';
2663 my $linktype=$params{linktype};
2665 if (defined $linktype) {
2666 $qualifier=" with type $linktype";
2669 my $links = $IkiWiki::links{$page};
2670 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2671 unless $links && @{$links};
2672 my $bestlink = IkiWiki::bestlink($from, $link);
2673 foreach my $p (@{$links}) {
2674 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2676 if (length $bestlink) {
2677 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2678 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2682 if (match_glob($p, $link, %params)) {
2683 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2685 my ($p_rel)=$p=~/^\/?(.*)/;
2687 if (match_glob($p_rel, $link, %params)) {
2688 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2692 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2695 sub match_backlink ($$;@) {
2699 if ($testpage eq '.') {
2700 $testpage = $params{'location'}
2702 my $ret=match_link($testpage, $page, @_);
2703 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2707 sub match_created_before ($$;@) {
2712 $testpage=derel($testpage, $params{location});
2714 if (exists $IkiWiki::pagectime{$testpage}) {
2715 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2716 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2719 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2723 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2727 sub match_created_after ($$;@) {
2732 $testpage=derel($testpage, $params{location});
2734 if (exists $IkiWiki::pagectime{$testpage}) {
2735 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2736 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2739 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2743 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2747 sub match_creation_day ($$;@) {
2750 if ($d !~ /^\d+$/) {
2751 return IkiWiki::ErrorReason->new("invalid day $d");
2753 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2754 return IkiWiki::SuccessReason->new('creation_day matched');
2757 return IkiWiki::FailReason->new('creation_day did not match');
2761 sub match_creation_month ($$;@) {
2764 if ($m !~ /^\d+$/) {
2765 return IkiWiki::ErrorReason->new("invalid month $m");
2767 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2768 return IkiWiki::SuccessReason->new('creation_month matched');
2771 return IkiWiki::FailReason->new('creation_month did not match');
2775 sub match_creation_year ($$;@) {
2778 if ($y !~ /^\d+$/) {
2779 return IkiWiki::ErrorReason->new("invalid year $y");
2781 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2782 return IkiWiki::SuccessReason->new('creation_year matched');
2785 return IkiWiki::FailReason->new('creation_year did not match');
2789 sub match_user ($$;@) {
2794 if (! exists $params{user}) {
2795 return IkiWiki::ErrorReason->new("no user specified");
2798 my $regexp=IkiWiki::glob2re($user);
2800 if (defined $params{user} && $params{user}=~$regexp) {
2801 return IkiWiki::SuccessReason->new("user is $user");
2803 elsif (! defined $params{user}) {
2804 return IkiWiki::FailReason->new("not logged in");
2807 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2811 sub match_admin ($$;@) {
2816 if (! exists $params{user}) {
2817 return IkiWiki::ErrorReason->new("no user specified");
2820 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2821 return IkiWiki::SuccessReason->new("user is an admin");
2823 elsif (! defined $params{user}) {
2824 return IkiWiki::FailReason->new("not logged in");
2827 return IkiWiki::FailReason->new("user is not an admin");
2831 sub match_ip ($$;@) {
2836 if (! exists $params{ip}) {
2837 return IkiWiki::ErrorReason->new("no IP specified");
2840 my $regexp=IkiWiki::glob2re(lc $ip);
2842 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2843 return IkiWiki::SuccessReason->new("IP is $ip");
2846 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2850 package IkiWiki::SortSpec;
2852 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2853 # are easily available in this namespace, for cmp functions to use them.
2860 IkiWiki::pagetitle(IkiWiki::basename($a))
2862 IkiWiki::pagetitle(IkiWiki::basename($b))
2865 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2866 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2867 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }