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 => @_);
731 sub log_message ($$) {
734 if ($config{syslog}) {
737 Sys::Syslog::setlogsock('unix');
738 Sys::Syslog::openlog('ikiwiki', '', 'user');
742 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
745 elsif (! $config{cgi}) {
749 return print STDERR "@_\n";
753 sub possibly_foolish_untaint ($) {
755 my ($untainted)=$tainted=~/(.*)/s;
775 return exists $pagesources{$page} &&
776 $pagesources{$page} =~ /\._([^.]+)$/;
782 if ($file =~ /\.([^.]+)$/) {
783 return $1 if exists $hooks{htmlize}{$1};
785 my $base=basename($file);
786 if (exists $hooks{htmlize}{$base} &&
787 $hooks{htmlize}{$base}{noextension}) {
798 if (exists $pagename_cache{$file}) {
799 return $pagename_cache{$file};
802 my $type=pagetype($file);
804 $page=~s/\Q.$type\E*$//
805 if defined $type && !$hooks{htmlize}{$type}{keepextension}
806 && !$hooks{htmlize}{$type}{noextension};
807 if ($config{indexpages} && $page=~/(.*)\/index$/) {
811 $pagename_cache{$file} = $page;
815 sub newpagefile ($$) {
819 if (! $config{indexpages} || $page eq 'index') {
820 return $page.".".$type;
823 return $page."/index.".$type;
827 sub targetpage ($$;$) {
832 if (defined $filename) {
833 return $page."/".$filename.".".$ext;
835 elsif (! $config{usedirs} || $page eq 'index') {
836 return $page.".".$ext;
839 return $page."/index.".$ext;
846 return targetpage($page, $config{htmlext});
853 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
854 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
855 return "$dir/$file", stat(_) if -e "$dir/$file";
857 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
862 return (srcfile_stat(@_))[0];
865 sub add_literal_underlay ($) {
868 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
869 unshift @{$config{underlaydirs}}, $dir;
873 sub add_underlay ($) {
877 $dir="$config{underlaydirbase}/$dir";
880 add_literal_underlay($dir);
881 # why does it return 1? we just don't know
885 sub readfile ($;$$) {
891 error("cannot read a symlink ($file)");
895 open (my $in, "<", $file) || error("failed to read $file: $!");
896 binmode($in) if ($binary);
897 return \*$in if $wantfd;
899 # check for invalid utf-8, and toss it back to avoid crashes
900 if (! utf8::valid($ret)) {
901 $ret=encode_utf8($ret);
903 close $in || error("failed to read $file: $!");
907 sub prep_writefile ($$) {
912 while (length $test) {
913 if (-l "$destdir/$test") {
914 error("cannot write to a symlink ($test)");
916 if (-f _ && $test ne $file) {
917 # Remove conflicting file.
918 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
919 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
921 unlink("$destdir/$test");
927 $test=dirname($test);
930 my $dir=dirname("$destdir/$file");
933 foreach my $s (split(m!/+!, $dir)) {
936 mkdir($d) || error("failed to create directory $d: $!");
944 sub writefile ($$$;$$) {
945 my $file=shift; # can include subdirs
946 my $destdir=shift; # directory to put file in
951 prep_writefile($file, $destdir);
953 my $newfile="$destdir/$file.ikiwiki-new";
955 error("cannot write to a symlink ($newfile)");
958 my $cleanup = sub { unlink($newfile) };
959 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
960 binmode($out) if ($binary);
962 $writer->(\*$out, $cleanup);
965 print $out $content or error("failed writing to $newfile: $!", $cleanup);
967 close $out || error("failed saving $newfile: $!", $cleanup);
968 rename($newfile, "$destdir/$file") ||
969 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
975 sub will_render ($$;$) {
980 # Important security check for independently created files.
981 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
982 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
983 my $from_other_page=0;
984 # Expensive, but rarely runs.
985 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
989 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
995 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
996 unless $from_other_page;
999 # If $dest exists as a directory, remove conflicting files in it
1000 # rendered from other pages.
1002 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1003 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1004 if (dirname($f) eq $dest) {
1005 unlink("$config{destdir}/$f");
1006 rmdir(dirname("$config{destdir}/$f"));
1012 if (! $clear || $cleared{$page}) {
1013 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1016 foreach my $old (@{$renderedfiles{$page}}) {
1017 delete $destsources{$old};
1019 $renderedfiles{$page}=[$dest];
1022 $destsources{$dest}=$page;
1032 if ($link=~s/^\/+//) {
1040 $l.="/" if length $l;
1043 if (exists $pagesources{$l}) {
1046 elsif (exists $pagecase{lc $l}) {
1047 return $pagecase{lc $l};
1049 } while $cwd=~s{/?[^/]+$}{};
1051 if (length $config{userdir}) {
1052 my $l = "$config{userdir}/".lc($link);
1053 if (exists $pagesources{$l}) {
1056 elsif (exists $pagecase{lc $l}) {
1057 return $pagecase{lc $l};
1061 #print STDERR "warning: page $page, broken link: $link\n";
1065 sub isinlinableimage ($) {
1068 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1071 sub pagetitle ($;$) {
1073 my $unescaped=shift;
1076 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1079 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1087 # support use w/o %config set
1088 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1089 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1095 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1096 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1103 my $cgiurl=$local_cgiurl;
1105 if (exists $params{cgiurl}) {
1106 $cgiurl=$params{cgiurl};
1107 delete $params{cgiurl};
1115 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1118 sub cgiurl_abs (@) {
1120 URI->new_abs(cgiurl(@_), $config{cgiurl});
1126 return $local_url if ! defined $page;
1128 $page=htmlpage($page);
1130 $page=~s/[^\/]+\//..\//g;
1138 return $url unless defined $urlbase && length $urlbase;
1141 URI->new_abs($url, $urlbase)->as_string;
1145 # Work around very innefficient behavior in File::Spec if abs2rel
1146 # is passed two relative paths. It's much faster if paths are
1147 # absolute! (Debian bug #376658; fixed in debian unstable now)
1152 my $ret=File::Spec->abs2rel($path, $base);
1153 $ret=~s/^// if defined $ret;
1157 sub displaytime ($;$$) {
1158 # Plugins can override this function to mark up the time to
1160 my $time=formattime($_[0], $_[1]);
1161 if ($config{html5}) {
1162 return '<time datetime="'.date_3339($_[0]).'"'.
1163 ($_[2] ? ' pubdate="pubdate"' : '').
1164 '>'.$time.'</time>';
1167 return '<span class="date">'.$time.'</span>';
1171 sub formattime ($;$) {
1172 # Plugins can override this function to format the time.
1175 if (! defined $format) {
1176 $format=$config{timeformat};
1179 return strftime_utf8($format, localtime($time));
1182 my $strftime_encoding;
1184 # strftime doesn't know about encodings, so make sure
1185 # its output is properly treated as utf8.
1186 # Note that this does not handle utf-8 in the format string.
1187 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1188 unless defined $strftime_encoding;
1190 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1191 : POSIX::strftime(@_);
1197 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1198 POSIX::setlocale(&POSIX::LC_TIME, "C");
1199 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1200 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1204 sub beautify_urlpath ($) {
1207 # Ensure url is not an empty link, and if necessary,
1208 # add ./ to avoid colon confusion.
1209 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1213 if ($config{usedirs}) {
1214 $url =~ s!/index.$config{htmlext}$!/!;
1229 if (! $destsources{$to}) {
1234 return $config{url}.beautify_urlpath("/".$to);
1237 if (! defined $from) {
1238 my $u = $local_url || '';
1240 return $u.beautify_urlpath("/".$to);
1243 my $link = abs2rel($to, dirname(htmlpage($from)));
1245 return beautify_urlpath($link);
1248 sub isselflink ($$) {
1249 # Plugins can override this function to support special types
1254 return $page eq $link;
1257 sub htmllink ($$$;@) {
1258 my $lpage=shift; # the page doing the linking
1259 my $page=shift; # the page that will contain the link (different for inline)
1266 if (! $opts{forcesubpage}) {
1267 $bestlink=bestlink($lpage, $link);
1270 $bestlink="$lpage/".lc($link);
1274 if (defined $opts{linktext}) {
1275 $linktext=$opts{linktext};
1278 $linktext=pagetitle(basename($link));
1281 return "<span class=\"selflink\">$linktext</span>"
1282 if length $bestlink && isselflink($page, $bestlink) &&
1283 ! defined $opts{anchor};
1285 if (! $destsources{$bestlink}) {
1286 $bestlink=htmlpage($bestlink);
1288 if (! $destsources{$bestlink}) {
1290 if (length $config{cgiurl}) {
1291 $cgilink = "<a href=\"".
1296 )."\" rel=\"nofollow\">?</a>";
1298 return "<span class=\"createlink\">$cgilink$linktext</span>"
1302 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1303 $bestlink=beautify_urlpath($bestlink);
1305 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1306 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1309 if (defined $opts{anchor}) {
1310 $bestlink.="#".$opts{anchor};
1314 foreach my $attr (qw{rel class title}) {
1315 if (defined $opts{$attr}) {
1316 push @attrs, " $attr=\"$opts{$attr}\"";
1320 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1325 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1328 sub openiduser ($) {
1331 if (defined $user && $user =~ m!^https?://! &&
1332 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1335 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1336 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1339 # backcompat with old version
1340 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1341 $display=$oid->display;
1344 # Convert "user.somehost.com" to "user [somehost.com]"
1345 # (also "user.somehost.co.uk")
1346 if ($display !~ /\[/) {
1347 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1349 # Convert "http://somehost.com/user" to "user [somehost.com]".
1350 # (also "https://somehost.com/user/")
1351 if ($display !~ /\[/) {
1352 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1354 $display=~s!^https?://!!; # make sure this is removed
1355 eval q{use CGI 'escapeHTML'};
1357 return escapeHTML($display);
1362 sub htmlize ($$$$) {
1368 my $oneline = $content !~ /\n/;
1370 if (exists $hooks{htmlize}{$type}) {
1371 $content=$hooks{htmlize}{$type}{call}->(
1373 content => $content,
1377 error("htmlization of $type not supported");
1380 run_hooks(sanitize => sub {
1383 destpage => $destpage,
1384 content => $content,
1389 # hack to get rid of enclosing junk added by markdown
1390 # and other htmlizers/sanitizers
1391 $content=~s/^<p>//i;
1392 $content=~s/<\/p>\n*$//i;
1403 run_hooks(linkify => sub {
1406 destpage => $destpage,
1407 content => $content,
1415 our $preprocess_preview=0;
1416 sub preprocess ($$$;$$) {
1417 my $page=shift; # the page the data comes from
1418 my $destpage=shift; # the page the data will appear in (different for inline)
1423 # Using local because it needs to be set within any nested calls
1425 local $preprocess_preview=$preview if defined $preview;
1432 $params="" if ! defined $params;
1434 if (length $escape) {
1435 return "[[$prefix$command $params]]";
1437 elsif (exists $hooks{preprocess}{$command}) {
1438 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1439 # Note: preserve order of params, some plugins may
1440 # consider it significant.
1442 while ($params =~ m{
1443 (?:([-.\w]+)=)? # 1: named parameter key?
1445 """(.*?)""" # 2: triple-quoted value
1447 "([^"]*?)" # 3: single-quoted value
1449 '''(.*?)''' # 4: triple-single-quote
1451 <<([a-zA-Z]+)\n # 5: heredoc start
1452 (.*?)\n\5 # 6: heredoc value
1454 (\S+) # 7: unquoted value
1456 (?:\s+|$) # delimiter to next param
1466 elsif (defined $3) {
1469 elsif (defined $4) {
1472 elsif (defined $7) {
1475 elsif (defined $6) {
1480 push @params, $key, $val;
1483 push @params, $val, '';
1486 if ($preprocessing{$page}++ > 3) {
1487 # Avoid loops of preprocessed pages preprocessing
1488 # other pages that preprocess them, etc.
1489 return "[[!$command <span class=\"error\">".
1490 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1491 $page, $preprocessing{$page}).
1497 $hooks{preprocess}{$command}{call}->(
1500 destpage => $destpage,
1501 preview => $preprocess_preview,
1507 $ret="[[!$command <span class=\"error\">".
1508 gettext("Error").": $error"."</span>]]";
1512 # use void context during scan pass
1514 $hooks{preprocess}{$command}{call}->(
1517 destpage => $destpage,
1518 preview => $preprocess_preview,
1523 $preprocessing{$page}--;
1527 return "[[$prefix$command $params]]";
1532 if ($config{prefix_directives}) {
1535 \[\[(!) # directive open; 2: prefix
1536 ([-\w]+) # 3: command
1537 ( # 4: the parameters..
1538 \s+ # Must have space if parameters present
1540 (?:[-.\w]+=)? # named parameter key?
1542 """.*?""" # triple-quoted value
1544 "[^"]*?" # single-quoted value
1546 '''.*?''' # triple-single-quote
1548 <<([a-zA-Z]+)\n # 5: heredoc start
1549 (?:.*?)\n\5 # heredoc value
1551 [^"\s\]]+ # unquoted value
1553 \s* # whitespace or end
1556 *)? # 0 or more parameters
1557 \]\] # directive closed
1563 \[\[(!?) # directive open; 2: optional prefix
1564 ([-\w]+) # 3: command
1566 ( # 4: the parameters..
1568 (?:[-.\w]+=)? # named parameter key?
1570 """.*?""" # triple-quoted value
1572 "[^"]*?" # single-quoted value
1574 '''.*?''' # triple-single-quote
1576 <<([a-zA-Z]+)\n # 5: heredoc start
1577 (?:.*?)\n\5 # heredoc value
1579 [^"\s\]]+ # unquoted value
1581 \s* # whitespace or end
1584 *) # 0 or more parameters
1585 \]\] # directive closed
1589 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1598 run_hooks(filter => sub {
1599 $content=shift->(page => $page, destpage => $destpage,
1600 content => $content);
1606 sub check_canedit ($$$;$) {
1613 run_hooks(canedit => sub {
1614 return if defined $canedit;
1615 my $ret=shift->($page, $q, $session);
1620 elsif (ref $ret eq 'CODE') {
1621 $ret->() unless $nonfatal;
1624 elsif (defined $ret) {
1625 error($ret) unless $nonfatal;
1630 return defined $canedit ? $canedit : 1;
1633 sub check_content (@) {
1636 return 1 if ! exists $hooks{checkcontent}; # optimisation
1638 if (exists $pagesources{$params{page}}) {
1640 my %old=map { $_ => 1 }
1641 split("\n", readfile(srcfile($pagesources{$params{page}})));
1642 foreach my $line (split("\n", $params{content})) {
1643 push @diff, $line if ! exists $old{$line};
1645 $params{diff}=join("\n", @diff);
1649 run_hooks(checkcontent => sub {
1650 return if defined $ok;
1651 my $ret=shift->(%params);
1656 elsif (ref $ret eq 'CODE') {
1657 $ret->() unless $params{nonfatal};
1660 elsif (defined $ret) {
1661 error($ret) unless $params{nonfatal};
1667 return defined $ok ? $ok : 1;
1670 sub check_canchange (@) {
1672 my $cgi = $params{cgi};
1673 my $session = $params{session};
1674 my @changes = @{$params{changes}};
1677 foreach my $change (@changes) {
1678 # This untaint is safe because we check file_pruned and
1680 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1681 $file=possibly_foolish_untaint($file);
1682 if (! defined $file || ! length $file ||
1683 file_pruned($file)) {
1684 error(gettext("bad file name %s"), $file);
1687 my $type=pagetype($file);
1688 my $page=pagename($file) if defined $type;
1690 if ($change->{action} eq 'add') {
1694 if ($change->{action} eq 'change' ||
1695 $change->{action} eq 'add') {
1696 if (defined $page) {
1697 check_canedit($page, $cgi, $session);
1701 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1702 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1703 check_canedit($file, $cgi, $session);
1708 elsif ($change->{action} eq 'remove') {
1709 # check_canremove tests to see if the file is present
1710 # on disk. This will fail when a single commit adds a
1711 # file and then removes it again. Avoid the problem
1712 # by not testing the removal in such pairs of changes.
1713 # (The add is still tested, just to make sure that
1714 # no data is added to the repo that a web edit
1716 next if $newfiles{$file};
1718 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1719 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1720 check_canedit(defined $page ? $page : $file, $cgi, $session);
1725 error "unknown action ".$change->{action};
1728 error sprintf(gettext("you are not allowed to change %s"), $file);
1736 # Take an exclusive lock on the wiki to prevent multiple concurrent
1737 # run issues. The lock will be dropped on program exit.
1738 if (! -d $config{wikistatedir}) {
1739 mkdir($config{wikistatedir});
1741 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1742 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1743 if (! flock($wikilock, 2)) { # LOCK_EX
1744 error("failed to get lock");
1750 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1751 return close($wikilock) if $wikilock;
1757 sub commit_hook_enabled () {
1758 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1759 error("cannot write to $config{wikistatedir}/commitlock: $!");
1760 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1761 close($commitlock) || error("failed closing commitlock: $!");
1764 close($commitlock) || error("failed closing commitlock: $!");
1768 sub disable_commit_hook () {
1769 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1770 error("cannot write to $config{wikistatedir}/commitlock: $!");
1771 if (! flock($commitlock, 2)) { # LOCK_EX
1772 error("failed to get commit lock");
1777 sub enable_commit_hook () {
1778 return close($commitlock) if $commitlock;
1783 %oldrenderedfiles=%pagectime=();
1784 if (! $config{rebuild}) {
1785 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1786 %destsources=%renderedfiles=%pagecase=%pagestate=
1787 %depends_simple=%typedlinks=%oldtypedlinks=();
1790 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1791 if (-e "$config{wikistatedir}/index") {
1792 system("ikiwiki-transition", "indexdb", $config{srcdir});
1793 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1796 $config{gettime}=1; # first build
1801 my $index=Storable::fd_retrieve($in);
1802 if (! defined $index) {
1807 if (exists $index->{version} && ! ref $index->{version}) {
1808 $pages=$index->{page};
1809 %wikistate=%{$index->{state}};
1810 # Handle plugins that got disabled by loading a new setup.
1811 if (exists $config{setupfile}) {
1812 require IkiWiki::Setup;
1813 IkiWiki::Setup::disabled_plugins(
1814 grep { ! $loaded_plugins{$_} } keys %wikistate);
1822 foreach my $src (keys %$pages) {
1823 my $d=$pages->{$src};
1824 my $page=pagename($src);
1825 $pagectime{$page}=$d->{ctime};
1826 $pagesources{$page}=$src;
1827 if (! $config{rebuild}) {
1828 $pagemtime{$page}=$d->{mtime};
1829 $renderedfiles{$page}=$d->{dest};
1830 if (exists $d->{links} && ref $d->{links}) {
1831 $links{$page}=$d->{links};
1832 $oldlinks{$page}=[@{$d->{links}}];
1834 if (ref $d->{depends_simple} eq 'ARRAY') {
1836 $depends_simple{$page}={
1837 map { $_ => 1 } @{$d->{depends_simple}}
1840 elsif (exists $d->{depends_simple}) {
1841 $depends_simple{$page}=$d->{depends_simple};
1843 if (exists $d->{dependslist}) {
1846 map { $_ => $DEPEND_CONTENT }
1847 @{$d->{dependslist}}
1850 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1852 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1854 elsif (exists $d->{depends}) {
1855 $depends{$page}=$d->{depends};
1857 if (exists $d->{state}) {
1858 $pagestate{$page}=$d->{state};
1860 if (exists $d->{typedlinks}) {
1861 $typedlinks{$page}=$d->{typedlinks};
1863 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1864 next unless %$links;
1865 $oldtypedlinks{$page}{$type} = {%$links};
1869 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1871 foreach my $page (keys %pagesources) {
1872 $pagecase{lc $page}=$page;
1874 foreach my $page (keys %renderedfiles) {
1875 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1881 run_hooks(savestate => sub { shift->() });
1883 my @plugins=keys %loaded_plugins;
1885 if (! -d $config{wikistatedir}) {
1886 mkdir($config{wikistatedir});
1888 my $newfile="$config{wikistatedir}/indexdb.new";
1889 my $cleanup = sub { unlink($newfile) };
1890 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1893 foreach my $page (keys %pagemtime) {
1894 next unless $pagemtime{$page};
1895 my $src=$pagesources{$page};
1897 $index{page}{$src}={
1898 ctime => $pagectime{$page},
1899 mtime => $pagemtime{$page},
1900 dest => $renderedfiles{$page},
1901 links => $links{$page},
1904 if (exists $depends{$page}) {
1905 $index{page}{$src}{depends} = $depends{$page};
1908 if (exists $depends_simple{$page}) {
1909 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1912 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1913 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1916 if (exists $pagestate{$page}) {
1917 foreach my $id (@plugins) {
1918 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1919 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1926 foreach my $id (@plugins) {
1927 $index{state}{$id}={}; # used to detect disabled plugins
1928 foreach my $key (keys %{$wikistate{$id}}) {
1929 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1933 $index{version}="3";
1934 my $ret=Storable::nstore_fd(\%index, $out);
1935 return if ! defined $ret || ! $ret;
1936 close $out || error("failed saving to $newfile: $!", $cleanup);
1937 rename($newfile, "$config{wikistatedir}/indexdb") ||
1938 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1943 sub template_file ($) {
1946 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1948 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1949 $template=srcfile($pagesources{$tpage}, 1);
1953 $template=srcfile($tpage, 1);
1956 if (defined $template) {
1957 return $template, $tpage, 1 if wantarray;
1961 $name=~s:/::; # avoid path traversal
1962 foreach my $dir ($config{templatedir},
1963 "$installdir/share/ikiwiki/templates") {
1964 if (-e "$dir/$name") {
1965 $template="$dir/$name";
1969 if (defined $template) {
1970 return $template, $tpage if wantarray;
1978 sub template_depends ($$;@) {
1982 my ($filename, $tpage, $untrusted)=template_file($name);
1983 if (! defined $filename) {
1984 error(sprintf(gettext("template %s not found"), $name))
1987 if (defined $page && defined $tpage) {
1988 add_depends($page, $tpage);
1993 my $text_ref = shift;
1994 ${$text_ref} = decode_utf8(${$text_ref});
1996 loop_context_vars => 1,
1997 die_on_bad_params => 0,
1998 parent_global_vars => 1,
1999 filename => $filename,
2001 ($untrusted ? (no_includes => 1) : ()),
2003 return @opts if wantarray;
2005 require HTML::Template;
2006 return HTML::Template->new(@opts);
2009 sub template ($;@) {
2010 template_depends(shift, undef, @_);
2013 sub templateactions ($$) {
2019 run_hooks(pageactions => sub {
2020 push @actions, map { { action => $_ } }
2021 grep { defined } shift->(page => $page);
2023 $template->param(actions => \@actions);
2025 if ($config{cgiurl} && exists $hooks{auth}) {
2026 $template->param(prefsurl => cgiurl(do => "prefs"));
2030 if ($have_actions || @actions) {
2031 $template->param(have_actions => 1);
2038 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2039 error 'hook requires type, call, and id parameters';
2042 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2044 $hooks{$param{type}}{$param{id}}=\%param;
2048 sub run_hooks ($$) {
2049 # Calls the given sub for each hook of the given type,
2050 # passing it the hook function to call.
2054 if (exists $hooks{$type}) {
2055 my (@first, @middle, @last);
2056 foreach my $id (keys %{$hooks{$type}}) {
2057 if ($hooks{$type}{$id}{first}) {
2060 elsif ($hooks{$type}{$id}{last}) {
2067 foreach my $id (@first, @middle, @last) {
2068 $sub->($hooks{$type}{$id}{call});
2076 $hooks{rcs}{rcs_update}{call}->(@_);
2079 sub rcs_prepedit ($) {
2080 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2083 sub rcs_commit (@) {
2084 $hooks{rcs}{rcs_commit}{call}->(@_);
2087 sub rcs_commit_staged (@) {
2088 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2092 $hooks{rcs}{rcs_add}{call}->(@_);
2095 sub rcs_remove ($) {
2096 $hooks{rcs}{rcs_remove}{call}->(@_);
2099 sub rcs_rename ($$) {
2100 $hooks{rcs}{rcs_rename}{call}->(@_);
2103 sub rcs_recentchanges ($) {
2104 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2107 sub rcs_diff ($;$) {
2108 $hooks{rcs}{rcs_diff}{call}->(@_);
2111 sub rcs_getctime ($) {
2112 $hooks{rcs}{rcs_getctime}{call}->(@_);
2115 sub rcs_getmtime ($) {
2116 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2119 sub rcs_receive () {
2120 $hooks{rcs}{rcs_receive}{call}->();
2123 sub add_depends ($$;$) {
2126 my $deptype=shift || $DEPEND_CONTENT;
2128 # Is the pagespec a simple page name?
2129 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2130 $pagespec !~ /[\s*?()!]/) {
2131 $depends_simple{$page}{lc $pagespec} |= $deptype;
2135 # Add explicit dependencies for influences.
2136 my $sub=pagespec_translate($pagespec);
2137 return unless defined $sub;
2138 foreach my $p (keys %pagesources) {
2139 my $r=$sub->($p, location => $page);
2140 my $i=$r->influences;
2141 my $static=$r->influences_static;
2142 foreach my $k (keys %$i) {
2143 next unless $r || $static || $k eq $page;
2144 $depends_simple{$page}{lc $k} |= $i->{$k};
2149 $depends{$page}{$pagespec} |= $deptype;
2155 foreach my $type (@_) {
2156 if ($type eq 'presence') {
2157 $deptype |= $DEPEND_PRESENCE;
2159 elsif ($type eq 'links') {
2160 $deptype |= $DEPEND_LINKS;
2162 elsif ($type eq 'content') {
2163 $deptype |= $DEPEND_CONTENT;
2169 my $file_prune_regexp;
2170 sub file_pruned ($) {
2173 if (defined $config{include} && length $config{include}) {
2174 return 0 if $file =~ m/$config{include}/;
2177 if (! defined $file_prune_regexp) {
2178 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2179 $file_prune_regexp=qr/$file_prune_regexp/;
2181 return $file =~ m/$file_prune_regexp/;
2184 sub define_gettext () {
2185 # If translation is needed, redefine the gettext function to do it.
2186 # Otherwise, it becomes a quick no-op.
2189 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2190 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2191 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2193 $gettext_obj=eval q{
2194 use Locale::gettext q{textdomain};
2195 Locale::gettext->domain('ikiwiki')
2200 no warnings 'redefine';
2202 $getobj->() if $getobj;
2204 $gettext_obj->get(shift);
2211 $getobj->() if $getobj;
2213 $gettext_obj->nget(@_);
2216 return ($_[2] == 1 ? $_[0] : $_[1])
2234 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2238 # Injects a new function into the symbol table to replace an
2239 # exported function.
2242 # This is deep ugly perl foo, beware.
2245 if (! defined $params{parent}) {
2246 $params{parent}='::';
2247 $params{old}=\&{$params{name}};
2248 $params{name}=~s/.*:://;
2250 my $parent=$params{parent};
2251 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2252 $ns = $params{parent} . $ns;
2253 inject(%params, parent => $ns) unless $ns eq '::main::';
2254 *{$ns . $params{name}} = $params{call}
2255 if exists ${$ns}{$params{name}} &&
2256 \&{${$ns}{$params{name}}} == $params{old};
2262 sub add_link ($$;$) {
2267 push @{$links{$page}}, $link
2268 unless grep { $_ eq $link } @{$links{$page}};
2270 if (defined $type) {
2271 $typedlinks{$page}{$type}{$link} = 1;
2275 sub add_autofile ($$$) {
2278 my $generator=shift;
2280 $autofiles{$file}{plugin}=$plugin;
2281 $autofiles{$file}{generator}=$generator;
2285 return LWP::UserAgent->new(
2286 cookie_jar => $config{cookiejar},
2287 env_proxy => 1, # respect proxy env vars
2291 sub sortspec_translate ($$) {
2293 my $reverse = shift;
2299 (-?) # group 1: perhaps negated
2302 \w+\([^\)]*\) # command(params)
2304 [^\s]+ # or anything else
2312 if ($word =~ m/^(\w+)\((.*)\)$/) {
2313 # command with parameters
2317 elsif ($word !~ m/^\w+$/) {
2318 error(sprintf(gettext("invalid sort type %s"), $word));
2329 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2330 if (defined $params) {
2331 push @data, $params;
2332 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2335 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2339 error(sprintf(gettext("unknown sort type %s"), $word));
2343 if (! length $code) {
2344 # undefined sorting method... sort arbitrarily
2353 return eval 'sub { '.$code.' }';
2356 sub pagespec_translate ($) {
2359 # Convert spec to perl code.
2363 \s* # ignore whitespace
2364 ( # 1: match a single word
2371 \w+\([^\)]*\) # command(params)
2373 [^\s()]+ # any other text
2375 \s* # ignore whitespace
2378 if (lc $word eq 'and') {
2381 elsif (lc $word eq 'or') {
2384 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2387 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2388 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2390 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2393 push @data, qq{unknown function in pagespec "$word"};
2394 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2399 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2403 if (! length $code) {
2404 $code="IkiWiki::FailReason->new('empty pagespec')";
2408 return eval 'sub { my $page=shift; '.$code.' }';
2411 sub pagespec_match ($$;@) {
2416 # Backwards compatability with old calling convention.
2418 unshift @params, 'location';
2421 my $sub=pagespec_translate($spec);
2422 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2424 return $sub->($page, @params);
2427 sub pagespec_match_list ($$;@) {
2432 # Backwards compatability with old calling convention.
2434 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2435 $params{list}=$page;
2436 $page=$params{location}; # ugh!
2439 my $sub=pagespec_translate($pagespec);
2440 error "syntax error in pagespec \"$pagespec\""
2442 my $sort=sortspec_translate($params{sort}, $params{reverse})
2443 if defined $params{sort};
2446 if (exists $params{list}) {
2447 @candidates=exists $params{filter}
2448 ? grep { ! $params{filter}->($_) } @{$params{list}}
2452 @candidates=exists $params{filter}
2453 ? grep { ! $params{filter}->($_) } keys %pagesources
2454 : keys %pagesources;
2457 # clear params, remainder is passed to pagespec
2458 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2459 my $num=$params{num};
2460 delete @params{qw{num deptype reverse sort filter list}};
2462 # when only the top matches will be returned, it's efficient to
2463 # sort before matching to pagespec,
2464 if (defined $num && defined $sort) {
2465 @candidates=IkiWiki::SortSpec::sort_pages(
2466 $sort, @candidates);
2472 my $accum=IkiWiki::SuccessReason->new();
2473 foreach my $p (@candidates) {
2474 my $r=$sub->($p, %params, location => $page);
2475 error(sprintf(gettext("cannot match pages: %s"), $r))
2476 if $r->isa("IkiWiki::ErrorReason");
2477 unless ($r || $r->influences_static) {
2478 $r->remove_influence($p);
2483 last if defined $num && ++$count == $num;
2487 # Add simple dependencies for accumulated influences.
2488 my $i=$accum->influences;
2489 foreach my $k (keys %$i) {
2490 $depends_simple{$page}{lc $k} |= $i->{$k};
2493 # when all matches will be returned, it's efficient to
2494 # sort after matching
2495 if (! defined $num && defined $sort) {
2496 return IkiWiki::SortSpec::sort_pages(
2504 sub pagespec_valid ($) {
2507 return defined pagespec_translate($spec);
2511 my $re=quotemeta(shift);
2517 package IkiWiki::FailReason;
2520 '""' => sub { $_[0][0] },
2522 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2523 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2524 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2528 our @ISA = 'IkiWiki::SuccessReason';
2530 package IkiWiki::SuccessReason;
2533 '""' => sub { $_[0][0] },
2535 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2536 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2537 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2544 return bless [$value, {@_}], $class;
2549 $this->[1]={@_} if @_;
2550 my %i=%{$this->[1]};
2555 sub influences_static {
2556 return ! $_[0][1]->{""};
2559 sub merge_influences {
2564 if (! $anded || (($this || %{$this->[1]}) &&
2565 ($other || %{$other->[1]}))) {
2566 foreach my $influence (keys %{$other->[1]}) {
2567 $this->[1]{$influence} |= $other->[1]{$influence};
2576 sub remove_influence {
2580 delete $this->[1]{$torm};
2583 package IkiWiki::ErrorReason;
2585 our @ISA = 'IkiWiki::FailReason';
2587 package IkiWiki::PageSpec;
2593 if ($path =~ m!^\.(/|$)!) {
2595 $from=~s#/?[^/]+$## if defined $from;
2597 $path="$from/$path" if defined $from && length $from;
2601 $path = "" unless defined $path;
2610 sub match_glob ($$;@) {
2615 $glob=derel($glob, $params{location});
2617 # Instead of converting the glob to a regex every time,
2618 # cache the compiled regex to save time.
2619 my $re=$glob_cache{$glob};
2620 unless (defined $re) {
2621 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2624 if (! IkiWiki::isinternal($page) || $params{internal}) {
2625 return IkiWiki::SuccessReason->new("$glob matches $page");
2628 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2632 return IkiWiki::FailReason->new("$glob does not match $page");
2636 sub match_internal ($$;@) {
2637 return match_glob(shift, shift, @_, internal => 1)
2640 sub match_page ($$;@) {
2642 my $match=match_glob($page, shift, @_);
2644 my $source=exists $IkiWiki::pagesources{$page} ?
2645 $IkiWiki::pagesources{$page} :
2646 $IkiWiki::delpagesources{$page};
2647 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2648 if (! defined $type) {
2649 return IkiWiki::FailReason->new("$page is not a page");
2655 sub match_link ($$;@) {
2660 $link=derel($link, $params{location});
2661 my $from=exists $params{location} ? $params{location} : '';
2662 my $linktype=$params{linktype};
2664 if (defined $linktype) {
2665 $qualifier=" with type $linktype";
2668 my $links = $IkiWiki::links{$page};
2669 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2670 unless $links && @{$links};
2671 my $bestlink = IkiWiki::bestlink($from, $link);
2672 foreach my $p (@{$links}) {
2673 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2675 if (length $bestlink) {
2676 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2677 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2681 if (match_glob($p, $link, %params)) {
2682 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2684 my ($p_rel)=$p=~/^\/?(.*)/;
2686 if (match_glob($p_rel, $link, %params)) {
2687 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2691 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2694 sub match_backlink ($$;@) {
2698 if ($testpage eq '.') {
2699 $testpage = $params{'location'}
2701 my $ret=match_link($testpage, $page, @_);
2702 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2706 sub match_created_before ($$;@) {
2711 $testpage=derel($testpage, $params{location});
2713 if (exists $IkiWiki::pagectime{$testpage}) {
2714 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2715 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2718 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2722 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2726 sub match_created_after ($$;@) {
2731 $testpage=derel($testpage, $params{location});
2733 if (exists $IkiWiki::pagectime{$testpage}) {
2734 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2735 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2738 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2742 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2746 sub match_creation_day ($$;@) {
2749 if ($d !~ /^\d+$/) {
2750 return IkiWiki::ErrorReason->new("invalid day $d");
2752 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2753 return IkiWiki::SuccessReason->new('creation_day matched');
2756 return IkiWiki::FailReason->new('creation_day did not match');
2760 sub match_creation_month ($$;@) {
2763 if ($m !~ /^\d+$/) {
2764 return IkiWiki::ErrorReason->new("invalid month $m");
2766 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2767 return IkiWiki::SuccessReason->new('creation_month matched');
2770 return IkiWiki::FailReason->new('creation_month did not match');
2774 sub match_creation_year ($$;@) {
2777 if ($y !~ /^\d+$/) {
2778 return IkiWiki::ErrorReason->new("invalid year $y");
2780 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2781 return IkiWiki::SuccessReason->new('creation_year matched');
2784 return IkiWiki::FailReason->new('creation_year did not match');
2788 sub match_user ($$;@) {
2793 if (! exists $params{user}) {
2794 return IkiWiki::ErrorReason->new("no user specified");
2797 my $regexp=IkiWiki::glob2re($user);
2799 if (defined $params{user} && $params{user}=~$regexp) {
2800 return IkiWiki::SuccessReason->new("user is $user");
2802 elsif (! defined $params{user}) {
2803 return IkiWiki::FailReason->new("not logged in");
2806 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2810 sub match_admin ($$;@) {
2815 if (! exists $params{user}) {
2816 return IkiWiki::ErrorReason->new("no user specified");
2819 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2820 return IkiWiki::SuccessReason->new("user is an admin");
2822 elsif (! defined $params{user}) {
2823 return IkiWiki::FailReason->new("not logged in");
2826 return IkiWiki::FailReason->new("user is not an admin");
2830 sub match_ip ($$;@) {
2835 if (! exists $params{ip}) {
2836 return IkiWiki::ErrorReason->new("no IP specified");
2839 my $regexp=IkiWiki::glob2re(lc $ip);
2841 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2842 return IkiWiki::SuccessReason->new("IP is $ip");
2845 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2849 package IkiWiki::SortSpec;
2851 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2852 # are easily available in this namespace, for cmp functions to use them.
2859 IkiWiki::pagetitle(IkiWiki::basename($a))
2861 IkiWiki::pagetitle(IkiWiki::basename($b))
2864 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2865 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2866 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }