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}],
156 description => "plugins to enable by default",
163 description => "plugins to add to the default configuration",
170 description => "plugins to disable",
176 default => "$installdir/share/ikiwiki/templates",
177 description => "additional directory to search for template files",
184 default => "$installdir/share/ikiwiki/basewiki",
185 description => "base wiki source location",
192 default => "$installdir/share/ikiwiki",
193 description => "parent directory containing additional underlays",
200 description => "wrappers to generate",
207 description => "additional underlays to use",
214 description => "display verbose messages?",
221 description => "log to syslog?",
228 description => "create output files named page/index.html?",
229 safe => 0, # changing requires manual transition
232 prefix_directives => {
235 description => "use '!'-prefixed preprocessor directives?",
236 safe => 0, # changing requires manual transition
242 description => "use page/index.mdwn source files",
249 description => "enable Discussion pages?",
255 default => gettext("Discussion"),
256 description => "name of Discussion pages",
263 description => "generate HTML5?",
271 description => "only send cookies over SSL connections?",
279 description => "extension to use for new pages",
280 safe => 0, # not sanitized
286 description => "extension to use for html files",
287 safe => 0, # not sanitized
293 description => "strftime format string to display date",
301 example => "en_US.UTF-8",
302 description => "UTF-8 locale to use",
311 description => "put user pages below specified page",
318 description => "how many backlinks to show before hiding excess (0 to show all)",
325 description => "attempt to hardlink source files? (optimisation for large files)",
327 safe => 0, # paranoia
333 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
335 safe => 0, # paranoia
340 example => "ikiwiki",
341 description => "group for wrappers to run in",
343 safe => 0, # paranoia
349 example => "$ENV{HOME}/.ikiwiki/",
350 description => "extra library and plugin directory",
352 safe => 0, # directory
358 description => "environment variables",
359 safe => 0, # paranoia
365 example => "US/Eastern",
366 description => "time zone name",
373 example => '^\.htaccess$',
374 description => "regexp of normally excluded files to include",
382 example => '^(*\.private|Makefile)$',
383 description => "regexp of files that should be skipped",
388 wiki_file_prune_regexps => {
390 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
391 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
392 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
393 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
394 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
395 description => "regexps of source files to ignore",
401 description => "specifies the characters that are allowed in source filenames",
402 default => "-[:alnum:]+/.:_",
406 wiki_file_regexp => {
408 description => "regexp of legal source files",
412 web_commit_regexp => {
414 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
415 description => "regexp to parse web commits from logs",
422 description => "run as a cgi",
426 cgi_disable_uploads => {
429 description => "whether CGI should accept file uploads",
436 description => "run as a post-commit hook",
443 description => "running in rebuild mode",
450 description => "running in setup mode",
457 description => "running in clean mode",
464 description => "running in refresh mode",
471 description => "running in receive test mode",
475 wrapper_background_command => {
478 description => "background shell command to run",
484 description => "running in gettime mode",
491 description => "running in w3mmode",
498 description => "path to the .ikiwiki directory holding ikiwiki state",
505 description => "path to setup file",
512 description => "perl class to use to dump setup file",
516 allow_symlinks_before_srcdir => {
519 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
525 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
526 description => "cookie control",
527 safe => 0, # hooks into perl module internals
533 example => "Wget/1.13.4 (linux-gnu)",
534 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
540 sub defaultconfig () {
543 foreach my $key (keys %s) {
544 push @ret, $key, $s{$key}->{default};
549 # URL to top of wiki as a path starting with /, valid from any wiki page or
550 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
552 # URL to CGI script, similar to $local_url
556 # locale stuff; avoid LC_ALL since it overrides everything
557 if (defined $ENV{LC_ALL}) {
558 $ENV{LANG} = $ENV{LC_ALL};
561 if (defined $config{locale}) {
562 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
563 $ENV{LANG}=$config{locale};
568 if (! defined $config{wiki_file_regexp}) {
569 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
572 if (ref $config{ENV} eq 'HASH') {
573 foreach my $val (keys %{$config{ENV}}) {
574 $ENV{$val}=$config{ENV}{$val};
577 if (defined $config{timezone} && length $config{timezone}) {
578 $ENV{TZ}=$config{timezone};
581 $config{timezone}=$ENV{TZ};
584 if ($config{w3mmode}) {
585 eval q{use Cwd q{abs_path}};
587 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
588 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
589 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
590 unless $config{cgiurl} =~ m!file:///!;
591 $config{url}="file://".$config{destdir};
594 if ($config{cgi} && ! length $config{url}) {
595 error(gettext("Must specify url to wiki with --url when using --cgi"));
598 if (defined $config{url} && length $config{url}) {
600 my $baseurl = URI->new($config{url});
602 $local_url = $baseurl->path . "/";
603 $local_cgiurl = undef;
605 if (length $config{cgiurl}) {
606 my $cgiurl = URI->new($config{cgiurl});
608 $local_cgiurl = $cgiurl->path;
610 if ($cgiurl->scheme ne $baseurl->scheme or
611 $cgiurl->authority ne $baseurl->authority) {
612 # too far apart, fall back to absolute URLs
613 $local_url = "$config{url}/";
614 $local_cgiurl = $config{cgiurl};
618 $local_url =~ s{//$}{/};
621 $local_cgiurl = $config{cgiurl};
624 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
625 unless exists $config{wikistatedir} && defined $config{wikistatedir};
627 if (defined $config{umask}) {
628 my $u = possibly_foolish_untaint($config{umask});
630 if ($u =~ m/^\d+$/) {
633 elsif ($u eq 'private') {
636 elsif ($u eq 'group') {
639 elsif ($u eq 'public') {
643 error(sprintf(gettext("unsupported umask setting %s"), $u));
647 run_hooks(checkconfig => sub { shift->() });
655 foreach my $dir (@INC, $config{libdir}) {
656 next unless defined $dir && length $dir;
657 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
658 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
662 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
663 next unless defined $dir && length $dir;
664 foreach my $file (glob("$dir/plugins/*")) {
665 $ret{basename($file)}=1 if -x $file;
673 if (defined $config{libdir} && length $config{libdir}) {
674 unshift @INC, possibly_foolish_untaint($config{libdir});
677 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
682 if (exists $hooks{rcs}) {
683 error(gettext("cannot use multiple rcs plugins"));
685 loadplugin($config{rcs});
687 if (! exists $hooks{rcs}) {
691 run_hooks(getopt => sub { shift->() });
692 if (grep /^-/, @ARGV) {
693 print STDERR "Unknown option (or missing parameter): $_\n"
694 foreach grep /^-/, @ARGV;
701 sub loadplugin ($;$) {
705 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
707 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
708 "$installdir/lib/ikiwiki") {
709 if (defined $dir && -x "$dir/plugins/$plugin") {
710 eval { require IkiWiki::Plugin::external };
713 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
715 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
716 $loaded_plugins{$plugin}=1;
721 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
724 error("Failed to load plugin $mod: $@");
726 $loaded_plugins{$plugin}=1;
733 log_message('err' => $message) if $config{syslog};
734 if (defined $cleaner) {
741 return unless $config{verbose};
742 return log_message(debug => @_);
747 sub log_message ($$) {
750 if ($config{syslog}) {
753 Sys::Syslog::setlogsock('unix');
754 Sys::Syslog::openlog('ikiwiki', '', 'user');
758 # keep a copy to avoid editing the original config repeatedly
759 my $wikiname = $config{wikiname};
760 utf8::encode($wikiname);
761 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
764 print STDERR "failed to syslog: $@" unless $log_failed;
770 elsif (! $config{cgi}) {
774 return print STDERR "@_\n";
778 sub possibly_foolish_untaint ($) {
780 my ($untainted)=$tainted=~/(.*)/s;
800 return exists $pagesources{$page} &&
801 $pagesources{$page} =~ /\._([^.]+)$/;
807 if ($file =~ /\.([^.]+)$/) {
808 return $1 if exists $hooks{htmlize}{$1};
810 my $base=basename($file);
811 if (exists $hooks{htmlize}{$base} &&
812 $hooks{htmlize}{$base}{noextension}) {
823 if (exists $pagename_cache{$file}) {
824 return $pagename_cache{$file};
827 my $type=pagetype($file);
829 $page=~s/\Q.$type\E*$//
830 if defined $type && !$hooks{htmlize}{$type}{keepextension}
831 && !$hooks{htmlize}{$type}{noextension};
832 if ($config{indexpages} && $page=~/(.*)\/index$/) {
836 $pagename_cache{$file} = $page;
840 sub newpagefile ($$) {
844 if (! $config{indexpages} || $page eq 'index') {
845 return $page.".".$type;
848 return $page."/index.".$type;
852 sub targetpage ($$;$) {
857 if (defined $filename) {
858 return $page."/".$filename.".".$ext;
860 elsif (! $config{usedirs} || $page eq 'index') {
861 return $page.".".$ext;
864 return $page."/index.".$ext;
871 return targetpage($page, $config{htmlext});
878 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
879 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
880 return "$dir/$file", stat(_) if -e "$dir/$file";
882 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
887 return (srcfile_stat(@_))[0];
890 sub add_literal_underlay ($) {
893 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
894 unshift @{$config{underlaydirs}}, $dir;
898 sub add_underlay ($) {
902 $dir="$config{underlaydirbase}/$dir";
905 add_literal_underlay($dir);
906 # why does it return 1? we just don't know
910 sub readfile ($;$$) {
916 error("cannot read a symlink ($file)");
920 open (my $in, "<", $file) || error("failed to read $file: $!");
921 binmode($in) if ($binary);
922 return \*$in if $wantfd;
924 # check for invalid utf-8, and toss it back to avoid crashes
925 if (! utf8::valid($ret)) {
926 $ret=encode_utf8($ret);
928 close $in || error("failed to read $file: $!");
932 sub prep_writefile ($$) {
937 while (length $test) {
938 if (-l "$destdir/$test") {
939 error("cannot write to a symlink ($test)");
941 if (-f _ && $test ne $file) {
942 # Remove conflicting file.
943 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
944 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
946 unlink("$destdir/$test");
952 $test=dirname($test);
955 my $dir=dirname("$destdir/$file");
958 foreach my $s (split(m!/+!, $dir)) {
961 mkdir($d) || error("failed to create directory $d: $!");
969 sub writefile ($$$;$$) {
970 my $file=shift; # can include subdirs
971 my $destdir=shift; # directory to put file in
976 prep_writefile($file, $destdir);
978 my $newfile="$destdir/$file.ikiwiki-new";
980 error("cannot write to a symlink ($newfile)");
983 my $cleanup = sub { unlink($newfile) };
984 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
985 binmode($out) if ($binary);
987 $writer->(\*$out, $cleanup);
990 print $out $content or error("failed writing to $newfile: $!", $cleanup);
992 close $out || error("failed saving $newfile: $!", $cleanup);
993 rename($newfile, "$destdir/$file") ||
994 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1000 sub will_render ($$;$) {
1005 # Important security check for independently created files.
1006 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1007 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1008 my $from_other_page=0;
1009 # Expensive, but rarely runs.
1010 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1013 dirname($_) eq $dest
1014 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1020 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1021 unless $from_other_page;
1024 # If $dest exists as a directory, remove conflicting files in it
1025 # rendered from other pages.
1027 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1028 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1029 if (dirname($f) eq $dest) {
1030 unlink("$config{destdir}/$f");
1031 rmdir(dirname("$config{destdir}/$f"));
1037 if (! $clear || $cleared{$page}) {
1038 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1041 foreach my $old (@{$renderedfiles{$page}}) {
1042 delete $destsources{$old};
1044 $renderedfiles{$page}=[$dest];
1047 $destsources{$dest}=$page;
1057 if ($link=~s/^\/+//) {
1065 $l.="/" if length $l;
1068 if (exists $pagesources{$l}) {
1071 elsif (exists $pagecase{lc $l}) {
1072 return $pagecase{lc $l};
1074 } while $cwd=~s{/?[^/]+$}{};
1076 if (length $config{userdir}) {
1077 my $l = "$config{userdir}/".lc($link);
1078 if (exists $pagesources{$l}) {
1081 elsif (exists $pagecase{lc $l}) {
1082 return $pagecase{lc $l};
1086 #print STDERR "warning: page $page, broken link: $link\n";
1090 sub isinlinableimage ($) {
1093 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1096 sub pagetitle ($;$) {
1098 my $unescaped=shift;
1101 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1104 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1112 # support use w/o %config set
1113 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1114 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1120 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1121 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1128 my $cgiurl=$local_cgiurl;
1130 if (exists $params{cgiurl}) {
1131 $cgiurl=$params{cgiurl};
1132 delete $params{cgiurl};
1140 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1143 sub cgiurl_abs (@) {
1145 URI->new_abs(cgiurl(@_), $config{cgiurl});
1151 return $local_url if ! defined $page;
1153 $page=htmlpage($page);
1155 $page=~s/[^\/]+\//..\//g;
1163 return $url unless defined $urlbase && length $urlbase;
1166 URI->new_abs($url, $urlbase)->as_string;
1170 # Work around very innefficient behavior in File::Spec if abs2rel
1171 # is passed two relative paths. It's much faster if paths are
1172 # absolute! (Debian bug #376658; fixed in debian unstable now)
1177 my $ret=File::Spec->abs2rel($path, $base);
1178 $ret=~s/^// if defined $ret;
1182 sub displaytime ($;$$) {
1183 # Plugins can override this function to mark up the time to
1185 my $time=formattime($_[0], $_[1]);
1186 if ($config{html5}) {
1187 return '<time datetime="'.date_3339($_[0]).'"'.
1188 ($_[2] ? ' pubdate="pubdate"' : '').
1189 '>'.$time.'</time>';
1192 return '<span class="date">'.$time.'</span>';
1196 sub formattime ($;$) {
1197 # Plugins can override this function to format the time.
1200 if (! defined $format) {
1201 $format=$config{timeformat};
1204 return strftime_utf8($format, localtime($time));
1207 my $strftime_encoding;
1209 # strftime doesn't know about encodings, so make sure
1210 # its output is properly treated as utf8.
1211 # Note that this does not handle utf-8 in the format string.
1212 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1213 unless defined $strftime_encoding;
1215 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1216 : POSIX::strftime(@_);
1222 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1223 POSIX::setlocale(&POSIX::LC_TIME, "C");
1224 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1225 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1229 sub beautify_urlpath ($) {
1232 # Ensure url is not an empty link, and if necessary,
1233 # add ./ to avoid colon confusion.
1234 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1238 if ($config{usedirs}) {
1239 $url =~ s!/index.$config{htmlext}$!/!;
1254 if (! $destsources{$to}) {
1259 return $config{url}.beautify_urlpath("/".$to);
1262 if (! defined $from) {
1263 my $u = $local_url || '';
1265 return $u.beautify_urlpath("/".$to);
1268 my $link = abs2rel($to, dirname(htmlpage($from)));
1270 return beautify_urlpath($link);
1273 sub isselflink ($$) {
1274 # Plugins can override this function to support special types
1279 return $page eq $link;
1282 sub htmllink ($$$;@) {
1283 my $lpage=shift; # the page doing the linking
1284 my $page=shift; # the page that will contain the link (different for inline)
1291 if (! $opts{forcesubpage}) {
1292 $bestlink=bestlink($lpage, $link);
1295 $bestlink="$lpage/".lc($link);
1299 if (defined $opts{linktext}) {
1300 $linktext=$opts{linktext};
1303 $linktext=pagetitle(basename($link));
1306 return "<span class=\"selflink\">$linktext</span>"
1307 if length $bestlink && isselflink($page, $bestlink) &&
1308 ! defined $opts{anchor};
1310 if (! $destsources{$bestlink}) {
1311 $bestlink=htmlpage($bestlink);
1313 if (! $destsources{$bestlink}) {
1315 if (length $config{cgiurl}) {
1316 $cgilink = "<a href=\"".
1321 )."\" rel=\"nofollow\">?</a>";
1323 return "<span class=\"createlink\">$cgilink$linktext</span>"
1327 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1328 $bestlink=beautify_urlpath($bestlink);
1330 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1331 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1334 if (defined $opts{anchor}) {
1335 $bestlink.="#".$opts{anchor};
1339 foreach my $attr (qw{rel class title}) {
1340 if (defined $opts{$attr}) {
1341 push @attrs, " $attr=\"$opts{$attr}\"";
1345 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1350 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1353 sub openiduser ($) {
1356 if (defined $user && $user =~ m!^https?://! &&
1357 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1360 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1361 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1364 # backcompat with old version
1365 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1366 $display=$oid->display;
1369 # Convert "user.somehost.com" to "user [somehost.com]"
1370 # (also "user.somehost.co.uk")
1371 if ($display !~ /\[/) {
1372 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1374 # Convert "http://somehost.com/user" to "user [somehost.com]".
1375 # (also "https://somehost.com/user/")
1376 if ($display !~ /\[/) {
1377 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1379 $display=~s!^https?://!!; # make sure this is removed
1380 eval q{use CGI 'escapeHTML'};
1382 return escapeHTML($display);
1387 sub htmlize ($$$$) {
1393 my $oneline = $content !~ /\n/;
1395 if (exists $hooks{htmlize}{$type}) {
1396 $content=$hooks{htmlize}{$type}{call}->(
1398 content => $content,
1402 error("htmlization of $type not supported");
1405 run_hooks(sanitize => sub {
1408 destpage => $destpage,
1409 content => $content,
1414 # hack to get rid of enclosing junk added by markdown
1415 # and other htmlizers/sanitizers
1416 $content=~s/^<p>//i;
1417 $content=~s/<\/p>\n*$//i;
1428 run_hooks(linkify => sub {
1431 destpage => $destpage,
1432 content => $content,
1440 our $preprocess_preview=0;
1441 sub preprocess ($$$;$$) {
1442 my $page=shift; # the page the data comes from
1443 my $destpage=shift; # the page the data will appear in (different for inline)
1448 # Using local because it needs to be set within any nested calls
1450 local $preprocess_preview=$preview if defined $preview;
1457 $params="" if ! defined $params;
1459 if (length $escape) {
1460 return "[[$prefix$command $params]]";
1462 elsif (exists $hooks{preprocess}{$command}) {
1463 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1464 # Note: preserve order of params, some plugins may
1465 # consider it significant.
1467 while ($params =~ m{
1468 (?:([-.\w]+)=)? # 1: named parameter key?
1470 """(.*?)""" # 2: triple-quoted value
1472 "([^"]*?)" # 3: single-quoted value
1474 '''(.*?)''' # 4: triple-single-quote
1476 <<([a-zA-Z]+)\n # 5: heredoc start
1477 (.*?)\n\5 # 6: heredoc value
1479 (\S+) # 7: unquoted value
1481 (?:\s+|$) # delimiter to next param
1491 elsif (defined $3) {
1494 elsif (defined $4) {
1497 elsif (defined $7) {
1500 elsif (defined $6) {
1505 push @params, $key, $val;
1508 push @params, $val, '';
1511 if ($preprocessing{$page}++ > 8) {
1512 # Avoid loops of preprocessed pages preprocessing
1513 # other pages that preprocess them, etc.
1514 return "[[!$command <span class=\"error\">".
1515 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1516 $page, $preprocessing{$page}).
1522 $hooks{preprocess}{$command}{call}->(
1525 destpage => $destpage,
1526 preview => $preprocess_preview,
1532 $ret="[[!$command <span class=\"error\">".
1533 gettext("Error").": $error"."</span>]]";
1537 # use void context during scan pass
1539 $hooks{preprocess}{$command}{call}->(
1542 destpage => $destpage,
1543 preview => $preprocess_preview,
1548 $preprocessing{$page}--;
1552 return "[[$prefix$command $params]]";
1557 if ($config{prefix_directives}) {
1560 \[\[(!) # directive open; 2: prefix
1561 ([-\w]+) # 3: command
1562 ( # 4: the parameters..
1563 \s+ # Must have space if parameters present
1565 (?:[-.\w]+=)? # named parameter key?
1567 """.*?""" # triple-quoted value
1569 "[^"]*?" # single-quoted value
1571 '''.*?''' # triple-single-quote
1573 <<([a-zA-Z]+)\n # 5: heredoc start
1574 (?:.*?)\n\5 # heredoc value
1576 [^"\s\]]+ # unquoted value
1578 \s* # whitespace or end
1581 *)? # 0 or more parameters
1582 \]\] # directive closed
1588 \[\[(!?) # directive open; 2: optional prefix
1589 ([-\w]+) # 3: command
1591 ( # 4: the parameters..
1593 (?:[-.\w]+=)? # named parameter key?
1595 """.*?""" # triple-quoted value
1597 "[^"]*?" # single-quoted value
1599 '''.*?''' # triple-single-quote
1601 <<([a-zA-Z]+)\n # 5: heredoc start
1602 (?:.*?)\n\5 # heredoc value
1604 [^"\s\]]+ # unquoted value
1606 \s* # whitespace or end
1609 *) # 0 or more parameters
1610 \]\] # directive closed
1614 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1623 run_hooks(filter => sub {
1624 $content=shift->(page => $page, destpage => $destpage,
1625 content => $content);
1631 sub check_canedit ($$$;$) {
1638 run_hooks(canedit => sub {
1639 return if defined $canedit;
1640 my $ret=shift->($page, $q, $session);
1645 elsif (ref $ret eq 'CODE') {
1646 $ret->() unless $nonfatal;
1649 elsif (defined $ret) {
1650 error($ret) unless $nonfatal;
1655 return defined $canedit ? $canedit : 1;
1658 sub check_content (@) {
1661 return 1 if ! exists $hooks{checkcontent}; # optimisation
1663 if (exists $pagesources{$params{page}}) {
1665 my %old=map { $_ => 1 }
1666 split("\n", readfile(srcfile($pagesources{$params{page}})));
1667 foreach my $line (split("\n", $params{content})) {
1668 push @diff, $line if ! exists $old{$line};
1670 $params{diff}=join("\n", @diff);
1674 run_hooks(checkcontent => sub {
1675 return if defined $ok;
1676 my $ret=shift->(%params);
1681 elsif (ref $ret eq 'CODE') {
1682 $ret->() unless $params{nonfatal};
1685 elsif (defined $ret) {
1686 error($ret) unless $params{nonfatal};
1692 return defined $ok ? $ok : 1;
1695 sub check_canchange (@) {
1697 my $cgi = $params{cgi};
1698 my $session = $params{session};
1699 my @changes = @{$params{changes}};
1702 foreach my $change (@changes) {
1703 # This untaint is safe because we check file_pruned and
1705 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1706 $file=possibly_foolish_untaint($file);
1707 if (! defined $file || ! length $file ||
1708 file_pruned($file)) {
1709 error(gettext("bad file name %s"), $file);
1712 my $type=pagetype($file);
1713 my $page=pagename($file) if defined $type;
1715 if ($change->{action} eq 'add') {
1719 if ($change->{action} eq 'change' ||
1720 $change->{action} eq 'add') {
1721 if (defined $page) {
1722 check_canedit($page, $cgi, $session);
1726 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1727 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1728 check_canedit($file, $cgi, $session);
1733 elsif ($change->{action} eq 'remove') {
1734 # check_canremove tests to see if the file is present
1735 # on disk. This will fail when a single commit adds a
1736 # file and then removes it again. Avoid the problem
1737 # by not testing the removal in such pairs of changes.
1738 # (The add is still tested, just to make sure that
1739 # no data is added to the repo that a web edit
1741 next if $newfiles{$file};
1743 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1744 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1745 check_canedit(defined $page ? $page : $file, $cgi, $session);
1750 error "unknown action ".$change->{action};
1753 error sprintf(gettext("you are not allowed to change %s"), $file);
1761 # Take an exclusive lock on the wiki to prevent multiple concurrent
1762 # run issues. The lock will be dropped on program exit.
1763 if (! -d $config{wikistatedir}) {
1764 mkdir($config{wikistatedir});
1766 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1767 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1768 if (! flock($wikilock, 2)) { # LOCK_EX
1769 error("failed to get lock");
1775 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1776 return close($wikilock) if $wikilock;
1782 sub commit_hook_enabled () {
1783 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1784 error("cannot write to $config{wikistatedir}/commitlock: $!");
1785 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1786 close($commitlock) || error("failed closing commitlock: $!");
1789 close($commitlock) || error("failed closing commitlock: $!");
1793 sub disable_commit_hook () {
1794 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1795 error("cannot write to $config{wikistatedir}/commitlock: $!");
1796 if (! flock($commitlock, 2)) { # LOCK_EX
1797 error("failed to get commit lock");
1802 sub enable_commit_hook () {
1803 return close($commitlock) if $commitlock;
1808 %oldrenderedfiles=%pagectime=();
1809 my $rebuild=$config{rebuild};
1811 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1812 %destsources=%renderedfiles=%pagecase=%pagestate=
1813 %depends_simple=%typedlinks=%oldtypedlinks=();
1816 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1817 if (-e "$config{wikistatedir}/index") {
1818 system("ikiwiki-transition", "indexdb", $config{srcdir});
1819 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1822 # gettime on first build
1823 $config{gettime}=1 unless defined $config{gettime};
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});
2031 loop_context_vars => 1,
2032 die_on_bad_params => 0,
2033 parent_global_vars => 1,
2034 filename => $filename,
2036 ($untrusted ? (no_includes => 1) : ()),
2038 return @opts if wantarray;
2040 require HTML::Template;
2041 return HTML::Template->new(@opts);
2044 sub template ($;@) {
2045 template_depends(shift, undef, @_);
2048 sub templateactions ($$) {
2054 run_hooks(pageactions => sub {
2055 push @actions, map { { action => $_ } }
2056 grep { defined } shift->(page => $page);
2058 $template->param(actions => \@actions);
2060 if ($config{cgiurl} && exists $hooks{auth}) {
2061 $template->param(prefsurl => cgiurl(do => "prefs"));
2065 if ($have_actions || @actions) {
2066 $template->param(have_actions => 1);
2073 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2074 error 'hook requires type, call, and id parameters';
2077 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2079 $hooks{$param{type}}{$param{id}}=\%param;
2083 sub run_hooks ($$) {
2084 # Calls the given sub for each hook of the given type,
2085 # passing it the hook function to call.
2089 if (exists $hooks{$type}) {
2090 my (@first, @middle, @last);
2091 foreach my $id (keys %{$hooks{$type}}) {
2092 if ($hooks{$type}{$id}{first}) {
2095 elsif ($hooks{$type}{$id}{last}) {
2102 foreach my $id (@first, @middle, @last) {
2103 $sub->($hooks{$type}{$id}{call});
2111 $hooks{rcs}{rcs_update}{call}->(@_);
2114 sub rcs_prepedit ($) {
2115 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2118 sub rcs_commit (@) {
2119 $hooks{rcs}{rcs_commit}{call}->(@_);
2122 sub rcs_commit_staged (@) {
2123 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2127 $hooks{rcs}{rcs_add}{call}->(@_);
2130 sub rcs_remove ($) {
2131 $hooks{rcs}{rcs_remove}{call}->(@_);
2134 sub rcs_rename ($$) {
2135 $hooks{rcs}{rcs_rename}{call}->(@_);
2138 sub rcs_recentchanges ($) {
2139 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2142 sub rcs_diff ($;$) {
2143 $hooks{rcs}{rcs_diff}{call}->(@_);
2146 sub rcs_getctime ($) {
2147 $hooks{rcs}{rcs_getctime}{call}->(@_);
2150 sub rcs_getmtime ($) {
2151 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2154 sub rcs_receive () {
2155 $hooks{rcs}{rcs_receive}{call}->();
2158 sub add_depends ($$;$) {
2161 my $deptype=shift || $DEPEND_CONTENT;
2163 # Is the pagespec a simple page name?
2164 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2165 $pagespec !~ /[\s*?()!]/) {
2166 $depends_simple{$page}{lc $pagespec} |= $deptype;
2170 # Add explicit dependencies for influences.
2171 my $sub=pagespec_translate($pagespec);
2172 return unless defined $sub;
2173 foreach my $p (keys %pagesources) {
2174 my $r=$sub->($p, location => $page);
2175 my $i=$r->influences;
2176 my $static=$r->influences_static;
2177 foreach my $k (keys %$i) {
2178 next unless $r || $static || $k eq $page;
2179 $depends_simple{$page}{lc $k} |= $i->{$k};
2184 $depends{$page}{$pagespec} |= $deptype;
2190 foreach my $type (@_) {
2191 if ($type eq 'presence') {
2192 $deptype |= $DEPEND_PRESENCE;
2194 elsif ($type eq 'links') {
2195 $deptype |= $DEPEND_LINKS;
2197 elsif ($type eq 'content') {
2198 $deptype |= $DEPEND_CONTENT;
2204 my $file_prune_regexp;
2205 sub file_pruned ($) {
2208 if (defined $config{include} && length $config{include}) {
2209 return 0 if $file =~ m/$config{include}/;
2212 if (! defined $file_prune_regexp) {
2213 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2214 $file_prune_regexp=qr/$file_prune_regexp/;
2216 return $file =~ m/$file_prune_regexp/;
2219 sub define_gettext () {
2220 # If translation is needed, redefine the gettext function to do it.
2221 # Otherwise, it becomes a quick no-op.
2224 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2225 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2226 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2228 $gettext_obj=eval q{
2229 use Locale::gettext q{textdomain};
2230 Locale::gettext->domain('ikiwiki')
2235 no warnings 'redefine';
2237 $getobj->() if $getobj;
2239 $gettext_obj->get(shift);
2246 $getobj->() if $getobj;
2248 $gettext_obj->nget(@_);
2251 return ($_[2] == 1 ? $_[0] : $_[1])
2269 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2273 # Injects a new function into the symbol table to replace an
2274 # exported function.
2277 # This is deep ugly perl foo, beware.
2280 if (! defined $params{parent}) {
2281 $params{parent}='::';
2282 $params{old}=\&{$params{name}};
2283 $params{name}=~s/.*:://;
2285 my $parent=$params{parent};
2286 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2287 $ns = $params{parent} . $ns;
2288 inject(%params, parent => $ns) unless $ns eq '::main::';
2289 *{$ns . $params{name}} = $params{call}
2290 if exists ${$ns}{$params{name}} &&
2291 \&{${$ns}{$params{name}}} == $params{old};
2297 sub add_link ($$;$) {
2302 push @{$links{$page}}, $link
2303 unless grep { $_ eq $link } @{$links{$page}};
2305 if (defined $type) {
2306 $typedlinks{$page}{$type}{$link} = 1;
2310 sub add_autofile ($$$) {
2313 my $generator=shift;
2315 $autofiles{$file}{plugin}=$plugin;
2316 $autofiles{$file}{generator}=$generator;
2320 return LWP::UserAgent->new(
2321 cookie_jar => $config{cookiejar},
2322 env_proxy => 1, # respect proxy env vars
2323 agent => $config{useragent},
2327 sub sortspec_translate ($$) {
2329 my $reverse = shift;
2335 (-?) # group 1: perhaps negated
2338 \w+\([^\)]*\) # command(params)
2340 [^\s]+ # or anything else
2348 if ($word =~ m/^(\w+)\((.*)\)$/) {
2349 # command with parameters
2353 elsif ($word !~ m/^\w+$/) {
2354 error(sprintf(gettext("invalid sort type %s"), $word));
2365 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2366 if (defined $params) {
2367 push @data, $params;
2368 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2371 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2375 error(sprintf(gettext("unknown sort type %s"), $word));
2379 if (! length $code) {
2380 # undefined sorting method... sort arbitrarily
2389 return eval 'sub { '.$code.' }';
2392 sub pagespec_translate ($) {
2395 # Convert spec to perl code.
2399 \s* # ignore whitespace
2400 ( # 1: match a single word
2407 \w+\([^\)]*\) # command(params)
2409 [^\s()]+ # any other text
2411 \s* # ignore whitespace
2414 if (lc $word eq 'and') {
2417 elsif (lc $word eq 'or') {
2420 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2423 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2424 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2426 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2429 push @data, qq{unknown function in pagespec "$word"};
2430 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2435 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2439 if (! length $code) {
2440 $code="IkiWiki::FailReason->new('empty pagespec')";
2444 return eval 'sub { my $page=shift; '.$code.' }';
2447 sub pagespec_match ($$;@) {
2452 # Backwards compatability with old calling convention.
2454 unshift @params, 'location';
2457 my $sub=pagespec_translate($spec);
2458 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2460 return $sub->($page, @params);
2463 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2465 # Not exported yet, but could be in future if it is generally useful.
2466 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2467 # which is "more internal".
2468 sub sort_pages ($$;@) {
2472 $sort = sortspec_translate($sort, $params{reverse});
2473 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2476 sub pagespec_match_list ($$;@) {
2481 # Backwards compatability with old calling convention.
2483 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2484 $params{list}=$page;
2485 $page=$params{location}; # ugh!
2488 my $sub=pagespec_translate($pagespec);
2489 error "syntax error in pagespec \"$pagespec\""
2491 my $sort=sortspec_translate($params{sort}, $params{reverse})
2492 if defined $params{sort};
2495 if (exists $params{list}) {
2496 @candidates=exists $params{filter}
2497 ? grep { ! $params{filter}->($_) } @{$params{list}}
2501 @candidates=exists $params{filter}
2502 ? grep { ! $params{filter}->($_) } keys %pagesources
2503 : keys %pagesources;
2506 # clear params, remainder is passed to pagespec
2507 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2508 my $num=$params{num};
2509 delete @params{qw{num deptype reverse sort filter list}};
2511 # when only the top matches will be returned, it's efficient to
2512 # sort before matching to pagespec,
2513 if (defined $num && defined $sort) {
2514 @candidates=IkiWiki::SortSpec::sort_pages(
2515 $sort, @candidates);
2521 my $accum=IkiWiki::SuccessReason->new();
2522 foreach my $p (@candidates) {
2523 my $r=$sub->($p, %params, location => $page);
2524 error(sprintf(gettext("cannot match pages: %s"), $r))
2525 if $r->isa("IkiWiki::ErrorReason");
2526 unless ($r || $r->influences_static) {
2527 $r->remove_influence($p);
2532 last if defined $num && ++$count == $num;
2536 # Add simple dependencies for accumulated influences.
2537 my $i=$accum->influences;
2538 foreach my $k (keys %$i) {
2539 $depends_simple{$page}{lc $k} |= $i->{$k};
2542 # when all matches will be returned, it's efficient to
2543 # sort after matching
2544 if (! defined $num && defined $sort) {
2545 return IkiWiki::SortSpec::sort_pages(
2553 sub pagespec_valid ($) {
2556 return defined pagespec_translate($spec);
2560 my $re=quotemeta(shift);
2566 package IkiWiki::FailReason;
2569 '""' => sub { $_[0][0] },
2571 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2572 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2573 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2577 our @ISA = 'IkiWiki::SuccessReason';
2579 package IkiWiki::SuccessReason;
2581 # A blessed array-ref:
2583 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2585 # - if absent or false, the influences of this evaluation are "static",
2586 # see the influences_static method
2587 # - if true, they are dynamic (not static)
2588 # [1]{any other key}:
2589 # the dependency types of influences, as returned by the influences method
2592 # in string context, it's the human-readable reason
2593 '""' => sub { $_[0][0] },
2594 # in boolean context, SuccessReason is 1 and FailReason is 0
2596 # negating a result gives the opposite result with the same influences
2597 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2598 # A & B = (A ? B : A) with the influences of both
2599 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2600 # A | B = (A ? A : B) with the influences of both
2601 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2605 # SuccessReason->new("human-readable reason", page => deptype, ...)
2610 return bless [$value, {@_}], $class;
2613 # influences(): return a reference to a copy of the hash
2614 # { page => dependency type } describing the pages that indirectly influenced
2615 # this result, but would not cause a dependency through ikiwiki's core
2618 # See [[todo/dependency_types]] for extensive discussion of what this means.
2620 # influences(page => deptype, ...): remove all influences, replace them
2621 # with the arguments, and return a reference to a copy of the new influences.
2625 $this->[1]={@_} if @_;
2626 my %i=%{$this->[1]};
2631 # True if this result has the same influences whichever page it matches,
2632 # For instance, whether bar matches backlink(foo) is influenced only by
2633 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2634 # which does not mention bar anywhere.
2636 # False if this result would have different influences when matching
2637 # different pages. For instance, when testing whether link(foo) matches bar,
2638 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2639 # bar's links could change the outcome; so its influences are not the same
2640 # as when testing whether link(foo) matches baz.
2642 # Static influences are one of the things that make pagespec_match_list
2643 # more efficient than repeated calls to pagespec_match.
2645 sub influences_static {
2646 return ! $_[0][1]->{""};
2649 # Change the influences of $this to be the influences of "$this & $other"
2650 # or "$this | $other".
2652 # If both $this and $other are either successful or have influences,
2653 # or this is an "or" operation, the result has all the influences from
2654 # either of the arguments. It has dynamic influences if either argument
2655 # has dynamic influences.
2657 # If this is an "and" operation, and at least one argument is a
2658 # FailReason with no influences, the result has no influences, and they
2659 # are not dynamic. For instance, link(foo) matching bar is influenced
2660 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2661 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2662 # bar, because it would be false however often you edit bar.
2664 sub merge_influences {
2669 # This "if" is odd because it needs to avoid negating $this
2670 # or $other, which would alter the objects in-place. Be careful.
2671 if (! $anded || (($this || %{$this->[1]}) &&
2672 ($other || %{$other->[1]}))) {
2673 foreach my $influence (keys %{$other->[1]}) {
2674 $this->[1]{$influence} |= $other->[1]{$influence};
2683 # Change $this so it is not considered to be influenced by $torm.
2685 sub remove_influence {
2689 delete $this->[1]{$torm};
2692 package IkiWiki::ErrorReason;
2694 our @ISA = 'IkiWiki::FailReason';
2696 package IkiWiki::PageSpec;
2702 if ($path =~ m!^\.(/|$)!) {
2704 $from=~s#/?[^/]+$## if defined $from;
2706 $path="$from/$path" if defined $from && length $from;
2710 $path = "" unless defined $path;
2719 sub match_glob ($$;@) {
2724 $glob=derel($glob, $params{location});
2726 # Instead of converting the glob to a regex every time,
2727 # cache the compiled regex to save time.
2728 my $re=$glob_cache{$glob};
2729 unless (defined $re) {
2730 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2733 if (! IkiWiki::isinternal($page) || $params{internal}) {
2734 return IkiWiki::SuccessReason->new("$glob matches $page");
2737 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2741 return IkiWiki::FailReason->new("$glob does not match $page");
2745 sub match_internal ($$;@) {
2746 return match_glob(shift, shift, @_, internal => 1)
2749 sub match_page ($$;@) {
2751 my $match=match_glob($page, shift, @_);
2753 my $source=exists $IkiWiki::pagesources{$page} ?
2754 $IkiWiki::pagesources{$page} :
2755 $IkiWiki::delpagesources{$page};
2756 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2757 if (! defined $type) {
2758 return IkiWiki::FailReason->new("$page is not a page");
2764 sub match_link ($$;@) {
2769 $link=derel($link, $params{location});
2770 my $from=exists $params{location} ? $params{location} : '';
2771 my $linktype=$params{linktype};
2773 if (defined $linktype) {
2774 $qualifier=" with type $linktype";
2777 my $links = $IkiWiki::links{$page};
2778 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2779 unless $links && @{$links};
2780 my $bestlink = IkiWiki::bestlink($from, $link);
2781 foreach my $p (@{$links}) {
2782 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2784 if (length $bestlink) {
2785 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2786 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2790 if (match_glob($p, $link, %params)) {
2791 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2793 my ($p_rel)=$p=~/^\/?(.*)/;
2795 if (match_glob($p_rel, $link, %params)) {
2796 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2800 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2803 sub match_backlink ($$;@) {
2807 if ($testpage eq '.') {
2808 $testpage = $params{'location'}
2810 my $ret=match_link($testpage, $page, @_);
2811 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2815 sub match_created_before ($$;@) {
2820 $testpage=derel($testpage, $params{location});
2822 if (exists $IkiWiki::pagectime{$testpage}) {
2823 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2824 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2827 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2831 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2835 sub match_created_after ($$;@) {
2840 $testpage=derel($testpage, $params{location});
2842 if (exists $IkiWiki::pagectime{$testpage}) {
2843 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2844 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2847 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2851 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2855 sub match_creation_day ($$;@) {
2858 if ($d !~ /^\d+$/) {
2859 return IkiWiki::ErrorReason->new("invalid day $d");
2861 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2862 return IkiWiki::SuccessReason->new('creation_day matched');
2865 return IkiWiki::FailReason->new('creation_day did not match');
2869 sub match_creation_month ($$;@) {
2872 if ($m !~ /^\d+$/) {
2873 return IkiWiki::ErrorReason->new("invalid month $m");
2875 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2876 return IkiWiki::SuccessReason->new('creation_month matched');
2879 return IkiWiki::FailReason->new('creation_month did not match');
2883 sub match_creation_year ($$;@) {
2886 if ($y !~ /^\d+$/) {
2887 return IkiWiki::ErrorReason->new("invalid year $y");
2889 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2890 return IkiWiki::SuccessReason->new('creation_year matched');
2893 return IkiWiki::FailReason->new('creation_year did not match');
2897 sub match_user ($$;@) {
2902 if (! exists $params{user}) {
2903 return IkiWiki::ErrorReason->new("no user specified");
2906 my $regexp=IkiWiki::glob2re($user);
2908 if (defined $params{user} && $params{user}=~$regexp) {
2909 return IkiWiki::SuccessReason->new("user is $user");
2911 elsif (! defined $params{user}) {
2912 return IkiWiki::FailReason->new("not logged in");
2915 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2919 sub match_admin ($$;@) {
2924 if (! exists $params{user}) {
2925 return IkiWiki::ErrorReason->new("no user specified");
2928 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2929 return IkiWiki::SuccessReason->new("user is an admin");
2931 elsif (! defined $params{user}) {
2932 return IkiWiki::FailReason->new("not logged in");
2935 return IkiWiki::FailReason->new("user is not an admin");
2939 sub match_ip ($$;@) {
2944 if (! exists $params{ip}) {
2945 return IkiWiki::ErrorReason->new("no IP specified");
2948 my $regexp=IkiWiki::glob2re(lc $ip);
2950 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2951 return IkiWiki::SuccessReason->new("IP is $ip");
2954 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2958 package IkiWiki::SortSpec;
2960 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2961 # are easily available in this namespace, for cmp functions to use them.
2968 IkiWiki::pagetitle(IkiWiki::basename($a))
2970 IkiWiki::pagetitle(IkiWiki::basename($b))
2973 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2974 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2975 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }