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 => "US/Eastern",
343 description => "time zone name",
350 example => '^\.htaccess$',
351 description => "regexp of normally excluded files to include",
359 example => '^(*\.private|Makefile)$',
360 description => "regexp of files that should be skipped",
365 wiki_file_prune_regexps => {
367 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
368 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
369 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
370 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
371 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
372 description => "regexps of source files to ignore",
378 description => "specifies the characters that are allowed in source filenames",
379 default => "-[:alnum:]+/.:_",
383 wiki_file_regexp => {
385 description => "regexp of legal source files",
389 web_commit_regexp => {
391 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
392 description => "regexp to parse web commits from logs",
399 description => "run as a cgi",
403 cgi_disable_uploads => {
406 description => "whether CGI should accept file uploads",
413 description => "run as a post-commit hook",
420 description => "running in rebuild mode",
427 description => "running in setup mode",
434 description => "running in clean mode",
441 description => "running in refresh mode",
448 description => "running in receive test mode",
452 wrapper_background_command => {
455 description => "background shell command to run",
461 description => "running in gettime mode",
468 description => "running in w3mmode",
475 description => "path to the .ikiwiki directory holding ikiwiki state",
482 description => "path to setup file",
488 default => "Standard",
489 description => "perl class to use to dump setup file",
493 allow_symlinks_before_srcdir => {
496 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
502 sub defaultconfig () {
505 foreach my $key (keys %s) {
506 push @ret, $key, $s{$key}->{default};
512 # URL to top of wiki as a path starting with /, valid from any wiki page or
513 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
515 # URL to CGI script, similar to $local_url
519 # locale stuff; avoid LC_ALL since it overrides everything
520 if (defined $ENV{LC_ALL}) {
521 $ENV{LANG} = $ENV{LC_ALL};
524 if (defined $config{locale}) {
525 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
526 $ENV{LANG}=$config{locale};
531 if (! defined $config{wiki_file_regexp}) {
532 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
535 if (ref $config{ENV} eq 'HASH') {
536 foreach my $val (keys %{$config{ENV}}) {
537 $ENV{$val}=$config{ENV}{$val};
540 if (defined $config{timezone} && length $config{timezone}) {
541 $ENV{TZ}=$config{timezone};
544 $config{timezone}=$ENV{TZ};
547 if ($config{w3mmode}) {
548 eval q{use Cwd q{abs_path}};
550 $config{srcdir
}=possibly_foolish_untaint
(abs_path
($config{srcdir
}));
551 $config{destdir
}=possibly_foolish_untaint
(abs_path
($config{destdir
}));
552 $config{cgiurl
}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl
}
553 unless $config{cgiurl
} =~ m!file:///!;
554 $config{url
}="file://".$config{destdir
};
557 if ($config{cgi
} && ! length $config{url
}) {
558 error
(gettext
("Must specify url to wiki with --url when using --cgi"));
561 if (defined $config{url
} && length $config{url
}) {
563 my $baseurl = URI
->new($config{url
});
565 $local_url = $baseurl->path . "/";
566 $local_cgiurl = undef;
568 if (length $config{cgiurl
}) {
569 my $cgiurl = URI
->new($config{cgiurl
});
571 $local_cgiurl = $cgiurl->path;
573 if ($cgiurl->scheme ne $baseurl->scheme or
574 $cgiurl->authority ne $baseurl->authority) {
575 # too far apart, fall back to absolute URLs
576 $local_url = "$config{url}/";
577 $local_cgiurl = $config{cgiurl
};
581 $local_url =~ s{//$}{/};
584 $local_cgiurl = $config{cgiurl
};
587 $config{wikistatedir
}="$config{srcdir}/.ikiwiki"
588 unless exists $config{wikistatedir
} && defined $config{wikistatedir
};
590 if (defined $config{umask}) {
591 umask(possibly_foolish_untaint
($config{umask}));
594 run_hooks
(checkconfig
=> sub { shift->() });
602 foreach my $dir (@INC, $config{libdir
}) {
603 next unless defined $dir && length $dir;
604 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
605 my ($plugin)=$file=~/.*\/(.*)\
.pm
$/;
609 foreach my $dir ($config{libdir
}, "$installdir/lib/ikiwiki") {
610 next unless defined $dir && length $dir;
611 foreach my $file (glob("$dir/plugins/*")) {
612 $ret{basename
($file)}=1 if -x
$file;
620 if (defined $config{libdir
} && length $config{libdir
}) {
621 unshift @INC, possibly_foolish_untaint
($config{libdir
});
624 foreach my $plugin (@
{$config{default_plugins
}}, @
{$config{add_plugins
}}) {
629 if (exists $hooks{rcs
}) {
630 error
(gettext
("cannot use multiple rcs plugins"));
632 loadplugin
($config{rcs
});
634 if (! exists $hooks{rcs
}) {
638 run_hooks
(getopt
=> sub { shift->() });
639 if (grep /^-/, @ARGV) {
640 print STDERR
"Unknown option (or missing parameter): $_\n"
641 foreach grep /^-/, @ARGV;
648 sub loadplugin
($;$) {
652 return if ! $force && grep { $_ eq $plugin} @
{$config{disable_plugins
}};
654 foreach my $dir (defined $config{libdir
} ? possibly_foolish_untaint
($config{libdir
}) : undef,
655 "$installdir/lib/ikiwiki") {
656 if (defined $dir && -x
"$dir/plugins/$plugin") {
657 eval { require IkiWiki
::Plugin
::external
};
660 error
(sprintf(gettext
("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
662 import IkiWiki
::Plugin
::external
"$dir/plugins/$plugin";
663 $loaded_plugins{$plugin}=1;
668 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint
($plugin);
671 error
("Failed to load plugin $mod: $@");
673 $loaded_plugins{$plugin}=1;
680 log_message
('err' => $message) if $config{syslog
};
681 if (defined $cleaner) {
688 return unless $config{verbose
};
689 return log_message
(debug
=> @_);
693 sub log_message
($$) {
696 if ($config{syslog
}) {
699 Sys
::Syslog
::setlogsock
('unix');
700 Sys
::Syslog
::openlog
('ikiwiki', '', 'user');
704 Sys
::Syslog
::syslog
($type, "[$config{wikiname}] %s", join(" ", @_));
707 elsif (! $config{cgi
}) {
711 return print STDERR
"@_\n";
715 sub possibly_foolish_untaint
($) {
717 my ($untainted)=$tainted=~/(.*)/s;
737 return exists $pagesources{$page} &&
738 $pagesources{$page} =~ /\._([^.]+)$/;
744 if ($file =~ /\.([^.]+)$/) {
745 return $1 if exists $hooks{htmlize
}{$1};
747 my $base=basename
($file);
748 if (exists $hooks{htmlize
}{$base} &&
749 $hooks{htmlize
}{$base}{noextension
}) {
760 if (exists $pagename_cache{$file}) {
761 return $pagename_cache{$file};
764 my $type=pagetype
($file);
766 $page=~s/\Q.$type\E*$//
767 if defined $type && !$hooks{htmlize
}{$type}{keepextension
}
768 && !$hooks{htmlize
}{$type}{noextension
};
769 if ($config{indexpages
} && $page=~/(.*)\/index
$/) {
773 $pagename_cache{$file} = $page;
777 sub newpagefile
($$) {
781 if (! $config{indexpages
} || $page eq 'index') {
782 return $page.".".$type;
785 return $page."/index.".$type;
789 sub targetpage
($$;$) {
794 if (defined $filename) {
795 return $page."/".$filename.".".$ext;
797 elsif (! $config{usedirs
} || $page eq 'index') {
798 return $page.".".$ext;
801 return $page."/index.".$ext;
808 return targetpage
($page, $config{htmlext
});
815 return "$config{srcdir}/$file", stat(_
) if -e
"$config{srcdir}/$file";
816 foreach my $dir (@
{$config{underlaydirs
}}, $config{underlaydir
}) {
817 return "$dir/$file", stat(_
) if -e
"$dir/$file";
819 error
("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
824 return (srcfile_stat
(@_))[0];
827 sub add_literal_underlay
($) {
830 if (! grep { $_ eq $dir } @
{$config{underlaydirs
}}) {
831 unshift @
{$config{underlaydirs
}}, $dir;
835 sub add_underlay
($) {
839 $dir="$config{underlaydirbase}/$dir";
842 add_literal_underlay
($dir);
843 # why does it return 1? we just don't know
847 sub readfile
($;$$) {
853 error
("cannot read a symlink ($file)");
857 open (my $in, "<", $file) || error
("failed to read $file: $!");
858 binmode($in) if ($binary);
859 return \
*$in if $wantfd;
861 # check for invalid utf-8, and toss it back to avoid crashes
862 if (! utf8
::valid
($ret)) {
863 $ret=encode_utf8
($ret);
865 close $in || error
("failed to read $file: $!");
869 sub prep_writefile
($$) {
874 while (length $test) {
875 if (-l
"$destdir/$test") {
876 error
("cannot write to a symlink ($test)");
878 if (-f _
&& $test ne $file) {
879 # Remove conflicting file.
880 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
881 foreach my $f (@
{$renderedfiles{$p}}, @
{$oldrenderedfiles{$p}}) {
883 unlink("$destdir/$test");
889 $test=dirname
($test);
892 my $dir=dirname
("$destdir/$file");
895 foreach my $s (split(m!/+!, $dir)) {
898 mkdir($d) || error
("failed to create directory $d: $!");
906 sub writefile
($$$;$$) {
907 my $file=shift; # can include subdirs
908 my $destdir=shift; # directory to put file in
913 prep_writefile
($file, $destdir);
915 my $newfile="$destdir/$file.ikiwiki-new";
917 error
("cannot write to a symlink ($newfile)");
920 my $cleanup = sub { unlink($newfile) };
921 open (my $out, '>', $newfile) || error
("failed to write $newfile: $!", $cleanup);
922 binmode($out) if ($binary);
924 $writer->(\
*$out, $cleanup);
927 print $out $content or error
("failed writing to $newfile: $!", $cleanup);
929 close $out || error
("failed saving $newfile: $!", $cleanup);
930 rename($newfile, "$destdir/$file") ||
931 error
("failed renaming $newfile to $destdir/$file: $!", $cleanup);
937 sub will_render
($$;$) {
942 # Important security check for independently created files.
943 if (-e
"$config{destdir}/$dest" && ! $config{rebuild
} &&
944 ! grep { $_ eq $dest } (@
{$renderedfiles{$page}}, @
{$oldrenderedfiles{$page}}, @
{$wikistate{editpage
}{previews
}})) {
945 my $from_other_page=0;
946 # Expensive, but rarely runs.
947 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
951 } @
{$renderedfiles{$p}}, @
{$oldrenderedfiles{$p}}) {
957 error
("$config{destdir}/$dest independently created, not overwriting with version from $page")
958 unless $from_other_page;
961 # If $dest exists as a directory, remove conflicting files in it
962 # rendered from other pages.
964 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
965 foreach my $f (@
{$renderedfiles{$p}}, @
{$oldrenderedfiles{$p}}) {
966 if (dirname
($f) eq $dest) {
967 unlink("$config{destdir}/$f");
968 rmdir(dirname
("$config{destdir}/$f"));
974 if (! $clear || $cleared{$page}) {
975 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @
{$renderedfiles{$page}}];
978 foreach my $old (@
{$renderedfiles{$page}}) {
979 delete $destsources{$old};
981 $renderedfiles{$page}=[$dest];
984 $destsources{$dest}=$page;
994 if ($link=~s/^\/+//) {
1002 $l.="/" if length $l;
1005 if (exists $pagesources{$l}) {
1008 elsif (exists $pagecase{lc $l}) {
1009 return $pagecase{lc $l};
1011 } while $cwd=~s{/?[^/]+$}{};
1013 if (length $config{userdir
}) {
1014 my $l = "$config{userdir}/".lc($link);
1015 if (exists $pagesources{$l}) {
1018 elsif (exists $pagecase{lc $l}) {
1019 return $pagecase{lc $l};
1023 #print STDERR "warning: page $page, broken link: $link\n";
1027 sub isinlinableimage
($) {
1030 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
1033 sub pagetitle
($;$) {
1035 my $unescaped=shift;
1038 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1041 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1049 # support use w/o %config set
1050 my $chars = defined $config{wiki_file_chars
} ?
$config{wiki_file_chars
} : "-[:alnum:]+/.:_";
1051 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1057 my $chars = defined $config{wiki_file_chars
} ?
$config{wiki_file_chars
} : "-[:alnum:]+/.:_";
1058 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1065 my $cgiurl=$local_cgiurl;
1067 if (exists $params{cgiurl
}) {
1068 $cgiurl=$params{cgiurl
};
1069 delete $params{cgiurl
};
1077 join("&", map $_."=".uri_escape_utf8
($params{$_}), keys %params);
1083 return $local_url if ! defined $page;
1085 $page=htmlpage
($page);
1087 $page=~s/[^\/]+\//..\//g
;
1095 return $url unless defined $urlbase && length $urlbase;
1098 URI
->new_abs($url, $urlbase)->as_string;
1102 # Work around very innefficient behavior in File::Spec if abs2rel
1103 # is passed two relative paths. It's much faster if paths are
1104 # absolute! (Debian bug #376658; fixed in debian unstable now)
1109 my $ret=File
::Spec
->abs2rel($path, $base);
1110 $ret=~s/^// if defined $ret;
1114 sub displaytime
($;$$) {
1115 # Plugins can override this function to mark up the time to
1117 my $time=formattime
($_[0], $_[1]);
1118 if ($config{html5
}) {
1119 return '<time datetime="'.date_3339
($_[0]).'"'.
1120 ($_[2] ?
' pubdate="pubdate"' : '').
1121 '>'.$time.'</time>';
1124 return '<span class="date">'.$time.'</span>';
1128 sub formattime
($;$) {
1129 # Plugins can override this function to format the time.
1132 if (! defined $format) {
1133 $format=$config{timeformat
};
1136 # strftime doesn't know about encodings, so make sure
1137 # its output is properly treated as utf8
1138 return decode_utf8
(POSIX
::strftime
($format, localtime($time)));
1144 my $lc_time=POSIX
::setlocale
(&POSIX
::LC_TIME
);
1145 POSIX
::setlocale
(&POSIX
::LC_TIME
, "C");
1146 my $ret=POSIX
::strftime
("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1147 POSIX
::setlocale
(&POSIX
::LC_TIME
, $lc_time);
1151 sub beautify_urlpath
($) {
1154 # Ensure url is not an empty link, and if necessary,
1155 # add ./ to avoid colon confusion.
1156 if ($url !~ /^\// && $url !~ /^\
.\
.?\
//) {
1160 if ($config{usedirs
}) {
1161 $url =~ s!/index.$config{htmlext}$!/!;
1176 if (! $destsources{$to}) {
1181 return $config{url
}.beautify_urlpath
("/".$to);
1184 if (! defined $from) {
1185 my $u = $local_url || '';
1187 return $u.beautify_urlpath
("/".$to);
1190 my $link = abs2rel
($to, dirname
(htmlpage
($from)));
1192 return beautify_urlpath
($link);
1195 sub isselflink
($$) {
1196 # Plugins can override this function to support special types
1201 return $page eq $link;
1204 sub htmllink
($$$;@
) {
1205 my $lpage=shift; # the page doing the linking
1206 my $page=shift; # the page that will contain the link (different for inline)
1213 if (! $opts{forcesubpage
}) {
1214 $bestlink=bestlink
($lpage, $link);
1217 $bestlink="$lpage/".lc($link);
1221 if (defined $opts{linktext
}) {
1222 $linktext=$opts{linktext
};
1225 $linktext=pagetitle
(basename
($link));
1228 return "<span class=\"selflink\">$linktext</span>"
1229 if length $bestlink && isselflink
($page, $bestlink) &&
1230 ! defined $opts{anchor
};
1232 if (! $destsources{$bestlink}) {
1233 $bestlink=htmlpage
($bestlink);
1235 if (! $destsources{$bestlink}) {
1237 if (length $config{cgiurl
}) {
1238 $cgilink = "<a href=\"".
1243 )."\" rel=\"nofollow\">?</a>";
1245 return "<span class=\"createlink\">$cgilink$linktext</span>"
1249 $bestlink=abs2rel
($bestlink, dirname
(htmlpage
($page)));
1250 $bestlink=beautify_urlpath
($bestlink);
1252 if (! $opts{noimageinline
} && isinlinableimage
($bestlink)) {
1253 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1256 if (defined $opts{anchor
}) {
1257 $bestlink.="#".$opts{anchor
};
1261 foreach my $attr (qw{rel
class title
}) {
1262 if (defined $opts{$attr}) {
1263 push @attrs, " $attr=\"$opts{$attr}\"";
1267 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1272 return length $config{userdir
} ?
"$config{userdir}/$user" : $user;
1275 sub openiduser
($) {
1278 if (defined $user && $user =~ m!^https?://! &&
1279 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@
) {
1282 if (Net
::OpenID
::VerifiedIdentity
->can("DisplayOfURL")) {
1283 $display = Net
::OpenID
::VerifiedIdentity
::DisplayOfURL
($user);
1286 # backcompat with old version
1287 my $oid=Net
::OpenID
::VerifiedIdentity
->new(identity
=> $user);
1288 $display=$oid->display;
1291 # Convert "user.somehost.com" to "user [somehost.com]"
1292 # (also "user.somehost.co.uk")
1293 if ($display !~ /\[/) {
1294 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1296 # Convert "http://somehost.com/user" to "user [somehost.com]".
1297 # (also "https://somehost.com/user/")
1298 if ($display !~ /\[/) {
1299 $display=~s/^https?:\/\/(.+)\
/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1301 $display=~s!^https?://!!; # make sure this is removed
1302 eval q{use CGI 'escapeHTML'};
1304 return escapeHTML
($display);
1309 sub htmlize
($$$$) {
1315 my $oneline = $content !~ /\n/;
1317 if (exists $hooks{htmlize
}{$type}) {
1318 $content=$hooks{htmlize
}{$type}{call
}->(
1320 content
=> $content,
1324 error
("htmlization of $type not supported");
1327 run_hooks
(sanitize
=> sub {
1330 destpage
=> $destpage,
1331 content
=> $content,
1336 # hack to get rid of enclosing junk added by markdown
1337 # and other htmlizers/sanitizers
1338 $content=~s/^<p>//i;
1339 $content=~s/<\/p>\n*$//i
;
1350 run_hooks
(linkify
=> sub {
1353 destpage
=> $destpage,
1354 content
=> $content,
1362 our $preprocess_preview=0;
1363 sub preprocess
($$$;$$) {
1364 my $page=shift; # the page the data comes from
1365 my $destpage=shift; # the page the data will appear in (different for inline)
1370 # Using local because it needs to be set within any nested calls
1372 local $preprocess_preview=$preview if defined $preview;
1379 $params="" if ! defined $params;
1381 if (length $escape) {
1382 return "[[$prefix$command $params]]";
1384 elsif (exists $hooks{preprocess
}{$command}) {
1385 return "" if $scan && ! $hooks{preprocess
}{$command}{scan
};
1386 # Note: preserve order of params, some plugins may
1387 # consider it significant.
1389 while ($params =~ m
{
1390 (?
:([-\w
]+)=)?
# 1: named parameter key?
1392 """(.*?)""" # 2: triple-quoted value
1394 "([^"]*?
)" # 3: single-quoted value
1396 (\S+) # 4: unquoted value
1398 (?:\s+|$) # delimiter to next param
1408 elsif (defined $3) {
1411 elsif (defined $4) {
1416 push @params, $key, $val;
1419 push @params, $val, '';
1422 if ($preprocessing{$page}++ > 3) {
1423 # Avoid loops of preprocessed pages preprocessing
1424 # other pages that preprocess them, etc.
1425 return "[[!$command <span
class=\"error
\">".
1426 sprintf(gettext("preprocessing
loop detected on
%s at depth
%i"),
1427 $page, $preprocessing{$page}).
1433 $hooks{preprocess}{$command}{call}->(
1436 destpage => $destpage,
1437 preview => $preprocess_preview,
1443 $ret="[[!$command <span
class=\"error
\">".
1444 gettext("Error
").": $error"."</span
>]]";
1448 # use void context during scan pass
1450 $hooks{preprocess}{$command}{call}->(
1453 destpage => $destpage,
1454 preview => $preprocess_preview,
1459 $preprocessing{$page}--;
1463 return "[[$prefix$command $params]]";
1468 if ($config{prefix_directives}) {
1471 \[\[(!) # directive open; 2: prefix
1472 ([-\w]+) # 3: command
1473 ( # 4: the parameters..
1474 \s+ # Must have space if parameters present
1476 (?:[-\w]+=)? # named parameter key?
1478 """.*?
""" # triple-quoted value
1480 "[^"]*?" # single-quoted value
1482 [^"\s\]]+ # unquoted value
1484 \s* # whitespace or end
1487 *)? # 0 or more parameters
1488 \]\] # directive closed
1494 \[\[(!?) # directive open; 2: optional prefix
1495 ([-\w]+) # 3: command
1497 ( # 4: the parameters..
1499 (?:[-\w]+=)? # named parameter key?
1501 """.*?
""" # triple-quoted value
1503 "[^"]*?" # single-quoted value
1505 [^"\s\]]+ # unquoted value
1507 \s* # whitespace or end
1510 *) # 0 or more parameters
1511 \]\] # directive closed
1515 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1524 run_hooks(filter => sub {
1525 $content=shift->(page => $page, destpage => $destpage,
1526 content => $content);
1532 sub check_canedit ($$$;$) {
1539 run_hooks(canedit => sub {
1540 return if defined $canedit;
1541 my $ret=shift->($page, $q, $session);
1546 elsif (ref $ret eq 'CODE') {
1547 $ret->() unless $nonfatal;
1550 elsif (defined $ret) {
1551 error($ret) unless $nonfatal;
1556 return defined $canedit ? $canedit : 1;
1559 sub check_content (@) {
1562 return 1 if ! exists $hooks{checkcontent}; # optimisation
1564 if (exists $pagesources{$params{page}}) {
1566 my %old=map { $_ => 1 }
1567 split("\n", readfile(srcfile($pagesources{$params{page}})));
1568 foreach my $line (split("\n", $params{content})) {
1569 push @diff, $line if ! exists $old{$line};
1571 $params{diff}=join("\n", @diff);
1575 run_hooks(checkcontent => sub {
1576 return if defined $ok;
1577 my $ret=shift->(%params);
1582 elsif (ref $ret eq 'CODE') {
1583 $ret->() unless $params{nonfatal};
1586 elsif (defined $ret) {
1587 error($ret) unless $params{nonfatal};
1593 return defined $ok ? $ok : 1;
1596 sub check_canchange (@) {
1598 my $cgi = $params{cgi};
1599 my $session = $params{session};
1600 my @changes = @{$params{changes}};
1603 foreach my $change (@changes) {
1604 # This untaint is safe because we check file_pruned and
1606 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1607 $file=possibly_foolish_untaint($file);
1608 if (! defined $file || ! length $file ||
1609 file_pruned($file)) {
1610 error(gettext("bad file name
%s"), $file);
1613 my $type=pagetype($file);
1614 my $page=pagename($file) if defined $type;
1616 if ($change->{action} eq 'add') {
1620 if ($change->{action} eq 'change' ||
1621 $change->{action} eq 'add') {
1622 if (defined $page) {
1623 check_canedit($page, $cgi, $session);
1627 if (IkiWiki::Plugin::attachment->can("check_canattach
")) {
1628 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1629 check_canedit($file, $cgi, $session);
1634 elsif ($change->{action} eq 'remove') {
1635 # check_canremove tests to see if the file is present
1636 # on disk. This will fail when a single commit adds a
1637 # file and then removes it again. Avoid the problem
1638 # by not testing the removal in such pairs of changes.
1639 # (The add is still tested, just to make sure that
1640 # no data is added to the repo that a web edit
1642 next if $newfiles{$file};
1644 if (IkiWiki::Plugin::remove->can("check_canremove
")) {
1645 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1646 check_canedit(defined $page ? $page : $file, $cgi, $session);
1651 error "unknown action
".$change->{action};
1654 error sprintf(gettext("you are
not allowed to change
%s"), $file);
1662 # Take an exclusive lock on the wiki to prevent multiple concurrent
1663 # run issues. The lock will be dropped on program exit.
1664 if (! -d $config{wikistatedir}) {
1665 mkdir($config{wikistatedir});
1667 open($wikilock, '>', "$config{wikistatedir
}/lockfile
") ||
1668 error ("cannot
write to
$config{wikistatedir
}/lockfile
: $!");
1669 if (! flock($wikilock, 2)) { # LOCK_EX
1670 error("failed to get
lock");
1676 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1677 return close($wikilock) if $wikilock;
1683 sub commit_hook_enabled () {
1684 open($commitlock, '+>', "$config{wikistatedir
}/commitlock
") ||
1685 error("cannot
write to
$config{wikistatedir
}/commitlock
: $!");
1686 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1687 close($commitlock) || error("failed closing commitlock
: $!");
1690 close($commitlock) || error("failed closing commitlock
: $!");
1694 sub disable_commit_hook () {
1695 open($commitlock, '>', "$config{wikistatedir
}/commitlock
") ||
1696 error("cannot
write to
$config{wikistatedir
}/commitlock
: $!");
1697 if (! flock($commitlock, 2)) { # LOCK_EX
1698 error("failed to get commit
lock");
1703 sub enable_commit_hook () {
1704 return close($commitlock) if $commitlock;
1709 %oldrenderedfiles=%pagectime=();
1710 if (! $config{rebuild}) {
1711 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1712 %destsources=%renderedfiles=%pagecase=%pagestate=
1713 %depends_simple=%typedlinks=%oldtypedlinks=();
1716 if (! open ($in, "<", "$config{wikistatedir
}/indexdb
")) {
1717 if (-e "$config{wikistatedir
}/index") {
1718 system("ikiwiki
-transition
", "indexdb
", $config{srcdir});
1719 open ($in, "<", "$config{wikistatedir
}/indexdb
") || return;
1722 $config{gettime}=1; # first build
1727 my $index=Storable::fd_retrieve($in);
1728 if (! defined $index) {
1733 if (exists $index->{version} && ! ref $index->{version}) {
1734 $pages=$index->{page};
1735 %wikistate=%{$index->{state}};
1736 # Handle plugins that got disabled by loading a new setup.
1737 if (exists $config{setupfile}) {
1738 require IkiWiki::Setup;
1739 IkiWiki::Setup::disabled_plugins(
1740 grep { ! $loaded_plugins{$_} } keys %wikistate);
1748 foreach my $src (keys %$pages) {
1749 my $d=$pages->{$src};
1750 my $page=pagename($src);
1751 $pagectime{$page}=$d->{ctime};
1752 $pagesources{$page}=$src;
1753 if (! $config{rebuild}) {
1754 $pagemtime{$page}=$d->{mtime};
1755 $renderedfiles{$page}=$d->{dest};
1756 if (exists $d->{links} && ref $d->{links}) {
1757 $links{$page}=$d->{links};
1758 $oldlinks{$page}=[@{$d->{links}}];
1760 if (ref $d->{depends_simple} eq 'ARRAY') {
1762 $depends_simple{$page}={
1763 map { $_ => 1 } @{$d->{depends_simple}}
1766 elsif (exists $d->{depends_simple}) {
1767 $depends_simple{$page}=$d->{depends_simple};
1769 if (exists $d->{dependslist}) {
1772 map { $_ => $DEPEND_CONTENT }
1773 @{$d->{dependslist}}
1776 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1778 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1780 elsif (exists $d->{depends}) {
1781 $depends{$page}=$d->{depends};
1783 if (exists $d->{state}) {
1784 $pagestate{$page}=$d->{state};
1786 if (exists $d->{typedlinks}) {
1787 $typedlinks{$page}=$d->{typedlinks};
1789 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1790 next unless %$links;
1791 $oldtypedlinks{$page}{$type} = {%$links};
1795 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1797 foreach my $page (keys %pagesources) {
1798 $pagecase{lc $page}=$page;
1800 foreach my $page (keys %renderedfiles) {
1801 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1807 run_hooks(savestate => sub { shift->() });
1809 my @plugins=keys %loaded_plugins;
1811 if (! -d $config{wikistatedir}) {
1812 mkdir($config{wikistatedir});
1814 my $newfile="$config{wikistatedir
}/indexdb
.new
";
1815 my $cleanup = sub { unlink($newfile) };
1816 open (my $out, '>', $newfile) || error("cannot
write to
$newfile: $!", $cleanup);
1819 foreach my $page (keys %pagemtime) {
1820 next unless $pagemtime{$page};
1821 my $src=$pagesources{$page};
1823 $index{page}{$src}={
1824 ctime => $pagectime{$page},
1825 mtime => $pagemtime{$page},
1826 dest => $renderedfiles{$page},
1827 links => $links{$page},
1830 if (exists $depends{$page}) {
1831 $index{page}{$src}{depends} = $depends{$page};
1834 if (exists $depends_simple{$page}) {
1835 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1838 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1839 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1842 if (exists $pagestate{$page}) {
1843 foreach my $id (@plugins) {
1844 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1845 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1852 foreach my $id (@plugins) {
1853 $index{state}{$id}={}; # used to detect disabled plugins
1854 foreach my $key (keys %{$wikistate{$id}}) {
1855 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1859 $index{version}="3";
1860 my $ret=Storable::nstore_fd(\%index, $out);
1861 return if ! defined $ret || ! $ret;
1862 close $out || error("failed saving to
$newfile: $!", $cleanup);
1863 rename($newfile, "$config{wikistatedir
}/indexdb
") ||
1864 error("failed renaming
$newfile to
$config{wikistatedir
}/indexdb
", $cleanup);
1869 sub template_file ($) {
1872 my $tpage=($name =~ s/^\///) ? $name : "templates
/$name";
1874 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1875 $template=srcfile($pagesources{$tpage}, 1);
1879 $template=srcfile($tpage, 1);
1882 if (defined $template) {
1883 return $template, $tpage, 1 if wantarray;
1887 $name=~s:/::; # avoid path traversal
1888 foreach my $dir ($config{templatedir},
1889 "$installdir/share/ikiwiki
/templates
") {
1890 if (-e "$dir/$name") {
1891 $template="$dir/$name";
1895 if (defined $template) {
1896 return $template, $tpage if wantarray;
1904 sub template_depends ($$;@) {
1908 my ($filename, $tpage, $untrusted)=template_file($name);
1909 if (! defined $filename) {
1910 error(sprintf(gettext("template
%s not found
"), $name))
1913 if (defined $page && defined $tpage) {
1914 add_depends($page, $tpage);
1919 my $text_ref = shift;
1920 ${$text_ref} = decode_utf8(${$text_ref});
1922 loop_context_vars => 1,
1923 die_on_bad_params => 0,
1924 parent_global_vars => 1,
1925 filename => $filename,
1927 ($untrusted ? (no_includes => 1) : ()),
1929 return @opts if wantarray;
1931 require HTML::Template;
1932 return HTML::Template->new(@opts);
1935 sub template ($;@) {
1936 template_depends(shift, undef, @_);
1939 sub templateactions ($$) {
1945 run_hooks(pageactions => sub {
1946 push @actions, map { { action => $_ } }
1947 grep { defined } shift->(page => $page);
1949 $template->param(actions => \@actions);
1951 if ($config{cgiurl} && exists $hooks{auth}) {
1952 $template->param(prefsurl => cgiurl(do => "prefs
"));
1956 if ($have_actions || @actions) {
1957 $template->param(have_actions => 1);
1964 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1965 error 'hook requires type, call, and id parameters';
1968 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1970 $hooks{$param{type}}{$param{id}}=\%param;
1974 sub run_hooks ($$) {
1975 # Calls the given sub for each hook of the given type,
1976 # passing it the hook function to call.
1980 if (exists $hooks{$type}) {
1981 my (@first, @middle, @last);
1982 foreach my $id (keys %{$hooks{$type}}) {
1983 if ($hooks{$type}{$id}{first}) {
1986 elsif ($hooks{$type}{$id}{last}) {
1993 foreach my $id (@first, @middle, @last) {
1994 $sub->($hooks{$type}{$id}{call});
2002 $hooks{rcs}{rcs_update}{call}->(@_);
2005 sub rcs_prepedit ($) {
2006 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2009 sub rcs_commit (@) {
2010 $hooks{rcs}{rcs_commit}{call}->(@_);
2013 sub rcs_commit_staged (@) {
2014 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2018 $hooks{rcs}{rcs_add}{call}->(@_);
2021 sub rcs_remove ($) {
2022 $hooks{rcs}{rcs_remove}{call}->(@_);
2025 sub rcs_rename ($$) {
2026 $hooks{rcs}{rcs_rename}{call}->(@_);
2029 sub rcs_recentchanges ($) {
2030 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2033 sub rcs_diff ($;$) {
2034 $hooks{rcs}{rcs_diff}{call}->(@_);
2037 sub rcs_getctime ($) {
2038 $hooks{rcs}{rcs_getctime}{call}->(@_);
2041 sub rcs_getmtime ($) {
2042 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2045 sub rcs_receive () {
2046 $hooks{rcs}{rcs_receive}{call}->();
2049 sub add_depends ($$;$) {
2052 my $deptype=shift || $DEPEND_CONTENT;
2054 # Is the pagespec a simple page name?
2055 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2056 $pagespec !~ /[\s*?()!]/) {
2057 $depends_simple{$page}{lc $pagespec} |= $deptype;
2061 # Add explicit dependencies for influences.
2062 my $sub=pagespec_translate($pagespec);
2063 return unless defined $sub;
2064 foreach my $p (keys %pagesources) {
2065 my $r=$sub->($p, location => $page);
2066 my $i=$r->influences;
2067 my $static=$r->influences_static;
2068 foreach my $k (keys %$i) {
2069 next unless $r || $static || $k eq $page;
2070 $depends_simple{$page}{lc $k} |= $i->{$k};
2075 $depends{$page}{$pagespec} |= $deptype;
2081 foreach my $type (@_) {
2082 if ($type eq 'presence') {
2083 $deptype |= $DEPEND_PRESENCE;
2085 elsif ($type eq 'links') {
2086 $deptype |= $DEPEND_LINKS;
2088 elsif ($type eq 'content') {
2089 $deptype |= $DEPEND_CONTENT;
2095 my $file_prune_regexp;
2096 sub file_pruned ($) {
2099 if (defined $config{include} && length $config{include}) {
2100 return 0 if $file =~ m/$config{include}/;
2103 if (! defined $file_prune_regexp) {
2104 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2105 $file_prune_regexp=qr/$file_prune_regexp/;
2107 return $file =~ m/$file_prune_regexp/;
2110 sub define_gettext () {
2111 # If translation is needed, redefine the gettext function to do it.
2112 # Otherwise, it becomes a quick no-op.
2115 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2116 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2117 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2119 $gettext_obj=eval q{
2120 use Locale::gettext q{textdomain};
2121 Locale
::gettext
->domain('ikiwiki')
2126 no warnings
'redefine';
2128 $getobj->() if $getobj;
2130 $gettext_obj->get(shift);
2137 $getobj->() if $getobj;
2139 $gettext_obj->nget(@_);
2142 return ($_[2] == 1 ?
$_[0] : $_[1])
2160 return (defined $val && (lc($val) eq gettext
("yes") || lc($val) eq "yes" || $val eq "1"));
2164 # Injects a new function into the symbol table to replace an
2165 # exported function.
2168 # This is deep ugly perl foo, beware.
2171 if (! defined $params{parent
}) {
2172 $params{parent
}='::';
2173 $params{old
}=\
&{$params{name
}};
2174 $params{name
}=~s/.*:://;
2176 my $parent=$params{parent
};
2177 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2178 $ns = $params{parent
} . $ns;
2179 inject
(%params, parent
=> $ns) unless $ns eq '::main::';
2180 *{$ns . $params{name
}} = $params{call
}
2181 if exists ${$ns}{$params{name
}} &&
2182 \
&{${$ns}{$params{name
}}} == $params{old
};
2188 sub add_link
($$;$) {
2193 push @
{$links{$page}}, $link
2194 unless grep { $_ eq $link } @
{$links{$page}};
2196 if (defined $type) {
2197 $typedlinks{$page}{$type}{$link} = 1;
2201 sub add_autofile
($$$) {
2204 my $generator=shift;
2206 $autofiles{$file}{plugin
}=$plugin;
2207 $autofiles{$file}{generator
}=$generator;
2210 sub sortspec_translate
($$) {
2212 my $reverse = shift;
2218 (-?
) # group 1: perhaps negated
2221 \w
+\
([^\
)]*\
) # command(params)
2223 [^\s
]+ # or anything else
2231 if ($word =~ m/^(\w+)\((.*)\)$/) {
2232 # command with parameters
2236 elsif ($word !~ m/^\w+$/) {
2237 error
(sprintf(gettext
("invalid sort type %s"), $word));
2248 if (exists $IkiWiki::SortSpec
::{"cmp_$word"}) {
2249 if (defined $params) {
2250 push @data, $params;
2251 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2254 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2258 error
(sprintf(gettext
("unknown sort type %s"), $word));
2262 if (! length $code) {
2263 # undefined sorting method... sort arbitrarily
2272 return eval 'sub { '.$code.' }';
2275 sub pagespec_translate
($) {
2278 # Convert spec to perl code.
2282 \s
* # ignore whitespace
2283 ( # 1: match a single word
2290 \w
+\
([^\
)]*\
) # command(params)
2292 [^\s
()]+ # any other text
2294 \s
* # ignore whitespace
2297 if (lc $word eq 'and') {
2300 elsif (lc $word eq 'or') {
2303 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2306 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2307 if (exists $IkiWiki::PageSpec
::{"match_$1"}) {
2309 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2312 push @data, qq{unknown function
in pagespec
"$word"};
2313 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2318 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2322 if (! length $code) {
2323 $code="IkiWiki::FailReason->new('empty pagespec')";
2327 return eval 'sub { my $page=shift; '.$code.' }';
2330 sub pagespec_match
($$;@
) {
2335 # Backwards compatability with old calling convention.
2337 unshift @params, 'location';
2340 my $sub=pagespec_translate
($spec);
2341 return IkiWiki
::ErrorReason
->new("syntax error in pagespec \"$spec\"")
2343 return $sub->($page, @params);
2346 sub pagespec_match_list
($$;@
) {
2351 # Backwards compatability with old calling convention.
2353 print STDERR
"warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2354 $params{list
}=$page;
2355 $page=$params{location
}; # ugh!
2358 my $sub=pagespec_translate
($pagespec);
2359 error
"syntax error in pagespec \"$pagespec\""
2361 my $sort=sortspec_translate
($params{sort}, $params{reverse})
2362 if defined $params{sort};
2365 if (exists $params{list
}) {
2366 @candidates=exists $params{filter
}
2367 ?
grep { ! $params{filter
}->($_) } @
{$params{list
}}
2371 @candidates=exists $params{filter
}
2372 ?
grep { ! $params{filter
}->($_) } keys %pagesources
2373 : keys %pagesources;
2376 # clear params, remainder is passed to pagespec
2377 $depends{$page}{$pagespec} |= ($params{deptype
} || $DEPEND_CONTENT);
2378 my $num=$params{num
};
2379 delete @params{qw{num deptype
reverse sort filter list
}};
2381 # when only the top matches will be returned, it's efficient to
2382 # sort before matching to pagespec,
2383 if (defined $num && defined $sort) {
2384 @candidates=IkiWiki
::SortSpec
::sort_pages
(
2385 $sort, @candidates);
2391 my $accum=IkiWiki
::SuccessReason
->new();
2392 foreach my $p (@candidates) {
2393 my $r=$sub->($p, %params, location
=> $page);
2394 error
(sprintf(gettext
("cannot match pages: %s"), $r))
2395 if $r->isa("IkiWiki::ErrorReason");
2396 unless ($r || $r->influences_static) {
2397 $r->remove_influence($p);
2402 last if defined $num && ++$count == $num;
2406 # Add simple dependencies for accumulated influences.
2407 my $i=$accum->influences;
2408 foreach my $k (keys %$i) {
2409 $depends_simple{$page}{lc $k} |= $i->{$k};
2412 # when all matches will be returned, it's efficient to
2413 # sort after matching
2414 if (! defined $num && defined $sort) {
2415 return IkiWiki
::SortSpec
::sort_pages
(
2423 sub pagespec_valid
($) {
2426 return defined pagespec_translate
($spec);
2430 my $re=quotemeta(shift);
2436 package IkiWiki
::FailReason
;
2439 '""' => sub { $_[0][0] },
2441 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2442 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2443 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2447 our @ISA = 'IkiWiki::SuccessReason';
2449 package IkiWiki
::SuccessReason
;
2452 '""' => sub { $_[0][0] },
2454 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2455 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2456 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2463 return bless [$value, {@_}], $class;
2468 $this->[1]={@_} if @_;
2469 my %i=%{$this->[1]};
2474 sub influences_static
{
2475 return ! $_[0][1]->{""};
2478 sub merge_influences
{
2483 if (! $anded || (($this || %{$this->[1]}) &&
2484 ($other || %{$other->[1]}))) {
2485 foreach my $influence (keys %{$other->[1]}) {
2486 $this->[1]{$influence} |= $other->[1]{$influence};
2495 sub remove_influence
{
2499 delete $this->[1]{$torm};
2502 package IkiWiki
::ErrorReason
;
2504 our @ISA = 'IkiWiki::FailReason';
2506 package IkiWiki
::PageSpec
;
2512 if ($path =~ m!^\.(/|$)!) {
2514 $from=~s
#/?[^/]+$## if defined $from;
2516 $path="$from/$path" if defined $from && length $from;
2520 $path = "" unless defined $path;
2529 sub match_glob
($$;@
) {
2534 $glob=derel
($glob, $params{location
});
2536 # Instead of converting the glob to a regex every time,
2537 # cache the compiled regex to save time.
2538 my $re=$glob_cache{$glob};
2539 unless (defined $re) {
2540 $glob_cache{$glob} = $re = IkiWiki
::glob2re
($glob);
2543 if (! IkiWiki
::isinternal
($page) || $params{internal
}) {
2544 return IkiWiki
::SuccessReason
->new("$glob matches $page");
2547 return IkiWiki
::FailReason
->new("$glob matches $page, but the page is an internal page");
2551 return IkiWiki
::FailReason
->new("$glob does not match $page");
2555 sub match_internal
($$;@
) {
2556 return match_glob
(shift, shift, @_, internal
=> 1)
2559 sub match_page
($$;@
) {
2561 my $match=match_glob
($page, shift, @_);
2563 my $source=exists $IkiWiki::pagesources
{$page} ?
2564 $IkiWiki::pagesources
{$page} :
2565 $IkiWiki::delpagesources
{$page};
2566 my $type=defined $source ? IkiWiki
::pagetype
($source) : undef;
2567 if (! defined $type) {
2568 return IkiWiki
::FailReason
->new("$page is not a page");
2574 sub match_link
($$;@
) {
2579 $link=derel
($link, $params{location
});
2580 my $from=exists $params{location
} ?
$params{location
} : '';
2581 my $linktype=$params{linktype
};
2583 if (defined $linktype) {
2584 $qualifier=" with type $linktype";
2587 my $links = $IkiWiki::links
{$page};
2588 return IkiWiki
::FailReason
->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS
, "" => 1)
2589 unless $links && @
{$links};
2590 my $bestlink = IkiWiki
::bestlink
($from, $link);
2591 foreach my $p (@
{$links}) {
2592 next unless (! defined $linktype || exists $IkiWiki::typedlinks
{$page}{$linktype}{$p});
2594 if (length $bestlink) {
2595 if ($bestlink eq IkiWiki
::bestlink
($page, $p)) {
2596 return IkiWiki
::SuccessReason
->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS
, "" => 1)
2600 if (match_glob
($p, $link, %params)) {
2601 return IkiWiki
::SuccessReason
->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS
, "" => 1)
2603 my ($p_rel)=$p=~/^\/?
(.*)/;
2605 if (match_glob
($p_rel, $link, %params)) {
2606 return IkiWiki
::SuccessReason
->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS
, "" => 1)
2610 return IkiWiki
::FailReason
->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS
, "" => 1);
2613 sub match_backlink
($$;@
) {
2614 my $ret=match_link
($_[1], $_[0], @_);
2615 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS
);
2619 sub match_created_before
($$;@
) {
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 before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2631 return IkiWiki
::FailReason
->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2635 return IkiWiki
::ErrorReason
->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2639 sub match_created_after
($$;@
) {
2644 $testpage=derel
($testpage, $params{location
});
2646 if (exists $IkiWiki::pagectime
{$testpage}) {
2647 if ($IkiWiki::pagectime
{$page} > $IkiWiki::pagectime
{$testpage}) {
2648 return IkiWiki
::SuccessReason
->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2651 return IkiWiki
::FailReason
->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2655 return IkiWiki
::ErrorReason
->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE
);
2659 sub match_creation_day
($$;@
) {
2662 if ($d !~ /^\d+$/) {
2663 return IkiWiki
::ErrorReason
->new("invalid day $d");
2665 if ((localtime($IkiWiki::pagectime
{$page}))[3] == $d) {
2666 return IkiWiki
::SuccessReason
->new('creation_day matched');
2669 return IkiWiki
::FailReason
->new('creation_day did not match');
2673 sub match_creation_month
($$;@
) {
2676 if ($m !~ /^\d+$/) {
2677 return IkiWiki
::ErrorReason
->new("invalid month $m");
2679 if ((localtime($IkiWiki::pagectime
{$page}))[4] + 1 == $m) {
2680 return IkiWiki
::SuccessReason
->new('creation_month matched');
2683 return IkiWiki
::FailReason
->new('creation_month did not match');
2687 sub match_creation_year
($$;@
) {
2690 if ($y !~ /^\d+$/) {
2691 return IkiWiki
::ErrorReason
->new("invalid year $y");
2693 if ((localtime($IkiWiki::pagectime
{$page}))[5] + 1900 == $y) {
2694 return IkiWiki
::SuccessReason
->new('creation_year matched');
2697 return IkiWiki
::FailReason
->new('creation_year did not match');
2701 sub match_user
($$;@
) {
2706 my $regexp=IkiWiki
::glob2re
($user);
2708 if (! exists $params{user
}) {
2709 return IkiWiki
::ErrorReason
->new("no user specified");
2712 if (defined $params{user
} && $params{user
}=~$regexp) {
2713 return IkiWiki
::SuccessReason
->new("user is $user");
2715 elsif (! defined $params{user
}) {
2716 return IkiWiki
::FailReason
->new("not logged in");
2719 return IkiWiki
::FailReason
->new("user is $params{user}, not $user");
2723 sub match_admin
($$;@
) {
2728 if (! exists $params{user
}) {
2729 return IkiWiki
::ErrorReason
->new("no user specified");
2732 if (defined $params{user
} && IkiWiki
::is_admin
($params{user
})) {
2733 return IkiWiki
::SuccessReason
->new("user is an admin");
2735 elsif (! defined $params{user
}) {
2736 return IkiWiki
::FailReason
->new("not logged in");
2739 return IkiWiki
::FailReason
->new("user is not an admin");
2743 sub match_ip
($$;@
) {
2748 if (! exists $params{ip
}) {
2749 return IkiWiki
::ErrorReason
->new("no IP specified");
2752 if (defined $params{ip
} && lc $params{ip
} eq lc $ip) {
2753 return IkiWiki
::SuccessReason
->new("IP is $ip");
2756 return IkiWiki
::FailReason
->new("IP is $params{ip}, not $ip");
2760 package IkiWiki
::SortSpec
;
2762 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2763 # are easily available in this namespace, for cmp functions to use them.
2770 IkiWiki
::pagetitle
(IkiWiki
::basename
($a))
2772 IkiWiki
::pagetitle
(IkiWiki
::basename
($b))
2775 sub cmp_mtime
{ $IkiWiki::pagemtime
{$b} <=> $IkiWiki::pagemtime
{$a} }
2776 sub cmp_age
{ $IkiWiki::pagectime
{$b} <=> $IkiWiki::pagectime
{$a} }