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 => { file => "$ENV{HOME}/.ikiwiki/cookies" },
519 description => "cookie control",
520 safe => 0, # hooks into perl module internals
525 sub defaultconfig () {
528 foreach my $key (keys %s) {
529 push @ret, $key, $s{$key}->{default};
534 # URL to top of wiki as a path starting with /, valid from any wiki page or
535 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
537 # URL to CGI script, similar to $local_url
541 # locale stuff; avoid LC_ALL since it overrides everything
542 if (defined $ENV{LC_ALL}) {
543 $ENV{LANG} = $ENV{LC_ALL};
546 if (defined $config{locale}) {
547 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
548 $ENV{LANG}=$config{locale};
553 if (! defined $config{wiki_file_regexp}) {
554 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
557 if (ref $config{ENV} eq 'HASH') {
558 foreach my $val (keys %{$config{ENV}}) {
559 $ENV{$val}=$config{ENV}{$val};
562 if (defined $config{timezone} && length $config{timezone}) {
563 $ENV{TZ}=$config{timezone};
566 $config{timezone}=$ENV{TZ};
569 if ($config{w3mmode}) {
570 eval q{use Cwd q{abs_path}};
572 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
573 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
574 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
575 unless $config{cgiurl} =~ m!file:///!;
576 $config{url}="file://".$config{destdir};
579 if ($config{cgi} && ! length $config{url}) {
580 error(gettext("Must specify url to wiki with --url when using --cgi"));
583 if (defined $config{url} && length $config{url}) {
585 my $baseurl = URI->new($config{url});
587 $local_url = $baseurl->path . "/";
588 $local_cgiurl = undef;
590 if (length $config{cgiurl}) {
591 my $cgiurl = URI->new($config{cgiurl});
593 $local_cgiurl = $cgiurl->path;
595 if ($cgiurl->scheme ne $baseurl->scheme or
596 $cgiurl->authority ne $baseurl->authority) {
597 # too far apart, fall back to absolute URLs
598 $local_url = "$config{url}/";
599 $local_cgiurl = $config{cgiurl};
603 $local_url =~ s{//$}{/};
606 $local_cgiurl = $config{cgiurl};
609 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
610 unless exists $config{wikistatedir} && defined $config{wikistatedir};
612 if (defined $config{umask}) {
613 my $u = possibly_foolish_untaint($config{umask});
615 if ($u =~ m/^\d+$/) {
618 elsif ($u eq 'private') {
621 elsif ($u eq 'group') {
624 elsif ($u eq 'public') {
628 error(sprintf(gettext("unsupported umask setting %s"), $u));
632 run_hooks(checkconfig => sub { shift->() });
640 foreach my $dir (@INC, $config{libdir}) {
641 next unless defined $dir && length $dir;
642 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
643 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
647 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
648 next unless defined $dir && length $dir;
649 foreach my $file (glob("$dir/plugins/*")) {
650 $ret{basename($file)}=1 if -x $file;
658 if (defined $config{libdir} && length $config{libdir}) {
659 unshift @INC, possibly_foolish_untaint($config{libdir});
662 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
667 if (exists $hooks{rcs}) {
668 error(gettext("cannot use multiple rcs plugins"));
670 loadplugin($config{rcs});
672 if (! exists $hooks{rcs}) {
676 run_hooks(getopt => sub { shift->() });
677 if (grep /^-/, @ARGV) {
678 print STDERR "Unknown option (or missing parameter): $_\n"
679 foreach grep /^-/, @ARGV;
686 sub loadplugin ($;$) {
690 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
692 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
693 "$installdir/lib/ikiwiki") {
694 if (defined $dir && -x "$dir/plugins/$plugin") {
695 eval { require IkiWiki::Plugin::external };
698 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
700 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
701 $loaded_plugins{$plugin}=1;
706 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
709 error("Failed to load plugin $mod: $@");
711 $loaded_plugins{$plugin}=1;
718 log_message('err' => $message) if $config{syslog};
719 if (defined $cleaner) {
726 return unless $config{verbose};
727 return log_message(debug => @_);
732 sub log_message ($$) {
735 if ($config{syslog}) {
738 Sys::Syslog::setlogsock('unix');
739 Sys::Syslog::openlog('ikiwiki', '', 'user');
743 # keep a copy to avoid editing the original config repeatedly
744 my $wikiname = $config{wikiname};
745 utf8::encode($wikiname);
746 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
749 print STDERR "failed to syslog: $@" unless $log_failed;
755 elsif (! $config{cgi}) {
759 return print STDERR "@_\n";
763 sub possibly_foolish_untaint ($) {
765 my ($untainted)=$tainted=~/(.*)/s;
785 return exists $pagesources{$page} &&
786 $pagesources{$page} =~ /\._([^.]+)$/;
792 if ($file =~ /\.([^.]+)$/) {
793 return $1 if exists $hooks{htmlize}{$1};
795 my $base=basename($file);
796 if (exists $hooks{htmlize}{$base} &&
797 $hooks{htmlize}{$base}{noextension}) {
808 if (exists $pagename_cache{$file}) {
809 return $pagename_cache{$file};
812 my $type=pagetype($file);
814 $page=~s/\Q.$type\E*$//
815 if defined $type && !$hooks{htmlize}{$type}{keepextension}
816 && !$hooks{htmlize}{$type}{noextension};
817 if ($config{indexpages} && $page=~/(.*)\/index$/) {
821 $pagename_cache{$file} = $page;
825 sub newpagefile ($$) {
829 if (! $config{indexpages} || $page eq 'index') {
830 return $page.".".$type;
833 return $page."/index.".$type;
837 sub targetpage ($$;$) {
842 if (defined $filename) {
843 return $page."/".$filename.".".$ext;
845 elsif (! $config{usedirs} || $page eq 'index') {
846 return $page.".".$ext;
849 return $page."/index.".$ext;
856 return targetpage($page, $config{htmlext});
863 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
864 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
865 return "$dir/$file", stat(_) if -e "$dir/$file";
867 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
872 return (srcfile_stat(@_))[0];
875 sub add_literal_underlay ($) {
878 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
879 unshift @{$config{underlaydirs}}, $dir;
883 sub add_underlay ($) {
887 $dir="$config{underlaydirbase}/$dir";
890 add_literal_underlay($dir);
891 # why does it return 1? we just don't know
895 sub readfile ($;$$) {
901 error("cannot read a symlink ($file)");
905 open (my $in, "<", $file) || error("failed to read $file: $!");
906 binmode($in) if ($binary);
907 return \*$in if $wantfd;
909 # check for invalid utf-8, and toss it back to avoid crashes
910 if (! utf8::valid($ret)) {
911 $ret=encode_utf8($ret);
913 close $in || error("failed to read $file: $!");
917 sub prep_writefile ($$) {
922 while (length $test) {
923 if (-l "$destdir/$test") {
924 error("cannot write to a symlink ($test)");
926 if (-f _ && $test ne $file) {
927 # Remove conflicting file.
928 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
929 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
931 unlink("$destdir/$test");
937 $test=dirname($test);
940 my $dir=dirname("$destdir/$file");
943 foreach my $s (split(m!/+!, $dir)) {
946 mkdir($d) || error("failed to create directory $d: $!");
954 sub writefile ($$$;$$) {
955 my $file=shift; # can include subdirs
956 my $destdir=shift; # directory to put file in
961 prep_writefile($file, $destdir);
963 my $newfile="$destdir/$file.ikiwiki-new";
965 error("cannot write to a symlink ($newfile)");
968 my $cleanup = sub { unlink($newfile) };
969 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
970 binmode($out) if ($binary);
972 $writer->(\*$out, $cleanup);
975 print $out $content or error("failed writing to $newfile: $!", $cleanup);
977 close $out || error("failed saving $newfile: $!", $cleanup);
978 rename($newfile, "$destdir/$file") ||
979 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
985 sub will_render ($$;$) {
990 # Important security check for independently created files.
991 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
992 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
993 my $from_other_page=0;
994 # Expensive, but rarely runs.
995 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
999 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1005 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1006 unless $from_other_page;
1009 # If $dest exists as a directory, remove conflicting files in it
1010 # rendered from other pages.
1012 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1013 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1014 if (dirname($f) eq $dest) {
1015 unlink("$config{destdir}/$f");
1016 rmdir(dirname("$config{destdir}/$f"));
1022 if (! $clear || $cleared{$page}) {
1023 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1026 foreach my $old (@{$renderedfiles{$page}}) {
1027 delete $destsources{$old};
1029 $renderedfiles{$page}=[$dest];
1032 $destsources{$dest}=$page;
1042 if ($link=~s/^\/+//) {
1050 $l.="/" if length $l;
1053 if (exists $pagesources{$l}) {
1056 elsif (exists $pagecase{lc $l}) {
1057 return $pagecase{lc $l};
1059 } while $cwd=~s{/?[^/]+$}{};
1061 if (length $config{userdir}) {
1062 my $l = "$config{userdir}/".lc($link);
1063 if (exists $pagesources{$l}) {
1066 elsif (exists $pagecase{lc $l}) {
1067 return $pagecase{lc $l};
1071 #print STDERR "warning: page $page, broken link: $link\n";
1075 sub isinlinableimage ($) {
1078 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1081 sub pagetitle ($;$) {
1083 my $unescaped=shift;
1086 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1089 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1097 # support use w/o %config set
1098 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1099 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1105 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1106 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1113 my $cgiurl=$local_cgiurl;
1115 if (exists $params{cgiurl}) {
1116 $cgiurl=$params{cgiurl};
1117 delete $params{cgiurl};
1125 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1128 sub cgiurl_abs (@) {
1130 URI->new_abs(cgiurl(@_), $config{cgiurl});
1136 return $local_url if ! defined $page;
1138 $page=htmlpage($page);
1140 $page=~s/[^\/]+\//..\//g;
1148 return $url unless defined $urlbase && length $urlbase;
1151 URI->new_abs($url, $urlbase)->as_string;
1155 # Work around very innefficient behavior in File::Spec if abs2rel
1156 # is passed two relative paths. It's much faster if paths are
1157 # absolute! (Debian bug #376658; fixed in debian unstable now)
1162 my $ret=File::Spec->abs2rel($path, $base);
1163 $ret=~s/^// if defined $ret;
1167 sub displaytime ($;$$) {
1168 # Plugins can override this function to mark up the time to
1170 my $time=formattime($_[0], $_[1]);
1171 if ($config{html5}) {
1172 return '<time datetime="'.date_3339($_[0]).'"'.
1173 ($_[2] ? ' pubdate="pubdate"' : '').
1174 '>'.$time.'</time>';
1177 return '<span class="date">'.$time.'</span>';
1181 sub formattime ($;$) {
1182 # Plugins can override this function to format the time.
1185 if (! defined $format) {
1186 $format=$config{timeformat};
1189 return strftime_utf8($format, localtime($time));
1192 my $strftime_encoding;
1194 # strftime doesn't know about encodings, so make sure
1195 # its output is properly treated as utf8.
1196 # Note that this does not handle utf-8 in the format string.
1197 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1198 unless defined $strftime_encoding;
1200 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1201 : POSIX::strftime(@_);
1207 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1208 POSIX::setlocale(&POSIX::LC_TIME, "C");
1209 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1210 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1214 sub beautify_urlpath ($) {
1217 # Ensure url is not an empty link, and if necessary,
1218 # add ./ to avoid colon confusion.
1219 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1223 if ($config{usedirs}) {
1224 $url =~ s!/index.$config{htmlext}$!/!;
1239 if (! $destsources{$to}) {
1244 return $config{url}.beautify_urlpath("/".$to);
1247 if (! defined $from) {
1248 my $u = $local_url || '';
1250 return $u.beautify_urlpath("/".$to);
1253 my $link = abs2rel($to, dirname(htmlpage($from)));
1255 return beautify_urlpath($link);
1258 sub isselflink ($$) {
1259 # Plugins can override this function to support special types
1264 return $page eq $link;
1267 sub htmllink ($$$;@) {
1268 my $lpage=shift; # the page doing the linking
1269 my $page=shift; # the page that will contain the link (different for inline)
1276 if (! $opts{forcesubpage}) {
1277 $bestlink=bestlink($lpage, $link);
1280 $bestlink="$lpage/".lc($link);
1284 if (defined $opts{linktext}) {
1285 $linktext=$opts{linktext};
1288 $linktext=pagetitle(basename($link));
1291 return "<span class=\"selflink\">$linktext</span>"
1292 if length $bestlink && isselflink($page, $bestlink) &&
1293 ! defined $opts{anchor};
1295 if (! $destsources{$bestlink}) {
1296 $bestlink=htmlpage($bestlink);
1298 if (! $destsources{$bestlink}) {
1300 if (length $config{cgiurl}) {
1301 $cgilink = "<a href=\"".
1306 )."\" rel=\"nofollow\">?</a>";
1308 return "<span class=\"createlink\">$cgilink$linktext</span>"
1312 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1313 $bestlink=beautify_urlpath($bestlink);
1315 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1316 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1319 if (defined $opts{anchor}) {
1320 $bestlink.="#".$opts{anchor};
1324 foreach my $attr (qw{rel class title}) {
1325 if (defined $opts{$attr}) {
1326 push @attrs, " $attr=\"$opts{$attr}\"";
1330 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1335 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1338 sub openiduser ($) {
1341 if (defined $user && $user =~ m!^https?://! &&
1342 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1345 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1346 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1349 # backcompat with old version
1350 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1351 $display=$oid->display;
1354 # Convert "user.somehost.com" to "user [somehost.com]"
1355 # (also "user.somehost.co.uk")
1356 if ($display !~ /\[/) {
1357 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1359 # Convert "http://somehost.com/user" to "user [somehost.com]".
1360 # (also "https://somehost.com/user/")
1361 if ($display !~ /\[/) {
1362 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1364 $display=~s!^https?://!!; # make sure this is removed
1365 eval q{use CGI 'escapeHTML'};
1367 return escapeHTML($display);
1372 sub htmlize ($$$$) {
1378 my $oneline = $content !~ /\n/;
1380 if (exists $hooks{htmlize}{$type}) {
1381 $content=$hooks{htmlize}{$type}{call}->(
1383 content => $content,
1387 error("htmlization of $type not supported");
1390 run_hooks(sanitize => sub {
1393 destpage => $destpage,
1394 content => $content,
1399 # hack to get rid of enclosing junk added by markdown
1400 # and other htmlizers/sanitizers
1401 $content=~s/^<p>//i;
1402 $content=~s/<\/p>\n*$//i;
1413 run_hooks(linkify => sub {
1416 destpage => $destpage,
1417 content => $content,
1425 our $preprocess_preview=0;
1426 sub preprocess ($$$;$$) {
1427 my $page=shift; # the page the data comes from
1428 my $destpage=shift; # the page the data will appear in (different for inline)
1433 # Using local because it needs to be set within any nested calls
1435 local $preprocess_preview=$preview if defined $preview;
1442 $params="" if ! defined $params;
1444 if (length $escape) {
1445 return "[[$prefix$command $params]]";
1447 elsif (exists $hooks{preprocess}{$command}) {
1448 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1449 # Note: preserve order of params, some plugins may
1450 # consider it significant.
1452 while ($params =~ m{
1453 (?:([-.\w]+)=)? # 1: named parameter key?
1455 """(.*?)""" # 2: triple-quoted value
1457 "([^"]*?)" # 3: single-quoted value
1459 '''(.*?)''' # 4: triple-single-quote
1461 <<([a-zA-Z]+)\n # 5: heredoc start
1462 (.*?)\n\5 # 6: heredoc value
1464 (\S+) # 7: unquoted value
1466 (?:\s+|$) # delimiter to next param
1476 elsif (defined $3) {
1479 elsif (defined $4) {
1482 elsif (defined $7) {
1485 elsif (defined $6) {
1490 push @params, $key, $val;
1493 push @params, $val, '';
1496 if ($preprocessing{$page}++ > 3) {
1497 # Avoid loops of preprocessed pages preprocessing
1498 # other pages that preprocess them, etc.
1499 return "[[!$command <span class=\"error\">".
1500 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1501 $page, $preprocessing{$page}).
1507 $hooks{preprocess}{$command}{call}->(
1510 destpage => $destpage,
1511 preview => $preprocess_preview,
1517 $ret="[[!$command <span class=\"error\">".
1518 gettext("Error").": $error"."</span>]]";
1522 # use void context during scan pass
1524 $hooks{preprocess}{$command}{call}->(
1527 destpage => $destpage,
1528 preview => $preprocess_preview,
1533 $preprocessing{$page}--;
1537 return "[[$prefix$command $params]]";
1542 if ($config{prefix_directives}) {
1545 \[\[(!) # directive open; 2: prefix
1546 ([-\w]+) # 3: command
1547 ( # 4: the parameters..
1548 \s+ # Must have space if parameters present
1550 (?:[-.\w]+=)? # named parameter key?
1552 """.*?""" # triple-quoted value
1554 "[^"]*?" # single-quoted value
1556 '''.*?''' # triple-single-quote
1558 <<([a-zA-Z]+)\n # 5: heredoc start
1559 (?:.*?)\n\5 # heredoc value
1561 [^"\s\]]+ # unquoted value
1563 \s* # whitespace or end
1566 *)? # 0 or more parameters
1567 \]\] # directive closed
1573 \[\[(!?) # directive open; 2: optional prefix
1574 ([-\w]+) # 3: command
1576 ( # 4: the parameters..
1578 (?:[-.\w]+=)? # named parameter key?
1580 """.*?""" # triple-quoted value
1582 "[^"]*?" # single-quoted value
1584 '''.*?''' # triple-single-quote
1586 <<([a-zA-Z]+)\n # 5: heredoc start
1587 (?:.*?)\n\5 # heredoc value
1589 [^"\s\]]+ # unquoted value
1591 \s* # whitespace or end
1594 *) # 0 or more parameters
1595 \]\] # directive closed
1599 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1608 run_hooks(filter => sub {
1609 $content=shift->(page => $page, destpage => $destpage,
1610 content => $content);
1616 sub check_canedit ($$$;$) {
1623 run_hooks(canedit => sub {
1624 return if defined $canedit;
1625 my $ret=shift->($page, $q, $session);
1630 elsif (ref $ret eq 'CODE') {
1631 $ret->() unless $nonfatal;
1634 elsif (defined $ret) {
1635 error($ret) unless $nonfatal;
1640 return defined $canedit ? $canedit : 1;
1643 sub check_content (@) {
1646 return 1 if ! exists $hooks{checkcontent}; # optimisation
1648 if (exists $pagesources{$params{page}}) {
1650 my %old=map { $_ => 1 }
1651 split("\n", readfile(srcfile($pagesources{$params{page}})));
1652 foreach my $line (split("\n", $params{content})) {
1653 push @diff, $line if ! exists $old{$line};
1655 $params{diff}=join("\n", @diff);
1659 run_hooks(checkcontent => sub {
1660 return if defined $ok;
1661 my $ret=shift->(%params);
1666 elsif (ref $ret eq 'CODE') {
1667 $ret->() unless $params{nonfatal};
1670 elsif (defined $ret) {
1671 error($ret) unless $params{nonfatal};
1677 return defined $ok ? $ok : 1;
1680 sub check_canchange (@) {
1682 my $cgi = $params{cgi};
1683 my $session = $params{session};
1684 my @changes = @{$params{changes}};
1687 foreach my $change (@changes) {
1688 # This untaint is safe because we check file_pruned and
1690 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1691 $file=possibly_foolish_untaint($file);
1692 if (! defined $file || ! length $file ||
1693 file_pruned($file)) {
1694 error(gettext("bad file name %s"), $file);
1697 my $type=pagetype($file);
1698 my $page=pagename($file) if defined $type;
1700 if ($change->{action} eq 'add') {
1704 if ($change->{action} eq 'change' ||
1705 $change->{action} eq 'add') {
1706 if (defined $page) {
1707 check_canedit($page, $cgi, $session);
1711 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1712 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1713 check_canedit($file, $cgi, $session);
1718 elsif ($change->{action} eq 'remove') {
1719 # check_canremove tests to see if the file is present
1720 # on disk. This will fail when a single commit adds a
1721 # file and then removes it again. Avoid the problem
1722 # by not testing the removal in such pairs of changes.
1723 # (The add is still tested, just to make sure that
1724 # no data is added to the repo that a web edit
1726 next if $newfiles{$file};
1728 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1729 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1730 check_canedit(defined $page ? $page : $file, $cgi, $session);
1735 error "unknown action ".$change->{action};
1738 error sprintf(gettext("you are not allowed to change %s"), $file);
1746 # Take an exclusive lock on the wiki to prevent multiple concurrent
1747 # run issues. The lock will be dropped on program exit.
1748 if (! -d $config{wikistatedir}) {
1749 mkdir($config{wikistatedir});
1751 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1752 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1753 if (! flock($wikilock, 2)) { # LOCK_EX
1754 error("failed to get lock");
1760 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1761 return close($wikilock) if $wikilock;
1767 sub commit_hook_enabled () {
1768 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1769 error("cannot write to $config{wikistatedir}/commitlock: $!");
1770 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1771 close($commitlock) || error("failed closing commitlock: $!");
1774 close($commitlock) || error("failed closing commitlock: $!");
1778 sub disable_commit_hook () {
1779 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1780 error("cannot write to $config{wikistatedir}/commitlock: $!");
1781 if (! flock($commitlock, 2)) { # LOCK_EX
1782 error("failed to get commit lock");
1787 sub enable_commit_hook () {
1788 return close($commitlock) if $commitlock;
1793 %oldrenderedfiles=%pagectime=();
1794 if (! $config{rebuild}) {
1795 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1796 %destsources=%renderedfiles=%pagecase=%pagestate=
1797 %depends_simple=%typedlinks=%oldtypedlinks=();
1800 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1801 if (-e "$config{wikistatedir}/index") {
1802 system("ikiwiki-transition", "indexdb", $config{srcdir});
1803 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1806 $config{gettime}=1; # first build
1811 my $index=Storable::fd_retrieve($in);
1812 if (! defined $index) {
1817 if (exists $index->{version} && ! ref $index->{version}) {
1818 $pages=$index->{page};
1819 %wikistate=%{$index->{state}};
1820 # Handle plugins that got disabled by loading a new setup.
1821 if (exists $config{setupfile}) {
1822 require IkiWiki::Setup;
1823 IkiWiki::Setup::disabled_plugins(
1824 grep { ! $loaded_plugins{$_} } keys %wikistate);
1832 foreach my $src (keys %$pages) {
1833 my $d=$pages->{$src};
1834 my $page=pagename($src);
1835 $pagectime{$page}=$d->{ctime};
1836 $pagesources{$page}=$src;
1837 if (! $config{rebuild}) {
1838 $pagemtime{$page}=$d->{mtime};
1839 $renderedfiles{$page}=$d->{dest};
1840 if (exists $d->{links} && ref $d->{links}) {
1841 $links{$page}=$d->{links};
1842 $oldlinks{$page}=[@{$d->{links}}];
1844 if (ref $d->{depends_simple} eq 'ARRAY') {
1846 $depends_simple{$page}={
1847 map { $_ => 1 } @{$d->{depends_simple}}
1850 elsif (exists $d->{depends_simple}) {
1851 $depends_simple{$page}=$d->{depends_simple};
1853 if (exists $d->{dependslist}) {
1856 map { $_ => $DEPEND_CONTENT }
1857 @{$d->{dependslist}}
1860 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1862 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1864 elsif (exists $d->{depends}) {
1865 $depends{$page}=$d->{depends};
1867 if (exists $d->{state}) {
1868 $pagestate{$page}=$d->{state};
1870 if (exists $d->{typedlinks}) {
1871 $typedlinks{$page}=$d->{typedlinks};
1873 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1874 next unless %$links;
1875 $oldtypedlinks{$page}{$type} = {%$links};
1879 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1881 foreach my $page (keys %pagesources) {
1882 $pagecase{lc $page}=$page;
1884 foreach my $page (keys %renderedfiles) {
1885 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1891 run_hooks(savestate => sub { shift->() });
1893 my @plugins=keys %loaded_plugins;
1895 if (! -d $config{wikistatedir}) {
1896 mkdir($config{wikistatedir});
1898 my $newfile="$config{wikistatedir}/indexdb.new";
1899 my $cleanup = sub { unlink($newfile) };
1900 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1903 foreach my $page (keys %pagemtime) {
1904 next unless $pagemtime{$page};
1905 my $src=$pagesources{$page};
1907 $index{page}{$src}={
1908 ctime => $pagectime{$page},
1909 mtime => $pagemtime{$page},
1910 dest => $renderedfiles{$page},
1911 links => $links{$page},
1914 if (exists $depends{$page}) {
1915 $index{page}{$src}{depends} = $depends{$page};
1918 if (exists $depends_simple{$page}) {
1919 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1922 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1923 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1926 if (exists $pagestate{$page}) {
1927 foreach my $id (@plugins) {
1928 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1929 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1936 foreach my $id (@plugins) {
1937 $index{state}{$id}={}; # used to detect disabled plugins
1938 foreach my $key (keys %{$wikistate{$id}}) {
1939 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1943 $index{version}="3";
1944 my $ret=Storable::nstore_fd(\%index, $out);
1945 return if ! defined $ret || ! $ret;
1946 close $out || error("failed saving to $newfile: $!", $cleanup);
1947 rename($newfile, "$config{wikistatedir}/indexdb") ||
1948 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1953 sub template_file ($) {
1956 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1958 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1959 $template=srcfile($pagesources{$tpage}, 1);
1963 $template=srcfile($tpage, 1);
1966 if (defined $template) {
1967 return $template, $tpage, 1 if wantarray;
1971 $name=~s:/::; # avoid path traversal
1972 foreach my $dir ($config{templatedir},
1973 "$installdir/share/ikiwiki/templates") {
1974 if (-e "$dir/$name") {
1975 $template="$dir/$name";
1979 if (defined $template) {
1980 return $template, $tpage if wantarray;
1988 sub template_depends ($$;@) {
1992 my ($filename, $tpage, $untrusted)=template_file($name);
1993 if (! defined $filename) {
1994 error(sprintf(gettext("template %s not found"), $name))
1997 if (defined $page && defined $tpage) {
1998 add_depends($page, $tpage);
2003 my $text_ref = shift;
2004 ${$text_ref} = decode_utf8(${$text_ref});
2006 loop_context_vars => 1,
2007 die_on_bad_params => 0,
2008 parent_global_vars => 1,
2009 filename => $filename,
2011 ($untrusted ? (no_includes => 1) : ()),
2013 return @opts if wantarray;
2015 require HTML::Template;
2016 return HTML::Template->new(@opts);
2019 sub template ($;@) {
2020 template_depends(shift, undef, @_);
2023 sub templateactions ($$) {
2029 run_hooks(pageactions => sub {
2030 push @actions, map { { action => $_ } }
2031 grep { defined } shift->(page => $page);
2033 $template->param(actions => \@actions);
2035 if ($config{cgiurl} && exists $hooks{auth}) {
2036 $template->param(prefsurl => cgiurl(do => "prefs"));
2040 if ($have_actions || @actions) {
2041 $template->param(have_actions => 1);
2048 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2049 error 'hook requires type, call, and id parameters';
2052 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2054 $hooks{$param{type}}{$param{id}}=\%param;
2058 sub run_hooks ($$) {
2059 # Calls the given sub for each hook of the given type,
2060 # passing it the hook function to call.
2064 if (exists $hooks{$type}) {
2065 my (@first, @middle, @last);
2066 foreach my $id (keys %{$hooks{$type}}) {
2067 if ($hooks{$type}{$id}{first}) {
2070 elsif ($hooks{$type}{$id}{last}) {
2077 foreach my $id (@first, @middle, @last) {
2078 $sub->($hooks{$type}{$id}{call});
2086 $hooks{rcs}{rcs_update}{call}->(@_);
2089 sub rcs_prepedit ($) {
2090 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2093 sub rcs_commit (@) {
2094 $hooks{rcs}{rcs_commit}{call}->(@_);
2097 sub rcs_commit_staged (@) {
2098 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2102 $hooks{rcs}{rcs_add}{call}->(@_);
2105 sub rcs_remove ($) {
2106 $hooks{rcs}{rcs_remove}{call}->(@_);
2109 sub rcs_rename ($$) {
2110 $hooks{rcs}{rcs_rename}{call}->(@_);
2113 sub rcs_recentchanges ($) {
2114 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2117 sub rcs_diff ($;$) {
2118 $hooks{rcs}{rcs_diff}{call}->(@_);
2121 sub rcs_getctime ($) {
2122 $hooks{rcs}{rcs_getctime}{call}->(@_);
2125 sub rcs_getmtime ($) {
2126 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2129 sub rcs_receive () {
2130 $hooks{rcs}{rcs_receive}{call}->();
2133 sub add_depends ($$;$) {
2136 my $deptype=shift || $DEPEND_CONTENT;
2138 # Is the pagespec a simple page name?
2139 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2140 $pagespec !~ /[\s*?()!]/) {
2141 $depends_simple{$page}{lc $pagespec} |= $deptype;
2145 # Add explicit dependencies for influences.
2146 my $sub=pagespec_translate($pagespec);
2147 return unless defined $sub;
2148 foreach my $p (keys %pagesources) {
2149 my $r=$sub->($p, location => $page);
2150 my $i=$r->influences;
2151 my $static=$r->influences_static;
2152 foreach my $k (keys %$i) {
2153 next unless $r || $static || $k eq $page;
2154 $depends_simple{$page}{lc $k} |= $i->{$k};
2159 $depends{$page}{$pagespec} |= $deptype;
2165 foreach my $type (@_) {
2166 if ($type eq 'presence') {
2167 $deptype |= $DEPEND_PRESENCE;
2169 elsif ($type eq 'links') {
2170 $deptype |= $DEPEND_LINKS;
2172 elsif ($type eq 'content') {
2173 $deptype |= $DEPEND_CONTENT;
2179 my $file_prune_regexp;
2180 sub file_pruned ($) {
2183 if (defined $config{include} && length $config{include}) {
2184 return 0 if $file =~ m/$config{include}/;
2187 if (! defined $file_prune_regexp) {
2188 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2189 $file_prune_regexp=qr/$file_prune_regexp/;
2191 return $file =~ m/$file_prune_regexp/;
2194 sub define_gettext () {
2195 # If translation is needed, redefine the gettext function to do it.
2196 # Otherwise, it becomes a quick no-op.
2199 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2200 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2201 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2203 $gettext_obj=eval q{
2204 use Locale::gettext q{textdomain};
2205 Locale::gettext->domain('ikiwiki')
2210 no warnings 'redefine';
2212 $getobj->() if $getobj;
2214 $gettext_obj->get(shift);
2221 $getobj->() if $getobj;
2223 $gettext_obj->nget(@_);
2226 return ($_[2] == 1 ? $_[0] : $_[1])
2244 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2248 # Injects a new function into the symbol table to replace an
2249 # exported function.
2252 # This is deep ugly perl foo, beware.
2255 if (! defined $params{parent}) {
2256 $params{parent}='::';
2257 $params{old}=\&{$params{name}};
2258 $params{name}=~s/.*:://;
2260 my $parent=$params{parent};
2261 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2262 $ns = $params{parent} . $ns;
2263 inject(%params, parent => $ns) unless $ns eq '::main::';
2264 *{$ns . $params{name}} = $params{call}
2265 if exists ${$ns}{$params{name}} &&
2266 \&{${$ns}{$params{name}}} == $params{old};
2272 sub add_link ($$;$) {
2277 push @{$links{$page}}, $link
2278 unless grep { $_ eq $link } @{$links{$page}};
2280 if (defined $type) {
2281 $typedlinks{$page}{$type}{$link} = 1;
2285 sub add_autofile ($$$) {
2288 my $generator=shift;
2290 $autofiles{$file}{plugin}=$plugin;
2291 $autofiles{$file}{generator}=$generator;
2295 return LWP::UserAgent->new(
2296 cookie_jar => $config{cookiejar},
2297 env_proxy => 1, # respect proxy env vars
2301 sub sortspec_translate ($$) {
2303 my $reverse = shift;
2309 (-?) # group 1: perhaps negated
2312 \w+\([^\)]*\) # command(params)
2314 [^\s]+ # or anything else
2322 if ($word =~ m/^(\w+)\((.*)\)$/) {
2323 # command with parameters
2327 elsif ($word !~ m/^\w+$/) {
2328 error(sprintf(gettext("invalid sort type %s"), $word));
2339 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2340 if (defined $params) {
2341 push @data, $params;
2342 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2345 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2349 error(sprintf(gettext("unknown sort type %s"), $word));
2353 if (! length $code) {
2354 # undefined sorting method... sort arbitrarily
2363 return eval 'sub { '.$code.' }';
2366 sub pagespec_translate ($) {
2369 # Convert spec to perl code.
2373 \s* # ignore whitespace
2374 ( # 1: match a single word
2381 \w+\([^\)]*\) # command(params)
2383 [^\s()]+ # any other text
2385 \s* # ignore whitespace
2388 if (lc $word eq 'and') {
2391 elsif (lc $word eq 'or') {
2394 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2397 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2398 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2400 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2403 push @data, qq{unknown function in pagespec "$word"};
2404 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2409 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2413 if (! length $code) {
2414 $code="IkiWiki::FailReason->new('empty pagespec')";
2418 return eval 'sub { my $page=shift; '.$code.' }';
2421 sub pagespec_match ($$;@) {
2426 # Backwards compatability with old calling convention.
2428 unshift @params, 'location';
2431 my $sub=pagespec_translate($spec);
2432 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2434 return $sub->($page, @params);
2437 sub pagespec_match_list ($$;@) {
2442 # Backwards compatability with old calling convention.
2444 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2445 $params{list}=$page;
2446 $page=$params{location}; # ugh!
2449 my $sub=pagespec_translate($pagespec);
2450 error "syntax error in pagespec \"$pagespec\""
2452 my $sort=sortspec_translate($params{sort}, $params{reverse})
2453 if defined $params{sort};
2456 if (exists $params{list}) {
2457 @candidates=exists $params{filter}
2458 ? grep { ! $params{filter}->($_) } @{$params{list}}
2462 @candidates=exists $params{filter}
2463 ? grep { ! $params{filter}->($_) } keys %pagesources
2464 : keys %pagesources;
2467 # clear params, remainder is passed to pagespec
2468 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2469 my $num=$params{num};
2470 delete @params{qw{num deptype reverse sort filter list}};
2472 # when only the top matches will be returned, it's efficient to
2473 # sort before matching to pagespec,
2474 if (defined $num && defined $sort) {
2475 @candidates=IkiWiki::SortSpec::sort_pages(
2476 $sort, @candidates);
2482 my $accum=IkiWiki::SuccessReason->new();
2483 foreach my $p (@candidates) {
2484 my $r=$sub->($p, %params, location => $page);
2485 error(sprintf(gettext("cannot match pages: %s"), $r))
2486 if $r->isa("IkiWiki::ErrorReason");
2487 unless ($r || $r->influences_static) {
2488 $r->remove_influence($p);
2493 last if defined $num && ++$count == $num;
2497 # Add simple dependencies for accumulated influences.
2498 my $i=$accum->influences;
2499 foreach my $k (keys %$i) {
2500 $depends_simple{$page}{lc $k} |= $i->{$k};
2503 # when all matches will be returned, it's efficient to
2504 # sort after matching
2505 if (! defined $num && defined $sort) {
2506 return IkiWiki::SortSpec::sort_pages(
2514 sub pagespec_valid ($) {
2517 return defined pagespec_translate($spec);
2521 my $re=quotemeta(shift);
2527 package IkiWiki::FailReason;
2530 '""' => sub { $_[0][0] },
2532 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2533 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2534 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2538 our @ISA = 'IkiWiki::SuccessReason';
2540 package IkiWiki::SuccessReason;
2543 '""' => sub { $_[0][0] },
2545 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2546 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2547 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2554 return bless [$value, {@_}], $class;
2559 $this->[1]={@_} if @_;
2560 my %i=%{$this->[1]};
2565 sub influences_static {
2566 return ! $_[0][1]->{""};
2569 sub merge_influences {
2574 if (! $anded || (($this || %{$this->[1]}) &&
2575 ($other || %{$other->[1]}))) {
2576 foreach my $influence (keys %{$other->[1]}) {
2577 $this->[1]{$influence} |= $other->[1]{$influence};
2586 sub remove_influence {
2590 delete $this->[1]{$torm};
2593 package IkiWiki::ErrorReason;
2595 our @ISA = 'IkiWiki::FailReason';
2597 package IkiWiki::PageSpec;
2603 if ($path =~ m!^\.(/|$)!) {
2605 $from=~s#/?[^/]+$## if defined $from;
2607 $path="$from/$path" if defined $from && length $from;
2611 $path = "" unless defined $path;
2620 sub match_glob ($$;@) {
2625 $glob=derel($glob, $params{location});
2627 # Instead of converting the glob to a regex every time,
2628 # cache the compiled regex to save time.
2629 my $re=$glob_cache{$glob};
2630 unless (defined $re) {
2631 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2634 if (! IkiWiki::isinternal($page) || $params{internal}) {
2635 return IkiWiki::SuccessReason->new("$glob matches $page");
2638 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2642 return IkiWiki::FailReason->new("$glob does not match $page");
2646 sub match_internal ($$;@) {
2647 return match_glob(shift, shift, @_, internal => 1)
2650 sub match_page ($$;@) {
2652 my $match=match_glob($page, shift, @_);
2654 my $source=exists $IkiWiki::pagesources{$page} ?
2655 $IkiWiki::pagesources{$page} :
2656 $IkiWiki::delpagesources{$page};
2657 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2658 if (! defined $type) {
2659 return IkiWiki::FailReason->new("$page is not a page");
2665 sub match_link ($$;@) {
2670 $link=derel($link, $params{location});
2671 my $from=exists $params{location} ? $params{location} : '';
2672 my $linktype=$params{linktype};
2674 if (defined $linktype) {
2675 $qualifier=" with type $linktype";
2678 my $links = $IkiWiki::links{$page};
2679 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2680 unless $links && @{$links};
2681 my $bestlink = IkiWiki::bestlink($from, $link);
2682 foreach my $p (@{$links}) {
2683 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2685 if (length $bestlink) {
2686 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2687 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2691 if (match_glob($p, $link, %params)) {
2692 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2694 my ($p_rel)=$p=~/^\/?(.*)/;
2696 if (match_glob($p_rel, $link, %params)) {
2697 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2701 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2704 sub match_backlink ($$;@) {
2708 if ($testpage eq '.') {
2709 $testpage = $params{'location'}
2711 my $ret=match_link($testpage, $page, @_);
2712 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2716 sub match_created_before ($$;@) {
2721 $testpage=derel($testpage, $params{location});
2723 if (exists $IkiWiki::pagectime{$testpage}) {
2724 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2725 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2728 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2732 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2736 sub match_created_after ($$;@) {
2741 $testpage=derel($testpage, $params{location});
2743 if (exists $IkiWiki::pagectime{$testpage}) {
2744 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2745 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2748 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2752 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2756 sub match_creation_day ($$;@) {
2759 if ($d !~ /^\d+$/) {
2760 return IkiWiki::ErrorReason->new("invalid day $d");
2762 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2763 return IkiWiki::SuccessReason->new('creation_day matched');
2766 return IkiWiki::FailReason->new('creation_day did not match');
2770 sub match_creation_month ($$;@) {
2773 if ($m !~ /^\d+$/) {
2774 return IkiWiki::ErrorReason->new("invalid month $m");
2776 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2777 return IkiWiki::SuccessReason->new('creation_month matched');
2780 return IkiWiki::FailReason->new('creation_month did not match');
2784 sub match_creation_year ($$;@) {
2787 if ($y !~ /^\d+$/) {
2788 return IkiWiki::ErrorReason->new("invalid year $y");
2790 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2791 return IkiWiki::SuccessReason->new('creation_year matched');
2794 return IkiWiki::FailReason->new('creation_year did not match');
2798 sub match_user ($$;@) {
2803 if (! exists $params{user}) {
2804 return IkiWiki::ErrorReason->new("no user specified");
2807 my $regexp=IkiWiki::glob2re($user);
2809 if (defined $params{user} && $params{user}=~$regexp) {
2810 return IkiWiki::SuccessReason->new("user is $user");
2812 elsif (! defined $params{user}) {
2813 return IkiWiki::FailReason->new("not logged in");
2816 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2820 sub match_admin ($$;@) {
2825 if (! exists $params{user}) {
2826 return IkiWiki::ErrorReason->new("no user specified");
2829 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2830 return IkiWiki::SuccessReason->new("user is an admin");
2832 elsif (! defined $params{user}) {
2833 return IkiWiki::FailReason->new("not logged in");
2836 return IkiWiki::FailReason->new("user is not an admin");
2840 sub match_ip ($$;@) {
2845 if (! exists $params{ip}) {
2846 return IkiWiki::ErrorReason->new("no IP specified");
2849 my $regexp=IkiWiki::glob2re(lc $ip);
2851 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2852 return IkiWiki::SuccessReason->new("IP is $ip");
2855 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2859 package IkiWiki::SortSpec;
2861 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2862 # are easily available in this namespace, for cmp functions to use them.
2869 IkiWiki::pagetitle(IkiWiki::basename($a))
2871 IkiWiki::pagetitle(IkiWiki::basename($b))
2874 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2875 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2876 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }