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 @underlayfiles $lastrev};
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)",
137 only_committed_changes => {
140 description => "enable optimization of only refreshing committed changes?",
147 description => "rcs backend to use",
148 safe => 0, # don't allow overriding
153 default => [qw{mdwn link inline meta htmlscrubber passwordauth
154 openid signinedit lockedit conditional
155 recentchanges parentlinks editpage
157 description => "plugins to enable by default",
164 description => "plugins to add to the default configuration",
171 description => "plugins to disable",
177 default => "$installdir/share/ikiwiki/templates",
178 description => "additional directory to search for template files",
185 default => "$installdir/share/ikiwiki/basewiki",
186 description => "base wiki source location",
193 default => "$installdir/share/ikiwiki",
194 description => "parent directory containing additional underlays",
201 description => "wrappers to generate",
208 description => "additional underlays to use",
215 description => "display verbose messages?",
222 description => "log to syslog?",
229 description => "create output files named page/index.html?",
230 safe => 0, # changing requires manual transition
233 prefix_directives => {
236 description => "use '!'-prefixed preprocessor directives?",
237 safe => 0, # changing requires manual transition
243 description => "use page/index.mdwn source files",
250 description => "enable Discussion pages?",
256 default => gettext("Discussion"),
257 description => "name of Discussion pages",
264 description => "generate HTML5?",
272 description => "only send cookies over SSL connections?",
280 description => "extension to use for new pages",
281 safe => 0, # not sanitized
287 description => "extension to use for html files",
288 safe => 0, # not sanitized
294 description => "strftime format string to display date",
302 example => "en_US.UTF-8",
303 description => "UTF-8 locale to use",
312 description => "put user pages below specified page",
319 description => "how many backlinks to show before hiding excess (0 to show all)",
326 description => "attempt to hardlink source files? (optimisation for large files)",
328 safe => 0, # paranoia
334 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
336 safe => 0, # paranoia
341 example => "ikiwiki",
342 description => "group for wrappers to run in",
344 safe => 0, # paranoia
350 example => "$ENV{HOME}/.ikiwiki/",
351 description => "extra library and plugin directory",
353 safe => 0, # directory
359 description => "environment variables",
360 safe => 0, # paranoia
366 example => "US/Eastern",
367 description => "time zone name",
374 example => '^\.htaccess$',
375 description => "regexp of normally excluded files to include",
383 example => '^(*\.private|Makefile)$',
384 description => "regexp of files that should be skipped",
389 wiki_file_prune_regexps => {
391 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
392 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
393 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
394 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
395 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
396 description => "regexps of source files to ignore",
402 description => "specifies the characters that are allowed in source filenames",
403 default => "-[:alnum:]+/.:_",
407 wiki_file_regexp => {
409 description => "regexp of legal source files",
413 web_commit_regexp => {
415 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
416 description => "regexp to parse web commits from logs",
423 description => "run as a cgi",
427 cgi_disable_uploads => {
430 description => "whether CGI should accept file uploads",
437 description => "run as a post-commit hook",
444 description => "running in rebuild mode",
451 description => "running in setup mode",
458 description => "running in clean mode",
465 description => "running in refresh mode",
472 description => "running in receive test mode",
476 wrapper_background_command => {
479 description => "background shell command to run",
485 description => "running in gettime mode",
492 description => "running in w3mmode",
499 description => "path to the .ikiwiki directory holding ikiwiki state",
506 description => "path to setup file",
513 description => "perl class to use to dump setup file",
517 allow_symlinks_before_srcdir => {
520 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
526 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
527 description => "cookie control",
528 safe => 0, # hooks into perl module internals
534 example => "Wget/1.13.4 (linux-gnu)",
535 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
541 sub defaultconfig () {
544 foreach my $key (keys %s) {
545 push @ret, $key, $s{$key}->{default};
550 # URL to top of wiki as a path starting with /, valid from any wiki page or
551 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
553 # URL to CGI script, similar to $local_url
557 # locale stuff; avoid LC_ALL since it overrides everything
558 if (defined $ENV{LC_ALL}) {
559 $ENV{LANG} = $ENV{LC_ALL};
562 if (defined $config{locale}) {
563 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
564 $ENV{LANG}=$config{locale};
569 if (! defined $config{wiki_file_regexp}) {
570 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
573 if (ref $config{ENV} eq 'HASH') {
574 foreach my $val (keys %{$config{ENV}}) {
575 $ENV{$val}=$config{ENV}{$val};
578 if (defined $config{timezone} && length $config{timezone}) {
579 $ENV{TZ}=$config{timezone};
582 $config{timezone}=$ENV{TZ};
585 if ($config{w3mmode}) {
586 eval q{use Cwd q{abs_path}};
588 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
589 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
590 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
591 unless $config{cgiurl} =~ m!file:///!;
592 $config{url}="file://".$config{destdir};
595 if ($config{cgi} && ! length $config{url}) {
596 error(gettext("Must specify url to wiki with --url when using --cgi"));
599 if (defined $config{url} && length $config{url}) {
601 my $baseurl = URI->new($config{url});
603 $local_url = $baseurl->path . "/";
604 $local_cgiurl = undef;
606 if (length $config{cgiurl}) {
607 my $cgiurl = URI->new($config{cgiurl});
609 $local_cgiurl = $cgiurl->path;
611 if ($cgiurl->scheme ne $baseurl->scheme or
612 $cgiurl->authority ne $baseurl->authority) {
613 # too far apart, fall back to absolute URLs
614 $local_url = "$config{url}/";
615 $local_cgiurl = $config{cgiurl};
619 $local_url =~ s{//$}{/};
622 $local_cgiurl = $config{cgiurl};
625 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
626 unless exists $config{wikistatedir} && defined $config{wikistatedir};
628 if (defined $config{umask}) {
629 my $u = possibly_foolish_untaint($config{umask});
631 if ($u =~ m/^\d+$/) {
634 elsif ($u eq 'private') {
637 elsif ($u eq 'group') {
640 elsif ($u eq 'public') {
644 error(sprintf(gettext("unsupported umask setting %s"), $u));
648 run_hooks(checkconfig => sub { shift->() });
656 foreach my $dir (@INC, $config{libdir}) {
657 next unless defined $dir && length $dir;
658 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
659 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
663 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
664 next unless defined $dir && length $dir;
665 foreach my $file (glob("$dir/plugins/*")) {
666 $ret{basename($file)}=1 if -x $file;
674 if (defined $config{libdir} && length $config{libdir}) {
675 unshift @INC, possibly_foolish_untaint($config{libdir});
678 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
683 if (exists $hooks{rcs}) {
684 error(gettext("cannot use multiple rcs plugins"));
686 loadplugin($config{rcs});
688 if (! exists $hooks{rcs}) {
692 run_hooks(getopt => sub { shift->() });
693 if (grep /^-/, @ARGV) {
694 print STDERR "Unknown option (or missing parameter): $_\n"
695 foreach grep /^-/, @ARGV;
702 sub loadplugin ($;$) {
706 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
708 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
709 "$installdir/lib/ikiwiki") {
710 if (defined $dir && -x "$dir/plugins/$plugin") {
711 eval { require IkiWiki::Plugin::external };
714 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
716 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
717 $loaded_plugins{$plugin}=1;
722 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
725 error("Failed to load plugin $mod: $@");
727 $loaded_plugins{$plugin}=1;
734 log_message('err' => $message) if $config{syslog};
735 if (defined $cleaner) {
742 return unless $config{verbose};
743 return log_message(debug => @_);
748 sub log_message ($$) {
751 if ($config{syslog}) {
754 Sys::Syslog::setlogsock('unix');
755 Sys::Syslog::openlog('ikiwiki', '', 'user');
759 # keep a copy to avoid editing the original config repeatedly
760 my $wikiname = $config{wikiname};
761 utf8::encode($wikiname);
762 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
765 print STDERR "failed to syslog: $@" unless $log_failed;
771 elsif (! $config{cgi}) {
775 return print STDERR "@_\n";
779 sub possibly_foolish_untaint ($) {
781 my ($untainted)=$tainted=~/(.*)/s;
801 return exists $pagesources{$page} &&
802 $pagesources{$page} =~ /\._([^.]+)$/;
808 if ($file =~ /\.([^.]+)$/) {
809 return $1 if exists $hooks{htmlize}{$1};
811 my $base=basename($file);
812 if (exists $hooks{htmlize}{$base} &&
813 $hooks{htmlize}{$base}{noextension}) {
824 if (exists $pagename_cache{$file}) {
825 return $pagename_cache{$file};
828 my $type=pagetype($file);
830 $page=~s/\Q.$type\E*$//
831 if defined $type && !$hooks{htmlize}{$type}{keepextension}
832 && !$hooks{htmlize}{$type}{noextension};
833 if ($config{indexpages} && $page=~/(.*)\/index$/) {
837 $pagename_cache{$file} = $page;
841 sub newpagefile ($$) {
845 if (! $config{indexpages} || $page eq 'index') {
846 return $page.".".$type;
849 return $page."/index.".$type;
853 sub targetpage ($$;$) {
858 if (defined $filename) {
859 return $page."/".$filename.".".$ext;
861 elsif (! $config{usedirs} || $page eq 'index') {
862 return $page.".".$ext;
865 return $page."/index.".$ext;
872 return targetpage($page, $config{htmlext});
879 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
880 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
881 return "$dir/$file", stat(_) if -e "$dir/$file";
883 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
888 return (srcfile_stat(@_))[0];
891 sub add_literal_underlay ($) {
894 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
895 unshift @{$config{underlaydirs}}, $dir;
899 sub add_underlay ($) {
903 $dir="$config{underlaydirbase}/$dir";
906 add_literal_underlay($dir);
907 # why does it return 1? we just don't know
911 sub readfile ($;$$) {
917 error("cannot read a symlink ($file)");
921 open (my $in, "<", $file) || error("failed to read $file: $!");
922 binmode($in) if ($binary);
923 return \*$in if $wantfd;
925 # check for invalid utf-8, and toss it back to avoid crashes
926 if (! utf8::valid($ret)) {
927 $ret=encode_utf8($ret);
929 close $in || error("failed to read $file: $!");
933 sub prep_writefile ($$) {
938 while (length $test) {
939 if (-l "$destdir/$test") {
940 error("cannot write to a symlink ($test)");
942 if (-f _ && $test ne $file) {
943 # Remove conflicting file.
944 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
945 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
947 unlink("$destdir/$test");
953 $test=dirname($test);
956 my $dir=dirname("$destdir/$file");
959 foreach my $s (split(m!/+!, $dir)) {
962 mkdir($d) || error("failed to create directory $d: $!");
970 sub writefile ($$$;$$) {
971 my $file=shift; # can include subdirs
972 my $destdir=shift; # directory to put file in
977 prep_writefile($file, $destdir);
979 my $newfile="$destdir/$file.ikiwiki-new";
981 error("cannot write to a symlink ($newfile)");
984 my $cleanup = sub { unlink($newfile) };
985 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
986 binmode($out) if ($binary);
988 $writer->(\*$out, $cleanup);
991 print $out $content or error("failed writing to $newfile: $!", $cleanup);
993 close $out || error("failed saving $newfile: $!", $cleanup);
994 rename($newfile, "$destdir/$file") ||
995 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1001 sub will_render ($$;$) {
1006 # Important security check for independently created files.
1007 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1008 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1009 my $from_other_page=0;
1010 # Expensive, but rarely runs.
1011 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1014 dirname($_) eq $dest
1015 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1021 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1022 unless $from_other_page;
1025 # If $dest exists as a directory, remove conflicting files in it
1026 # rendered from other pages.
1028 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1029 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1030 if (dirname($f) eq $dest) {
1031 unlink("$config{destdir}/$f");
1032 rmdir(dirname("$config{destdir}/$f"));
1038 if (! $clear || $cleared{$page}) {
1039 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1042 foreach my $old (@{$renderedfiles{$page}}) {
1043 delete $destsources{$old};
1045 $renderedfiles{$page}=[$dest];
1048 $destsources{$dest}=$page;
1058 if ($link=~s/^\/+//) {
1066 $l.="/" if length $l;
1069 if (exists $pagesources{$l}) {
1072 elsif (exists $pagecase{lc $l}) {
1073 return $pagecase{lc $l};
1075 } while $cwd=~s{/?[^/]+$}{};
1077 if (length $config{userdir}) {
1078 my $l = "$config{userdir}/".lc($link);
1079 if (exists $pagesources{$l}) {
1082 elsif (exists $pagecase{lc $l}) {
1083 return $pagecase{lc $l};
1087 #print STDERR "warning: page $page, broken link: $link\n";
1091 sub isinlinableimage ($) {
1094 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1097 sub pagetitle ($;$) {
1099 my $unescaped=shift;
1102 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1105 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1113 # support use w/o %config set
1114 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1115 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1121 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1122 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1129 my $cgiurl=$local_cgiurl;
1131 if (exists $params{cgiurl}) {
1132 $cgiurl=$params{cgiurl};
1133 delete $params{cgiurl};
1141 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1144 sub cgiurl_abs (@) {
1146 URI->new_abs(cgiurl(@_), $config{cgiurl});
1152 return $local_url if ! defined $page;
1154 $page=htmlpage($page);
1156 $page=~s/[^\/]+\//..\//g;
1164 return $url unless defined $urlbase && length $urlbase;
1167 URI->new_abs($url, $urlbase)->as_string;
1171 # Work around very innefficient behavior in File::Spec if abs2rel
1172 # is passed two relative paths. It's much faster if paths are
1173 # absolute! (Debian bug #376658; fixed in debian unstable now)
1178 my $ret=File::Spec->abs2rel($path, $base);
1179 $ret=~s/^// if defined $ret;
1183 sub displaytime ($;$$) {
1184 # Plugins can override this function to mark up the time to
1186 my $time=formattime($_[0], $_[1]);
1187 if ($config{html5}) {
1188 return '<time datetime="'.date_3339($_[0]).'"'.
1189 ($_[2] ? ' pubdate="pubdate"' : '').
1190 '>'.$time.'</time>';
1193 return '<span class="date">'.$time.'</span>';
1197 sub formattime ($;$) {
1198 # Plugins can override this function to format the time.
1201 if (! defined $format) {
1202 $format=$config{timeformat};
1205 return strftime_utf8($format, localtime($time));
1208 my $strftime_encoding;
1210 # strftime doesn't know about encodings, so make sure
1211 # its output is properly treated as utf8.
1212 # Note that this does not handle utf-8 in the format string.
1213 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1214 unless defined $strftime_encoding;
1216 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1217 : POSIX::strftime(@_);
1223 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1224 POSIX::setlocale(&POSIX::LC_TIME, "C");
1225 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1226 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1230 sub beautify_urlpath ($) {
1233 # Ensure url is not an empty link, and if necessary,
1234 # add ./ to avoid colon confusion.
1235 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1239 if ($config{usedirs}) {
1240 $url =~ s!/index.$config{htmlext}$!/!;
1255 if (! $destsources{$to}) {
1260 return $config{url}.beautify_urlpath("/".$to);
1263 if (! defined $from) {
1264 my $u = $local_url || '';
1266 return $u.beautify_urlpath("/".$to);
1269 my $link = abs2rel($to, dirname(htmlpage($from)));
1271 return beautify_urlpath($link);
1274 sub isselflink ($$) {
1275 # Plugins can override this function to support special types
1280 return $page eq $link;
1283 sub htmllink ($$$;@) {
1284 my $lpage=shift; # the page doing the linking
1285 my $page=shift; # the page that will contain the link (different for inline)
1292 if (! $opts{forcesubpage}) {
1293 $bestlink=bestlink($lpage, $link);
1296 $bestlink="$lpage/".lc($link);
1300 if (defined $opts{linktext}) {
1301 $linktext=$opts{linktext};
1304 $linktext=pagetitle(basename($link));
1307 return "<span class=\"selflink\">$linktext</span>"
1308 if length $bestlink && isselflink($page, $bestlink) &&
1309 ! defined $opts{anchor};
1311 if (! $destsources{$bestlink}) {
1312 $bestlink=htmlpage($bestlink);
1314 if (! $destsources{$bestlink}) {
1316 if (length $config{cgiurl}) {
1317 $cgilink = "<a href=\"".
1322 )."\" rel=\"nofollow\">?</a>";
1324 return "<span class=\"createlink\">$cgilink$linktext</span>"
1328 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1329 $bestlink=beautify_urlpath($bestlink);
1331 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1332 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1335 if (defined $opts{anchor}) {
1336 $bestlink.="#".$opts{anchor};
1340 foreach my $attr (qw{rel class title}) {
1341 if (defined $opts{$attr}) {
1342 push @attrs, " $attr=\"$opts{$attr}\"";
1346 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1351 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1354 sub openiduser ($) {
1357 if (defined $user && $user =~ m!^https?://! &&
1358 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1361 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1362 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1365 # backcompat with old version
1366 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1367 $display=$oid->display;
1370 # Convert "user.somehost.com" to "user [somehost.com]"
1371 # (also "user.somehost.co.uk")
1372 if ($display !~ /\[/) {
1373 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1375 # Convert "http://somehost.com/user" to "user [somehost.com]".
1376 # (also "https://somehost.com/user/")
1377 if ($display !~ /\[/) {
1378 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1380 $display=~s!^https?://!!; # make sure this is removed
1381 eval q{use CGI 'escapeHTML'};
1383 return escapeHTML($display);
1388 sub htmlize ($$$$) {
1394 my $oneline = $content !~ /\n/;
1396 if (exists $hooks{htmlize}{$type}) {
1397 $content=$hooks{htmlize}{$type}{call}->(
1399 content => $content,
1403 error("htmlization of $type not supported");
1406 run_hooks(sanitize => sub {
1409 destpage => $destpage,
1410 content => $content,
1415 # hack to get rid of enclosing junk added by markdown
1416 # and other htmlizers/sanitizers
1417 $content=~s/^<p>//i;
1418 $content=~s/<\/p>\n*$//i;
1429 run_hooks(linkify => sub {
1432 destpage => $destpage,
1433 content => $content,
1441 our $preprocess_preview=0;
1442 sub preprocess ($$$;$$) {
1443 my $page=shift; # the page the data comes from
1444 my $destpage=shift; # the page the data will appear in (different for inline)
1449 # Using local because it needs to be set within any nested calls
1451 local $preprocess_preview=$preview if defined $preview;
1458 $params="" if ! defined $params;
1460 if (length $escape) {
1461 return "[[$prefix$command $params]]";
1463 elsif (exists $hooks{preprocess}{$command}) {
1464 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1465 # Note: preserve order of params, some plugins may
1466 # consider it significant.
1468 while ($params =~ m{
1469 (?:([-.\w]+)=)? # 1: named parameter key?
1471 """(.*?)""" # 2: triple-quoted value
1473 "([^"]*?)" # 3: single-quoted value
1475 '''(.*?)''' # 4: triple-single-quote
1477 <<([a-zA-Z]+)\n # 5: heredoc start
1478 (.*?)\n\5 # 6: heredoc value
1480 (\S+) # 7: unquoted value
1482 (?:\s+|$) # delimiter to next param
1492 elsif (defined $3) {
1495 elsif (defined $4) {
1498 elsif (defined $7) {
1501 elsif (defined $6) {
1506 push @params, $key, $val;
1509 push @params, $val, '';
1512 if ($preprocessing{$page}++ > 8) {
1513 # Avoid loops of preprocessed pages preprocessing
1514 # other pages that preprocess them, etc.
1515 return "[[!$command <span class=\"error\">".
1516 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1517 $page, $preprocessing{$page}).
1523 $hooks{preprocess}{$command}{call}->(
1526 destpage => $destpage,
1527 preview => $preprocess_preview,
1533 $ret="[[!$command <span class=\"error\">".
1534 gettext("Error").": $error"."</span>]]";
1538 # use void context during scan pass
1540 $hooks{preprocess}{$command}{call}->(
1543 destpage => $destpage,
1544 preview => $preprocess_preview,
1549 $preprocessing{$page}--;
1553 return "[[$prefix$command $params]]";
1558 if ($config{prefix_directives}) {
1561 \[\[(!) # directive open; 2: prefix
1562 ([-\w]+) # 3: command
1563 ( # 4: the parameters..
1564 \s+ # Must have space if parameters present
1566 (?:[-.\w]+=)? # named parameter key?
1568 """.*?""" # triple-quoted value
1570 "[^"]*?" # single-quoted value
1572 '''.*?''' # triple-single-quote
1574 <<([a-zA-Z]+)\n # 5: heredoc start
1575 (?:.*?)\n\5 # heredoc value
1577 [^"\s\]]+ # unquoted value
1579 \s* # whitespace or end
1582 *)? # 0 or more parameters
1583 \]\] # directive closed
1589 \[\[(!?) # directive open; 2: optional prefix
1590 ([-\w]+) # 3: command
1592 ( # 4: the parameters..
1594 (?:[-.\w]+=)? # named parameter key?
1596 """.*?""" # triple-quoted value
1598 "[^"]*?" # single-quoted value
1600 '''.*?''' # triple-single-quote
1602 <<([a-zA-Z]+)\n # 5: heredoc start
1603 (?:.*?)\n\5 # heredoc value
1605 [^"\s\]]+ # unquoted value
1607 \s* # whitespace or end
1610 *) # 0 or more parameters
1611 \]\] # directive closed
1615 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1624 run_hooks(filter => sub {
1625 $content=shift->(page => $page, destpage => $destpage,
1626 content => $content);
1632 sub check_canedit ($$$;$) {
1639 run_hooks(canedit => sub {
1640 return if defined $canedit;
1641 my $ret=shift->($page, $q, $session);
1646 elsif (ref $ret eq 'CODE') {
1647 $ret->() unless $nonfatal;
1650 elsif (defined $ret) {
1651 error($ret) unless $nonfatal;
1656 return defined $canedit ? $canedit : 1;
1659 sub check_content (@) {
1662 return 1 if ! exists $hooks{checkcontent}; # optimisation
1664 if (exists $pagesources{$params{page}}) {
1666 my %old=map { $_ => 1 }
1667 split("\n", readfile(srcfile($pagesources{$params{page}})));
1668 foreach my $line (split("\n", $params{content})) {
1669 push @diff, $line if ! exists $old{$line};
1671 $params{diff}=join("\n", @diff);
1675 run_hooks(checkcontent => sub {
1676 return if defined $ok;
1677 my $ret=shift->(%params);
1682 elsif (ref $ret eq 'CODE') {
1683 $ret->() unless $params{nonfatal};
1686 elsif (defined $ret) {
1687 error($ret) unless $params{nonfatal};
1693 return defined $ok ? $ok : 1;
1696 sub check_canchange (@) {
1698 my $cgi = $params{cgi};
1699 my $session = $params{session};
1700 my @changes = @{$params{changes}};
1703 foreach my $change (@changes) {
1704 # This untaint is safe because we check file_pruned and
1706 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1707 $file=possibly_foolish_untaint($file);
1708 if (! defined $file || ! length $file ||
1709 file_pruned($file)) {
1710 error(gettext("bad file name %s"), $file);
1713 my $type=pagetype($file);
1714 my $page=pagename($file) if defined $type;
1716 if ($change->{action} eq 'add') {
1720 if ($change->{action} eq 'change' ||
1721 $change->{action} eq 'add') {
1722 if (defined $page) {
1723 check_canedit($page, $cgi, $session);
1727 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1728 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1729 check_canedit($file, $cgi, $session);
1734 elsif ($change->{action} eq 'remove') {
1735 # check_canremove tests to see if the file is present
1736 # on disk. This will fail when a single commit adds a
1737 # file and then removes it again. Avoid the problem
1738 # by not testing the removal in such pairs of changes.
1739 # (The add is still tested, just to make sure that
1740 # no data is added to the repo that a web edit
1742 next if $newfiles{$file};
1744 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1745 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1746 check_canedit(defined $page ? $page : $file, $cgi, $session);
1751 error "unknown action ".$change->{action};
1754 error sprintf(gettext("you are not allowed to change %s"), $file);
1762 # Take an exclusive lock on the wiki to prevent multiple concurrent
1763 # run issues. The lock will be dropped on program exit.
1764 if (! -d $config{wikistatedir}) {
1765 mkdir($config{wikistatedir});
1767 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1768 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1769 if (! flock($wikilock, 2)) { # LOCK_EX
1770 error("failed to get lock");
1776 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1777 return close($wikilock) if $wikilock;
1783 sub commit_hook_enabled () {
1784 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1785 error("cannot write to $config{wikistatedir}/commitlock: $!");
1786 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1787 close($commitlock) || error("failed closing commitlock: $!");
1790 close($commitlock) || error("failed closing commitlock: $!");
1794 sub disable_commit_hook () {
1795 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1796 error("cannot write to $config{wikistatedir}/commitlock: $!");
1797 if (! flock($commitlock, 2)) { # LOCK_EX
1798 error("failed to get commit lock");
1803 sub enable_commit_hook () {
1804 return close($commitlock) if $commitlock;
1809 %oldrenderedfiles=%pagectime=();
1810 my $rebuild=$config{rebuild};
1812 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1813 %destsources=%renderedfiles=%pagecase=%pagestate=
1814 %depends_simple=%typedlinks=%oldtypedlinks=();
1817 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1818 if (-e "$config{wikistatedir}/index") {
1819 system("ikiwiki-transition", "indexdb", $config{srcdir});
1820 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1823 $config{gettime}=1; # first build
1828 my $index=Storable::fd_retrieve($in);
1829 if (! defined $index) {
1834 if (exists $index->{version} && ! ref $index->{version}) {
1835 $pages=$index->{page};
1836 %wikistate=%{$index->{state}};
1837 # Handle plugins that got disabled by loading a new setup.
1838 if (exists $config{setupfile}) {
1839 require IkiWiki::Setup;
1840 IkiWiki::Setup::disabled_plugins(
1841 grep { ! $loaded_plugins{$_} } keys %wikistate);
1849 foreach my $src (keys %$pages) {
1850 my $d=$pages->{$src};
1852 if (exists $d->{page} && ! $rebuild) {
1856 $page=pagename($src);
1858 $pagectime{$page}=$d->{ctime};
1859 $pagesources{$page}=$src;
1861 $pagemtime{$page}=$d->{mtime};
1862 $renderedfiles{$page}=$d->{dest};
1863 if (exists $d->{links} && ref $d->{links}) {
1864 $links{$page}=$d->{links};
1865 $oldlinks{$page}=[@{$d->{links}}];
1867 if (ref $d->{depends_simple} eq 'ARRAY') {
1869 $depends_simple{$page}={
1870 map { $_ => 1 } @{$d->{depends_simple}}
1873 elsif (exists $d->{depends_simple}) {
1874 $depends_simple{$page}=$d->{depends_simple};
1876 if (exists $d->{dependslist}) {
1879 map { $_ => $DEPEND_CONTENT }
1880 @{$d->{dependslist}}
1883 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1885 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1887 elsif (exists $d->{depends}) {
1888 $depends{$page}=$d->{depends};
1890 if (exists $d->{state}) {
1891 $pagestate{$page}=$d->{state};
1893 if (exists $d->{typedlinks}) {
1894 $typedlinks{$page}=$d->{typedlinks};
1896 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1897 next unless %$links;
1898 $oldtypedlinks{$page}{$type} = {%$links};
1902 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1904 foreach my $page (keys %pagesources) {
1905 $pagecase{lc $page}=$page;
1907 foreach my $page (keys %renderedfiles) {
1908 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1910 $lastrev=$index->{lastrev};
1911 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1916 run_hooks(savestate => sub { shift->() });
1918 my @plugins=keys %loaded_plugins;
1920 if (! -d $config{wikistatedir}) {
1921 mkdir($config{wikistatedir});
1923 my $newfile="$config{wikistatedir}/indexdb.new";
1924 my $cleanup = sub { unlink($newfile) };
1925 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1928 foreach my $page (keys %pagemtime) {
1929 next unless $pagemtime{$page};
1930 my $src=$pagesources{$page};
1932 $index{page}{$src}={
1934 ctime => $pagectime{$page},
1935 mtime => $pagemtime{$page},
1936 dest => $renderedfiles{$page},
1937 links => $links{$page},
1940 if (exists $depends{$page}) {
1941 $index{page}{$src}{depends} = $depends{$page};
1944 if (exists $depends_simple{$page}) {
1945 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1948 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1949 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1952 if (exists $pagestate{$page}) {
1953 $index{page}{$src}{state}=$pagestate{$page};
1958 foreach my $id (@plugins) {
1959 $index{state}{$id}={}; # used to detect disabled plugins
1960 foreach my $key (keys %{$wikistate{$id}}) {
1961 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1965 $index{lastrev}=$lastrev;
1966 $index{underlayfiles}=\@underlayfiles;
1968 $index{version}="3";
1969 my $ret=Storable::nstore_fd(\%index, $out);
1970 return if ! defined $ret || ! $ret;
1971 close $out || error("failed saving to $newfile: $!", $cleanup);
1972 rename($newfile, "$config{wikistatedir}/indexdb") ||
1973 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1978 sub template_file ($) {
1981 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1983 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1984 $template=srcfile($pagesources{$tpage}, 1);
1988 $template=srcfile($tpage, 1);
1991 if (defined $template) {
1992 return $template, $tpage, 1 if wantarray;
1996 $name=~s:/::; # avoid path traversal
1997 foreach my $dir ($config{templatedir},
1998 "$installdir/share/ikiwiki/templates") {
1999 if (-e "$dir/$name") {
2000 $template="$dir/$name";
2004 if (defined $template) {
2005 return $template, $tpage if wantarray;
2013 sub template_depends ($$;@) {
2017 my ($filename, $tpage, $untrusted)=template_file($name);
2018 if (! defined $filename) {
2019 error(sprintf(gettext("template %s not found"), $name))
2022 if (defined $page && defined $tpage) {
2023 add_depends($page, $tpage);
2028 my $text_ref = shift;
2029 ${$text_ref} = decode_utf8(${$text_ref});
2030 run_hooks(readtemplate => sub {
2031 ${$text_ref} = shift->(
2034 content => ${$text_ref},
2035 untrusted => $untrusted,
2039 loop_context_vars => 1,
2040 die_on_bad_params => 0,
2041 parent_global_vars => 1,
2042 filename => $filename,
2044 ($untrusted ? (no_includes => 1) : ()),
2046 return @opts if wantarray;
2048 require HTML::Template;
2049 return HTML::Template->new(@opts);
2052 sub template ($;@) {
2053 template_depends(shift, undef, @_);
2056 sub templateactions ($$) {
2062 run_hooks(pageactions => sub {
2063 push @actions, map { { action => $_ } }
2064 grep { defined } shift->(page => $page);
2066 $template->param(actions => \@actions);
2068 if ($config{cgiurl} && exists $hooks{auth}) {
2069 $template->param(prefsurl => cgiurl(do => "prefs"));
2073 if ($have_actions || @actions) {
2074 $template->param(have_actions => 1);
2081 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2082 error 'hook requires type, call, and id parameters';
2085 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2087 $hooks{$param{type}}{$param{id}}=\%param;
2091 sub run_hooks ($$) {
2092 # Calls the given sub for each hook of the given type,
2093 # passing it the hook function to call.
2097 if (exists $hooks{$type}) {
2098 my (@first, @middle, @last);
2099 foreach my $id (keys %{$hooks{$type}}) {
2100 if ($hooks{$type}{$id}{first}) {
2103 elsif ($hooks{$type}{$id}{last}) {
2110 foreach my $id (@first, @middle, @last) {
2111 $sub->($hooks{$type}{$id}{call});
2119 $hooks{rcs}{rcs_update}{call}->(@_);
2122 sub rcs_prepedit ($) {
2123 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2126 sub rcs_commit (@) {
2127 $hooks{rcs}{rcs_commit}{call}->(@_);
2130 sub rcs_commit_staged (@) {
2131 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2135 $hooks{rcs}{rcs_add}{call}->(@_);
2138 sub rcs_remove ($) {
2139 $hooks{rcs}{rcs_remove}{call}->(@_);
2142 sub rcs_rename ($$) {
2143 $hooks{rcs}{rcs_rename}{call}->(@_);
2146 sub rcs_recentchanges ($) {
2147 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2150 sub rcs_diff ($;$) {
2151 $hooks{rcs}{rcs_diff}{call}->(@_);
2154 sub rcs_getctime ($) {
2155 $hooks{rcs}{rcs_getctime}{call}->(@_);
2158 sub rcs_getmtime ($) {
2159 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2162 sub rcs_receive () {
2163 $hooks{rcs}{rcs_receive}{call}->();
2166 sub add_depends ($$;$) {
2169 my $deptype=shift || $DEPEND_CONTENT;
2171 # Is the pagespec a simple page name?
2172 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2173 $pagespec !~ /[\s*?()!]/) {
2174 $depends_simple{$page}{lc $pagespec} |= $deptype;
2178 # Add explicit dependencies for influences.
2179 my $sub=pagespec_translate($pagespec);
2180 return unless defined $sub;
2181 foreach my $p (keys %pagesources) {
2182 my $r=$sub->($p, location => $page);
2183 my $i=$r->influences;
2184 my $static=$r->influences_static;
2185 foreach my $k (keys %$i) {
2186 next unless $r || $static || $k eq $page;
2187 $depends_simple{$page}{lc $k} |= $i->{$k};
2192 $depends{$page}{$pagespec} |= $deptype;
2198 foreach my $type (@_) {
2199 if ($type eq 'presence') {
2200 $deptype |= $DEPEND_PRESENCE;
2202 elsif ($type eq 'links') {
2203 $deptype |= $DEPEND_LINKS;
2205 elsif ($type eq 'content') {
2206 $deptype |= $DEPEND_CONTENT;
2212 my $file_prune_regexp;
2213 sub file_pruned ($) {
2216 if (defined $config{include} && length $config{include}) {
2217 return 0 if $file =~ m/$config{include}/;
2220 if (! defined $file_prune_regexp) {
2221 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2222 $file_prune_regexp=qr/$file_prune_regexp/;
2224 return $file =~ m/$file_prune_regexp/;
2227 sub define_gettext () {
2228 # If translation is needed, redefine the gettext function to do it.
2229 # Otherwise, it becomes a quick no-op.
2232 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2233 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2234 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2236 $gettext_obj=eval q{
2237 use Locale::gettext q{textdomain};
2238 Locale::gettext->domain('ikiwiki')
2243 no warnings 'redefine';
2245 $getobj->() if $getobj;
2247 $gettext_obj->get(shift);
2254 $getobj->() if $getobj;
2256 $gettext_obj->nget(@_);
2259 return ($_[2] == 1 ? $_[0] : $_[1])
2277 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2281 # Injects a new function into the symbol table to replace an
2282 # exported function.
2285 # This is deep ugly perl foo, beware.
2288 if (! defined $params{parent}) {
2289 $params{parent}='::';
2290 $params{old}=\&{$params{name}};
2291 $params{name}=~s/.*:://;
2293 my $parent=$params{parent};
2294 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2295 $ns = $params{parent} . $ns;
2296 inject(%params, parent => $ns) unless $ns eq '::main::';
2297 *{$ns . $params{name}} = $params{call}
2298 if exists ${$ns}{$params{name}} &&
2299 \&{${$ns}{$params{name}}} == $params{old};
2305 sub add_link ($$;$) {
2310 push @{$links{$page}}, $link
2311 unless grep { $_ eq $link } @{$links{$page}};
2313 if (defined $type) {
2314 $typedlinks{$page}{$type}{$link} = 1;
2318 sub add_autofile ($$$) {
2321 my $generator=shift;
2323 $autofiles{$file}{plugin}=$plugin;
2324 $autofiles{$file}{generator}=$generator;
2328 return LWP::UserAgent->new(
2329 cookie_jar => $config{cookiejar},
2330 env_proxy => 1, # respect proxy env vars
2331 agent => $config{useragent},
2335 sub sortspec_translate ($$) {
2337 my $reverse = shift;
2343 (-?) # group 1: perhaps negated
2346 \w+\([^\)]*\) # command(params)
2348 [^\s]+ # or anything else
2356 if ($word =~ m/^(\w+)\((.*)\)$/) {
2357 # command with parameters
2361 elsif ($word !~ m/^\w+$/) {
2362 error(sprintf(gettext("invalid sort type %s"), $word));
2373 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2374 if (defined $params) {
2375 push @data, $params;
2376 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2379 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2383 error(sprintf(gettext("unknown sort type %s"), $word));
2387 if (! length $code) {
2388 # undefined sorting method... sort arbitrarily
2397 return eval 'sub { '.$code.' }';
2400 sub pagespec_translate ($) {
2403 # Convert spec to perl code.
2407 \s* # ignore whitespace
2408 ( # 1: match a single word
2415 \w+\([^\)]*\) # command(params)
2417 [^\s()]+ # any other text
2419 \s* # ignore whitespace
2422 if (lc $word eq 'and') {
2425 elsif (lc $word eq 'or') {
2428 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2431 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2432 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2434 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2437 push @data, qq{unknown function in pagespec "$word"};
2438 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2443 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2447 if (! length $code) {
2448 $code="IkiWiki::FailReason->new('empty pagespec')";
2452 return eval 'sub { my $page=shift; '.$code.' }';
2455 sub pagespec_match ($$;@) {
2460 # Backwards compatability with old calling convention.
2462 unshift @params, 'location';
2465 my $sub=pagespec_translate($spec);
2466 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2468 return $sub->($page, @params);
2471 sub pagespec_match_list ($$;@) {
2476 # Backwards compatability with old calling convention.
2478 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2479 $params{list}=$page;
2480 $page=$params{location}; # ugh!
2483 my $sub=pagespec_translate($pagespec);
2484 error "syntax error in pagespec \"$pagespec\""
2486 my $sort=sortspec_translate($params{sort}, $params{reverse})
2487 if defined $params{sort};
2490 if (exists $params{list}) {
2491 @candidates=exists $params{filter}
2492 ? grep { ! $params{filter}->($_) } @{$params{list}}
2496 @candidates=exists $params{filter}
2497 ? grep { ! $params{filter}->($_) } keys %pagesources
2498 : keys %pagesources;
2501 # clear params, remainder is passed to pagespec
2502 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2503 my $num=$params{num};
2504 delete @params{qw{num deptype reverse sort filter list}};
2506 # when only the top matches will be returned, it's efficient to
2507 # sort before matching to pagespec,
2508 if (defined $num && defined $sort) {
2509 @candidates=IkiWiki::SortSpec::sort_pages(
2510 $sort, @candidates);
2516 my $accum=IkiWiki::SuccessReason->new();
2517 foreach my $p (@candidates) {
2518 my $r=$sub->($p, %params, location => $page);
2519 error(sprintf(gettext("cannot match pages: %s"), $r))
2520 if $r->isa("IkiWiki::ErrorReason");
2521 unless ($r || $r->influences_static) {
2522 $r->remove_influence($p);
2527 last if defined $num && ++$count == $num;
2531 # Add simple dependencies for accumulated influences.
2532 my $i=$accum->influences;
2533 foreach my $k (keys %$i) {
2534 $depends_simple{$page}{lc $k} |= $i->{$k};
2537 # when all matches will be returned, it's efficient to
2538 # sort after matching
2539 if (! defined $num && defined $sort) {
2540 return IkiWiki::SortSpec::sort_pages(
2548 sub pagespec_valid ($) {
2551 return defined pagespec_translate($spec);
2555 my $re=quotemeta(shift);
2561 package IkiWiki::FailReason;
2564 '""' => sub { $_[0][0] },
2566 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2567 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2568 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2572 our @ISA = 'IkiWiki::SuccessReason';
2574 package IkiWiki::SuccessReason;
2577 '""' => sub { $_[0][0] },
2579 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2580 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2581 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2588 return bless [$value, {@_}], $class;
2593 $this->[1]={@_} if @_;
2594 my %i=%{$this->[1]};
2599 sub influences_static {
2600 return ! $_[0][1]->{""};
2603 sub merge_influences {
2608 if (! $anded || (($this || %{$this->[1]}) &&
2609 ($other || %{$other->[1]}))) {
2610 foreach my $influence (keys %{$other->[1]}) {
2611 $this->[1]{$influence} |= $other->[1]{$influence};
2620 sub remove_influence {
2624 delete $this->[1]{$torm};
2627 package IkiWiki::ErrorReason;
2629 our @ISA = 'IkiWiki::FailReason';
2631 package IkiWiki::PageSpec;
2637 if ($path =~ m!^\.(/|$)!) {
2639 $from=~s#/?[^/]+$## if defined $from;
2641 $path="$from/$path" if defined $from && length $from;
2645 $path = "" unless defined $path;
2654 sub match_glob ($$;@) {
2659 $glob=derel($glob, $params{location});
2661 # Instead of converting the glob to a regex every time,
2662 # cache the compiled regex to save time.
2663 my $re=$glob_cache{$glob};
2664 unless (defined $re) {
2665 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2668 if (! IkiWiki::isinternal($page) || $params{internal}) {
2669 return IkiWiki::SuccessReason->new("$glob matches $page");
2672 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2676 return IkiWiki::FailReason->new("$glob does not match $page");
2680 sub match_internal ($$;@) {
2681 return match_glob(shift, shift, @_, internal => 1)
2684 sub match_page ($$;@) {
2686 my $match=match_glob($page, shift, @_);
2688 my $source=exists $IkiWiki::pagesources{$page} ?
2689 $IkiWiki::pagesources{$page} :
2690 $IkiWiki::delpagesources{$page};
2691 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2692 if (! defined $type) {
2693 return IkiWiki::FailReason->new("$page is not a page");
2699 sub match_link ($$;@) {
2704 $link=derel($link, $params{location});
2705 my $from=exists $params{location} ? $params{location} : '';
2706 my $linktype=$params{linktype};
2708 if (defined $linktype) {
2709 $qualifier=" with type $linktype";
2712 my $links = $IkiWiki::links{$page};
2713 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2714 unless $links && @{$links};
2715 my $bestlink = IkiWiki::bestlink($from, $link);
2716 foreach my $p (@{$links}) {
2717 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2719 if (length $bestlink) {
2720 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2721 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2725 if (match_glob($p, $link, %params)) {
2726 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2728 my ($p_rel)=$p=~/^\/?(.*)/;
2730 if (match_glob($p_rel, $link, %params)) {
2731 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2735 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2738 sub match_backlink ($$;@) {
2742 if ($testpage eq '.') {
2743 $testpage = $params{'location'}
2745 my $ret=match_link($testpage, $page, @_);
2746 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2750 sub match_created_before ($$;@) {
2755 $testpage=derel($testpage, $params{location});
2757 if (exists $IkiWiki::pagectime{$testpage}) {
2758 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2759 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2762 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2766 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2770 sub match_created_after ($$;@) {
2775 $testpage=derel($testpage, $params{location});
2777 if (exists $IkiWiki::pagectime{$testpage}) {
2778 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2779 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2782 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2786 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2790 sub match_creation_day ($$;@) {
2793 if ($d !~ /^\d+$/) {
2794 return IkiWiki::ErrorReason->new("invalid day $d");
2796 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2797 return IkiWiki::SuccessReason->new('creation_day matched');
2800 return IkiWiki::FailReason->new('creation_day did not match');
2804 sub match_creation_month ($$;@) {
2807 if ($m !~ /^\d+$/) {
2808 return IkiWiki::ErrorReason->new("invalid month $m");
2810 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2811 return IkiWiki::SuccessReason->new('creation_month matched');
2814 return IkiWiki::FailReason->new('creation_month did not match');
2818 sub match_creation_year ($$;@) {
2821 if ($y !~ /^\d+$/) {
2822 return IkiWiki::ErrorReason->new("invalid year $y");
2824 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2825 return IkiWiki::SuccessReason->new('creation_year matched');
2828 return IkiWiki::FailReason->new('creation_year did not match');
2832 sub match_user ($$;@) {
2837 if (! exists $params{user}) {
2838 return IkiWiki::ErrorReason->new("no user specified");
2841 my $regexp=IkiWiki::glob2re($user);
2843 if (defined $params{user} && $params{user}=~$regexp) {
2844 return IkiWiki::SuccessReason->new("user is $user");
2846 elsif (! defined $params{user}) {
2847 return IkiWiki::FailReason->new("not logged in");
2850 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2854 sub match_admin ($$;@) {
2859 if (! exists $params{user}) {
2860 return IkiWiki::ErrorReason->new("no user specified");
2863 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2864 return IkiWiki::SuccessReason->new("user is an admin");
2866 elsif (! defined $params{user}) {
2867 return IkiWiki::FailReason->new("not logged in");
2870 return IkiWiki::FailReason->new("user is not an admin");
2874 sub match_ip ($$;@) {
2879 if (! exists $params{ip}) {
2880 return IkiWiki::ErrorReason->new("no IP specified");
2883 my $regexp=IkiWiki::glob2re(lc $ip);
2885 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2886 return IkiWiki::SuccessReason->new("IP is $ip");
2889 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2893 package IkiWiki::SortSpec;
2895 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2896 # are easily available in this namespace, for cmp functions to use them.
2903 IkiWiki::pagetitle(IkiWiki::basename($a))
2905 IkiWiki::pagetitle(IkiWiki::basename($b))
2908 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2909 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2910 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }