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 $phase};
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;
37 # Phases of processing.
38 sub PHASE_SCAN () { 0 }
39 sub PHASE_RENDER () { 1 }
45 memoize("sortspec_translate");
46 memoize("pagespec_translate");
47 memoize("template_file");
53 description => "name of the wiki",
60 example => 'me@example.com',
61 description => "contact email for wiki",
68 description => "users who are wiki admins",
75 description => "users who are banned from the wiki",
82 example => "$ENV{HOME}/wiki",
83 description => "where the source of the wiki is located",
90 example => "/var/www/wiki",
91 description => "where to build the wiki",
98 example => "http://example.com/wiki",
99 description => "base url to the wiki",
106 example => "http://example.com/wiki/ikiwiki.cgi",
107 description => "url to the ikiwiki.cgi",
114 example => "/var/www/wiki/ikiwiki.cgi",
115 description => "filename of cgi wrapper to generate",
122 description => "mode for cgi_wrapper (can safely be made suid)",
126 cgi_overload_delay => {
130 description => "number of seconds to delay CGI requests when overloaded",
134 cgi_overload_message => {
137 example => "Please wait",
138 description => "message to display when overloaded (may contain html)",
142 only_committed_changes => {
145 description => "enable optimization of only refreshing committed changes?",
152 description => "rcs backend to use",
153 safe => 0, # don't allow overriding
158 default => [qw{mdwn link inline meta htmlscrubber passwordauth
159 openid signinedit lockedit conditional
160 recentchanges parentlinks editpage
162 description => "plugins to enable by default",
169 description => "plugins to add to the default configuration",
176 description => "plugins to disable",
182 default => "$installdir/share/ikiwiki/templates",
183 description => "additional directory to search for template files",
190 default => "$installdir/share/ikiwiki/basewiki",
191 description => "base wiki source location",
198 default => "$installdir/share/ikiwiki",
199 description => "parent directory containing additional underlays",
206 description => "wrappers to generate",
213 description => "additional underlays to use",
220 description => "display verbose messages?",
227 description => "log to syslog?",
234 description => "create output files named page/index.html?",
235 safe => 0, # changing requires manual transition
238 prefix_directives => {
241 description => "use '!'-prefixed preprocessor directives?",
242 safe => 0, # changing requires manual transition
248 description => "use page/index.mdwn source files",
255 description => "enable Discussion pages?",
261 default => gettext("Discussion"),
262 description => "name of Discussion pages",
269 description => "generate HTML5?",
277 description => "only send cookies over SSL connections?",
285 description => "extension to use for new pages",
286 safe => 0, # not sanitized
292 description => "extension to use for html files",
293 safe => 0, # not sanitized
299 description => "strftime format string to display date",
307 example => "en_US.UTF-8",
308 description => "UTF-8 locale to use",
317 description => "put user pages below specified page",
324 description => "how many backlinks to show before hiding excess (0 to show all)",
331 description => "attempt to hardlink source files? (optimisation for large files)",
333 safe => 0, # paranoia
339 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
341 safe => 0, # paranoia
346 example => "ikiwiki",
347 description => "group for wrappers to run in",
349 safe => 0, # paranoia
355 example => "$ENV{HOME}/.ikiwiki/",
356 description => "extra library and plugin directory",
358 safe => 0, # directory
364 description => "environment variables",
365 safe => 0, # paranoia
371 example => "US/Eastern",
372 description => "time zone name",
379 example => '^\.htaccess$',
380 description => "regexp of normally excluded files to include",
388 example => '^(*\.private|Makefile)$',
389 description => "regexp of files that should be skipped",
394 wiki_file_prune_regexps => {
396 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
397 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
398 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
399 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
400 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
401 description => "regexps of source files to ignore",
407 description => "specifies the characters that are allowed in source filenames",
408 default => "-[:alnum:]+/.:_",
412 wiki_file_regexp => {
414 description => "regexp of legal source files",
418 web_commit_regexp => {
420 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
421 description => "regexp to parse web commits from logs",
428 description => "run as a cgi",
432 cgi_disable_uploads => {
435 description => "whether CGI should accept file uploads",
442 description => "run as a post-commit hook",
449 description => "running in rebuild mode",
456 description => "running in setup mode",
463 description => "running in clean mode",
470 description => "running in refresh mode",
477 description => "running in receive test mode",
481 wrapper_background_command => {
484 description => "background shell command to run",
490 description => "running in gettime mode",
497 description => "running in w3mmode",
504 description => "path to the .ikiwiki directory holding ikiwiki state",
511 description => "path to setup file",
518 description => "perl class to use to dump setup file",
522 allow_symlinks_before_srcdir => {
525 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
531 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
532 description => "cookie control",
533 safe => 0, # hooks into perl module internals
539 example => "Wget/1.13.4 (linux-gnu)",
540 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
546 sub defaultconfig () {
549 foreach my $key (keys %s) {
550 push @ret, $key, $s{$key}->{default};
555 # URL to top of wiki as a path starting with /, valid from any wiki page or
556 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
558 # URL to CGI script, similar to $local_url
562 # locale stuff; avoid LC_ALL since it overrides everything
563 if (defined $ENV{LC_ALL}) {
564 $ENV{LANG} = $ENV{LC_ALL};
567 if (defined $config{locale}) {
568 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
569 $ENV{LANG}=$config{locale};
574 if (! defined $config{wiki_file_regexp}) {
575 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
578 if (ref $config{ENV} eq 'HASH') {
579 foreach my $val (keys %{$config{ENV}}) {
580 $ENV{$val}=$config{ENV}{$val};
583 if (defined $config{timezone} && length $config{timezone}) {
584 $ENV{TZ}=$config{timezone};
587 $config{timezone}=$ENV{TZ};
590 if ($config{w3mmode}) {
591 eval q{use Cwd q{abs_path}};
593 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
594 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
595 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
596 unless $config{cgiurl} =~ m!file:///!;
597 $config{url}="file://".$config{destdir};
600 if ($config{cgi} && ! length $config{url}) {
601 error(gettext("Must specify url to wiki with --url when using --cgi"));
604 if (defined $config{url} && length $config{url}) {
606 my $baseurl = URI->new($config{url});
608 $local_url = $baseurl->path . "/";
609 $local_cgiurl = undef;
611 if (length $config{cgiurl}) {
612 my $cgiurl = URI->new($config{cgiurl});
614 $local_cgiurl = $cgiurl->path;
616 if ($cgiurl->scheme ne $baseurl->scheme or
617 $cgiurl->authority ne $baseurl->authority) {
618 # too far apart, fall back to absolute URLs
619 $local_url = "$config{url}/";
620 $local_cgiurl = $config{cgiurl};
624 $local_url =~ s{//$}{/};
627 $local_cgiurl = $config{cgiurl};
630 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
631 unless exists $config{wikistatedir} && defined $config{wikistatedir};
633 if (defined $config{umask}) {
634 my $u = possibly_foolish_untaint($config{umask});
636 if ($u =~ m/^\d+$/) {
639 elsif ($u eq 'private') {
642 elsif ($u eq 'group') {
645 elsif ($u eq 'public') {
649 error(sprintf(gettext("unsupported umask setting %s"), $u));
653 run_hooks(checkconfig => sub { shift->() });
661 foreach my $dir (@INC, $config{libdir}) {
662 next unless defined $dir && length $dir;
663 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
664 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
668 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
669 next unless defined $dir && length $dir;
670 foreach my $file (glob("$dir/plugins/*")) {
671 $ret{basename($file)}=1 if -x $file;
679 if (defined $config{libdir} && length $config{libdir}) {
680 unshift @INC, possibly_foolish_untaint($config{libdir});
683 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
688 if (exists $hooks{rcs}) {
689 error(gettext("cannot use multiple rcs plugins"));
691 loadplugin($config{rcs});
693 if (! exists $hooks{rcs}) {
697 run_hooks(getopt => sub { shift->() });
698 if (grep /^-/, @ARGV) {
699 print STDERR "Unknown option (or missing parameter): $_\n"
700 foreach grep /^-/, @ARGV;
707 sub loadplugin ($;$) {
711 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
713 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
714 "$installdir/lib/ikiwiki") {
715 if (defined $dir && -x "$dir/plugins/$plugin") {
716 eval { require IkiWiki::Plugin::external };
719 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
721 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
722 $loaded_plugins{$plugin}=1;
727 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
730 error("Failed to load plugin $mod: $@");
732 $loaded_plugins{$plugin}=1;
739 log_message('err' => $message) if $config{syslog};
740 if (defined $cleaner) {
747 return unless $config{verbose};
748 return log_message(debug => @_);
753 sub log_message ($$) {
756 if ($config{syslog}) {
759 Sys::Syslog::setlogsock('unix');
760 Sys::Syslog::openlog('ikiwiki', '', 'user');
764 # keep a copy to avoid editing the original config repeatedly
765 my $wikiname = $config{wikiname};
766 utf8::encode($wikiname);
767 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
770 print STDERR "failed to syslog: $@" unless $log_failed;
776 elsif (! $config{cgi}) {
780 return print STDERR "@_\n";
784 sub possibly_foolish_untaint ($) {
786 my ($untainted)=$tainted=~/(.*)/s;
806 return exists $pagesources{$page} &&
807 $pagesources{$page} =~ /\._([^.]+)$/;
813 if ($file =~ /\.([^.]+)$/) {
814 return $1 if exists $hooks{htmlize}{$1};
816 my $base=basename($file);
817 if (exists $hooks{htmlize}{$base} &&
818 $hooks{htmlize}{$base}{noextension}) {
829 if (exists $pagename_cache{$file}) {
830 return $pagename_cache{$file};
833 my $type=pagetype($file);
835 $page=~s/\Q.$type\E*$//
836 if defined $type && !$hooks{htmlize}{$type}{keepextension}
837 && !$hooks{htmlize}{$type}{noextension};
838 if ($config{indexpages} && $page=~/(.*)\/index$/) {
842 $pagename_cache{$file} = $page;
846 sub newpagefile ($$) {
850 if (! $config{indexpages} || $page eq 'index') {
851 return $page.".".$type;
854 return $page."/index.".$type;
858 sub targetpage ($$;$) {
863 if (defined $filename) {
864 return $page."/".$filename.".".$ext;
866 elsif (! $config{usedirs} || $page eq 'index') {
867 return $page.".".$ext;
870 return $page."/index.".$ext;
877 return targetpage($page, $config{htmlext});
884 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
885 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
886 return "$dir/$file", stat(_) if -e "$dir/$file";
888 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
893 return (srcfile_stat(@_))[0];
896 sub add_literal_underlay ($) {
899 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
900 unshift @{$config{underlaydirs}}, $dir;
904 sub add_underlay ($) {
908 $dir="$config{underlaydirbase}/$dir";
911 add_literal_underlay($dir);
912 # why does it return 1? we just don't know
916 sub readfile ($;$$) {
922 error("cannot read a symlink ($file)");
926 open (my $in, "<", $file) || error("failed to read $file: $!");
927 binmode($in) if ($binary);
928 return \*$in if $wantfd;
930 # check for invalid utf-8, and toss it back to avoid crashes
931 if (! utf8::valid($ret)) {
932 $ret=encode_utf8($ret);
934 close $in || error("failed to read $file: $!");
938 sub prep_writefile ($$) {
943 while (length $test) {
944 if (-l "$destdir/$test") {
945 error("cannot write to a symlink ($test)");
947 if (-f _ && $test ne $file) {
948 # Remove conflicting file.
949 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
950 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
952 unlink("$destdir/$test");
958 $test=dirname($test);
961 my $dir=dirname("$destdir/$file");
964 foreach my $s (split(m!/+!, $dir)) {
967 mkdir($d) || error("failed to create directory $d: $!");
975 sub writefile ($$$;$$) {
976 my $file=shift; # can include subdirs
977 my $destdir=shift; # directory to put file in
982 prep_writefile($file, $destdir);
984 my $newfile="$destdir/$file.ikiwiki-new";
986 error("cannot write to a symlink ($newfile)");
989 my $cleanup = sub { unlink($newfile) };
990 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
991 binmode($out) if ($binary);
993 $writer->(\*$out, $cleanup);
996 print $out $content or error("failed writing to $newfile: $!", $cleanup);
998 close $out || error("failed saving $newfile: $!", $cleanup);
999 rename($newfile, "$destdir/$file") ||
1000 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1006 sub will_render ($$;$) {
1011 # Important security check for independently created files.
1012 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1013 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1014 my $from_other_page=0;
1015 # Expensive, but rarely runs.
1016 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1019 dirname($_) eq $dest
1020 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1026 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1027 unless $from_other_page;
1030 # If $dest exists as a directory, remove conflicting files in it
1031 # rendered from other pages.
1033 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1034 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1035 if (dirname($f) eq $dest) {
1036 unlink("$config{destdir}/$f");
1037 rmdir(dirname("$config{destdir}/$f"));
1043 if (! $clear || $cleared{$page}) {
1044 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1047 foreach my $old (@{$renderedfiles{$page}}) {
1048 delete $destsources{$old};
1050 $renderedfiles{$page}=[$dest];
1053 $destsources{$dest}=$page;
1063 if ($link=~s/^\/+//) {
1071 $l.="/" if length $l;
1074 if (exists $pagesources{$l}) {
1077 elsif (exists $pagecase{lc $l}) {
1078 return $pagecase{lc $l};
1080 } while $cwd=~s{/?[^/]+$}{};
1082 if (length $config{userdir}) {
1083 my $l = "$config{userdir}/".lc($link);
1084 if (exists $pagesources{$l}) {
1087 elsif (exists $pagecase{lc $l}) {
1088 return $pagecase{lc $l};
1092 #print STDERR "warning: page $page, broken link: $link\n";
1096 sub isinlinableimage ($) {
1099 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1102 sub pagetitle ($;$) {
1104 my $unescaped=shift;
1107 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1110 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1118 # support use w/o %config set
1119 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1120 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1126 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1127 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1134 my $cgiurl=$local_cgiurl;
1136 if (exists $params{cgiurl}) {
1137 $cgiurl=$params{cgiurl};
1138 delete $params{cgiurl};
1146 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1149 sub cgiurl_abs (@) {
1151 URI->new_abs(cgiurl(@_), $config{cgiurl});
1157 return $local_url if ! defined $page;
1159 $page=htmlpage($page);
1161 $page=~s/[^\/]+\//..\//g;
1169 return $url unless defined $urlbase && length $urlbase;
1172 URI->new_abs($url, $urlbase)->as_string;
1176 # Work around very innefficient behavior in File::Spec if abs2rel
1177 # is passed two relative paths. It's much faster if paths are
1178 # absolute! (Debian bug #376658; fixed in debian unstable now)
1183 my $ret=File::Spec->abs2rel($path, $base);
1184 $ret=~s/^// if defined $ret;
1188 sub displaytime ($;$$) {
1189 # Plugins can override this function to mark up the time to
1191 my $time=formattime($_[0], $_[1]);
1192 if ($config{html5}) {
1193 return '<time datetime="'.date_3339($_[0]).'"'.
1194 ($_[2] ? ' pubdate="pubdate"' : '').
1195 '>'.$time.'</time>';
1198 return '<span class="date">'.$time.'</span>';
1202 sub formattime ($;$) {
1203 # Plugins can override this function to format the time.
1206 if (! defined $format) {
1207 $format=$config{timeformat};
1210 return strftime_utf8($format, localtime($time));
1213 my $strftime_encoding;
1215 # strftime doesn't know about encodings, so make sure
1216 # its output is properly treated as utf8.
1217 # Note that this does not handle utf-8 in the format string.
1218 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1219 unless defined $strftime_encoding;
1221 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1222 : POSIX::strftime(@_);
1228 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1229 POSIX::setlocale(&POSIX::LC_TIME, "C");
1230 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1231 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1235 sub beautify_urlpath ($) {
1238 # Ensure url is not an empty link, and if necessary,
1239 # add ./ to avoid colon confusion.
1240 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1244 if ($config{usedirs}) {
1245 $url =~ s!/index.$config{htmlext}$!/!;
1260 if (! $destsources{$to}) {
1265 return $config{url}.beautify_urlpath("/".$to);
1268 if (! defined $from) {
1269 my $u = $local_url || '';
1271 return $u.beautify_urlpath("/".$to);
1274 my $link = abs2rel($to, dirname(htmlpage($from)));
1276 return beautify_urlpath($link);
1279 sub isselflink ($$) {
1280 # Plugins can override this function to support special types
1285 return $page eq $link;
1288 sub htmllink ($$$;@) {
1289 my $lpage=shift; # the page doing the linking
1290 my $page=shift; # the page that will contain the link (different for inline)
1297 if (! $opts{forcesubpage}) {
1298 $bestlink=bestlink($lpage, $link);
1301 $bestlink="$lpage/".lc($link);
1305 if (defined $opts{linktext}) {
1306 $linktext=$opts{linktext};
1309 $linktext=pagetitle(basename($link));
1312 return "<span class=\"selflink\">$linktext</span>"
1313 if length $bestlink && isselflink($page, $bestlink) &&
1314 ! defined $opts{anchor};
1316 if (! $destsources{$bestlink}) {
1317 $bestlink=htmlpage($bestlink);
1319 if (! $destsources{$bestlink}) {
1321 if (length $config{cgiurl}) {
1322 $cgilink = "<a href=\"".
1327 )."\" rel=\"nofollow\">?</a>";
1329 return "<span class=\"createlink\">$cgilink$linktext</span>"
1333 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1334 $bestlink=beautify_urlpath($bestlink);
1336 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1337 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1340 if (defined $opts{anchor}) {
1341 $bestlink.="#".$opts{anchor};
1345 foreach my $attr (qw{rel class title}) {
1346 if (defined $opts{$attr}) {
1347 push @attrs, " $attr=\"$opts{$attr}\"";
1351 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1356 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1359 sub openiduser ($) {
1362 if (defined $user && $user =~ m!^https?://! &&
1363 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1366 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1367 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1370 # backcompat with old version
1371 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1372 $display=$oid->display;
1375 # Convert "user.somehost.com" to "user [somehost.com]"
1376 # (also "user.somehost.co.uk")
1377 if ($display !~ /\[/) {
1378 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1380 # Convert "http://somehost.com/user" to "user [somehost.com]".
1381 # (also "https://somehost.com/user/")
1382 if ($display !~ /\[/) {
1383 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1385 $display=~s!^https?://!!; # make sure this is removed
1386 eval q{use CGI 'escapeHTML'};
1388 return escapeHTML($display);
1393 sub htmlize ($$$$) {
1399 my $oneline = $content !~ /\n/;
1401 if (exists $hooks{htmlize}{$type}) {
1402 $content=$hooks{htmlize}{$type}{call}->(
1404 content => $content,
1408 error("htmlization of $type not supported");
1411 run_hooks(sanitize => sub {
1414 destpage => $destpage,
1415 content => $content,
1420 # hack to get rid of enclosing junk added by markdown
1421 # and other htmlizers/sanitizers
1422 $content=~s/^<p>//i;
1423 $content=~s/<\/p>\n*$//i;
1434 run_hooks(linkify => sub {
1437 destpage => $destpage,
1438 content => $content,
1446 our $preprocess_preview=0;
1447 sub preprocess ($$$;$$) {
1448 my $page=shift; # the page the data comes from
1449 my $destpage=shift; # the page the data will appear in (different for inline)
1454 # Using local because it needs to be set within any nested calls
1456 local $preprocess_preview=$preview if defined $preview;
1463 $params="" if ! defined $params;
1465 if (length $escape) {
1466 return "[[$prefix$command $params]]";
1468 elsif (exists $hooks{preprocess}{$command}) {
1469 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1470 # Note: preserve order of params, some plugins may
1471 # consider it significant.
1473 while ($params =~ m{
1474 (?:([-.\w]+)=)? # 1: named parameter key?
1476 """(.*?)""" # 2: triple-quoted value
1478 "([^"]*?)" # 3: single-quoted value
1480 '''(.*?)''' # 4: triple-single-quote
1482 <<([a-zA-Z]+)\n # 5: heredoc start
1483 (.*?)\n\5 # 6: heredoc value
1485 (\S+) # 7: unquoted value
1487 (?:\s+|$) # delimiter to next param
1497 elsif (defined $3) {
1500 elsif (defined $4) {
1503 elsif (defined $7) {
1506 elsif (defined $6) {
1511 push @params, $key, $val;
1514 push @params, $val, '';
1517 if ($preprocessing{$page}++ > 8) {
1518 # Avoid loops of preprocessed pages preprocessing
1519 # other pages that preprocess them, etc.
1520 return "[[!$command <span class=\"error\">".
1521 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1522 $page, $preprocessing{$page}).
1528 $hooks{preprocess}{$command}{call}->(
1531 destpage => $destpage,
1532 preview => $preprocess_preview,
1538 $ret="[[!$command <span class=\"error\">".
1539 gettext("Error").": $error"."</span>]]";
1543 # use void context during scan pass
1545 $hooks{preprocess}{$command}{call}->(
1548 destpage => $destpage,
1549 preview => $preprocess_preview,
1554 $preprocessing{$page}--;
1558 return "[[$prefix$command $params]]";
1563 if ($config{prefix_directives}) {
1566 \[\[(!) # directive open; 2: prefix
1567 ([-\w]+) # 3: command
1568 ( # 4: the parameters..
1569 \s+ # Must have space if parameters present
1571 (?:[-.\w]+=)? # named parameter key?
1573 """.*?""" # triple-quoted value
1575 "[^"]*?" # single-quoted value
1577 '''.*?''' # triple-single-quote
1579 <<([a-zA-Z]+)\n # 5: heredoc start
1580 (?:.*?)\n\5 # heredoc value
1582 [^"\s\]]+ # unquoted value
1584 \s* # whitespace or end
1587 *)? # 0 or more parameters
1588 \]\] # directive closed
1594 \[\[(!?) # directive open; 2: optional prefix
1595 ([-\w]+) # 3: command
1597 ( # 4: the parameters..
1599 (?:[-.\w]+=)? # named parameter key?
1601 """.*?""" # triple-quoted value
1603 "[^"]*?" # single-quoted value
1605 '''.*?''' # triple-single-quote
1607 <<([a-zA-Z]+)\n # 5: heredoc start
1608 (?:.*?)\n\5 # heredoc value
1610 [^"\s\]]+ # unquoted value
1612 \s* # whitespace or end
1615 *) # 0 or more parameters
1616 \]\] # directive closed
1620 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1629 run_hooks(filter => sub {
1630 $content=shift->(page => $page, destpage => $destpage,
1631 content => $content);
1637 sub check_canedit ($$$;$) {
1644 run_hooks(canedit => sub {
1645 return if defined $canedit;
1646 my $ret=shift->($page, $q, $session);
1651 elsif (ref $ret eq 'CODE') {
1652 $ret->() unless $nonfatal;
1655 elsif (defined $ret) {
1656 error($ret) unless $nonfatal;
1661 return defined $canedit ? $canedit : 1;
1664 sub check_content (@) {
1667 return 1 if ! exists $hooks{checkcontent}; # optimisation
1669 if (exists $pagesources{$params{page}}) {
1671 my %old=map { $_ => 1 }
1672 split("\n", readfile(srcfile($pagesources{$params{page}})));
1673 foreach my $line (split("\n", $params{content})) {
1674 push @diff, $line if ! exists $old{$line};
1676 $params{diff}=join("\n", @diff);
1680 run_hooks(checkcontent => sub {
1681 return if defined $ok;
1682 my $ret=shift->(%params);
1687 elsif (ref $ret eq 'CODE') {
1688 $ret->() unless $params{nonfatal};
1691 elsif (defined $ret) {
1692 error($ret) unless $params{nonfatal};
1698 return defined $ok ? $ok : 1;
1701 sub check_canchange (@) {
1703 my $cgi = $params{cgi};
1704 my $session = $params{session};
1705 my @changes = @{$params{changes}};
1708 foreach my $change (@changes) {
1709 # This untaint is safe because we check file_pruned and
1711 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1712 $file=possibly_foolish_untaint($file);
1713 if (! defined $file || ! length $file ||
1714 file_pruned($file)) {
1715 error(gettext("bad file name %s"), $file);
1718 my $type=pagetype($file);
1719 my $page=pagename($file) if defined $type;
1721 if ($change->{action} eq 'add') {
1725 if ($change->{action} eq 'change' ||
1726 $change->{action} eq 'add') {
1727 if (defined $page) {
1728 check_canedit($page, $cgi, $session);
1732 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1733 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1734 check_canedit($file, $cgi, $session);
1739 elsif ($change->{action} eq 'remove') {
1740 # check_canremove tests to see if the file is present
1741 # on disk. This will fail when a single commit adds a
1742 # file and then removes it again. Avoid the problem
1743 # by not testing the removal in such pairs of changes.
1744 # (The add is still tested, just to make sure that
1745 # no data is added to the repo that a web edit
1747 next if $newfiles{$file};
1749 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1750 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1751 check_canedit(defined $page ? $page : $file, $cgi, $session);
1756 error "unknown action ".$change->{action};
1759 error sprintf(gettext("you are not allowed to change %s"), $file);
1767 # Take an exclusive lock on the wiki to prevent multiple concurrent
1768 # run issues. The lock will be dropped on program exit.
1769 if (! -d $config{wikistatedir}) {
1770 mkdir($config{wikistatedir});
1772 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1773 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1774 if (! flock($wikilock, 2)) { # LOCK_EX
1775 error("failed to get lock");
1781 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1782 return close($wikilock) if $wikilock;
1788 sub commit_hook_enabled () {
1789 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1790 error("cannot write to $config{wikistatedir}/commitlock: $!");
1791 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1792 close($commitlock) || error("failed closing commitlock: $!");
1795 close($commitlock) || error("failed closing commitlock: $!");
1799 sub disable_commit_hook () {
1800 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1801 error("cannot write to $config{wikistatedir}/commitlock: $!");
1802 if (! flock($commitlock, 2)) { # LOCK_EX
1803 error("failed to get commit lock");
1808 sub enable_commit_hook () {
1809 return close($commitlock) if $commitlock;
1814 %oldrenderedfiles=%pagectime=();
1815 my $rebuild=$config{rebuild};
1817 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1818 %destsources=%renderedfiles=%pagecase=%pagestate=
1819 %depends_simple=%typedlinks=%oldtypedlinks=();
1822 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1823 if (-e "$config{wikistatedir}/index") {
1824 system("ikiwiki-transition", "indexdb", $config{srcdir});
1825 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1828 # gettime on first build
1829 $config{gettime}=1 unless defined $config{gettime};
1834 my $index=Storable::fd_retrieve($in);
1835 if (! defined $index) {
1840 if (exists $index->{version} && ! ref $index->{version}) {
1841 $pages=$index->{page};
1842 %wikistate=%{$index->{state}};
1843 # Handle plugins that got disabled by loading a new setup.
1844 if (exists $config{setupfile}) {
1845 require IkiWiki::Setup;
1846 IkiWiki::Setup::disabled_plugins(
1847 grep { ! $loaded_plugins{$_} } keys %wikistate);
1855 foreach my $src (keys %$pages) {
1856 my $d=$pages->{$src};
1858 if (exists $d->{page} && ! $rebuild) {
1862 $page=pagename($src);
1864 $pagectime{$page}=$d->{ctime};
1865 $pagesources{$page}=$src;
1867 $pagemtime{$page}=$d->{mtime};
1868 $renderedfiles{$page}=$d->{dest};
1869 if (exists $d->{links} && ref $d->{links}) {
1870 $links{$page}=$d->{links};
1871 $oldlinks{$page}=[@{$d->{links}}];
1873 if (ref $d->{depends_simple} eq 'ARRAY') {
1875 $depends_simple{$page}={
1876 map { $_ => 1 } @{$d->{depends_simple}}
1879 elsif (exists $d->{depends_simple}) {
1880 $depends_simple{$page}=$d->{depends_simple};
1882 if (exists $d->{dependslist}) {
1885 map { $_ => $DEPEND_CONTENT }
1886 @{$d->{dependslist}}
1889 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1891 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1893 elsif (exists $d->{depends}) {
1894 $depends{$page}=$d->{depends};
1896 if (exists $d->{state}) {
1897 $pagestate{$page}=$d->{state};
1899 if (exists $d->{typedlinks}) {
1900 $typedlinks{$page}=$d->{typedlinks};
1902 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1903 next unless %$links;
1904 $oldtypedlinks{$page}{$type} = {%$links};
1908 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1910 foreach my $page (keys %pagesources) {
1911 $pagecase{lc $page}=$page;
1913 foreach my $page (keys %renderedfiles) {
1914 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1916 $lastrev=$index->{lastrev};
1917 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1922 run_hooks(savestate => sub { shift->() });
1924 my @plugins=keys %loaded_plugins;
1926 if (! -d $config{wikistatedir}) {
1927 mkdir($config{wikistatedir});
1929 my $newfile="$config{wikistatedir}/indexdb.new";
1930 my $cleanup = sub { unlink($newfile) };
1931 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1934 foreach my $page (keys %pagemtime) {
1935 next unless $pagemtime{$page};
1936 my $src=$pagesources{$page};
1938 $index{page}{$src}={
1940 ctime => $pagectime{$page},
1941 mtime => $pagemtime{$page},
1942 dest => $renderedfiles{$page},
1943 links => $links{$page},
1946 if (exists $depends{$page}) {
1947 $index{page}{$src}{depends} = $depends{$page};
1950 if (exists $depends_simple{$page}) {
1951 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1954 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1955 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1958 if (exists $pagestate{$page}) {
1959 $index{page}{$src}{state}=$pagestate{$page};
1964 foreach my $id (@plugins) {
1965 $index{state}{$id}={}; # used to detect disabled plugins
1966 foreach my $key (keys %{$wikistate{$id}}) {
1967 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1971 $index{lastrev}=$lastrev;
1972 $index{underlayfiles}=\@underlayfiles;
1974 $index{version}="3";
1975 my $ret=Storable::nstore_fd(\%index, $out);
1976 return if ! defined $ret || ! $ret;
1977 close $out || error("failed saving to $newfile: $!", $cleanup);
1978 rename($newfile, "$config{wikistatedir}/indexdb") ||
1979 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1984 sub template_file ($) {
1987 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1989 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1990 $template=srcfile($pagesources{$tpage}, 1);
1994 $template=srcfile($tpage, 1);
1997 if (defined $template) {
1998 return $template, $tpage, 1 if wantarray;
2002 $name=~s:/::; # avoid path traversal
2003 foreach my $dir ($config{templatedir},
2004 "$installdir/share/ikiwiki/templates") {
2005 if (-e "$dir/$name") {
2006 $template="$dir/$name";
2010 if (defined $template) {
2011 return $template, $tpage if wantarray;
2019 sub template_depends ($$;@) {
2023 my ($filename, $tpage, $untrusted)=template_file($name);
2024 if (! defined $filename) {
2025 error(sprintf(gettext("template %s not found"), $name))
2028 if (defined $page && defined $tpage) {
2029 add_depends($page, $tpage);
2034 my $text_ref = shift;
2035 ${$text_ref} = decode_utf8(${$text_ref});
2036 run_hooks(readtemplate => sub {
2037 ${$text_ref} = shift->(
2040 content => ${$text_ref},
2041 untrusted => $untrusted,
2045 loop_context_vars => 1,
2046 die_on_bad_params => 0,
2047 parent_global_vars => 1,
2048 filename => $filename,
2050 ($untrusted ? (no_includes => 1) : ()),
2052 return @opts if wantarray;
2054 require HTML::Template;
2055 return HTML::Template->new(@opts);
2058 sub template ($;@) {
2059 template_depends(shift, undef, @_);
2062 sub templateactions ($$) {
2068 run_hooks(pageactions => sub {
2069 push @actions, map { { action => $_ } }
2070 grep { defined } shift->(page => $page);
2072 $template->param(actions => \@actions);
2074 if ($config{cgiurl} && exists $hooks{auth}) {
2075 $template->param(prefsurl => cgiurl(do => "prefs"));
2079 if ($have_actions || @actions) {
2080 $template->param(have_actions => 1);
2087 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2088 error 'hook requires type, call, and id parameters';
2091 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2093 $hooks{$param{type}}{$param{id}}=\%param;
2097 sub run_hooks ($$) {
2098 # Calls the given sub for each hook of the given type,
2099 # passing it the hook function to call.
2103 if (exists $hooks{$type}) {
2104 my (@first, @middle, @last);
2105 foreach my $id (keys %{$hooks{$type}}) {
2106 if ($hooks{$type}{$id}{first}) {
2109 elsif ($hooks{$type}{$id}{last}) {
2116 foreach my $id (@first, @middle, @last) {
2117 $sub->($hooks{$type}{$id}{call});
2125 $hooks{rcs}{rcs_update}{call}->(@_);
2128 sub rcs_prepedit ($) {
2129 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2132 sub rcs_commit (@) {
2133 $hooks{rcs}{rcs_commit}{call}->(@_);
2136 sub rcs_commit_staged (@) {
2137 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2141 $hooks{rcs}{rcs_add}{call}->(@_);
2144 sub rcs_remove ($) {
2145 $hooks{rcs}{rcs_remove}{call}->(@_);
2148 sub rcs_rename ($$) {
2149 $hooks{rcs}{rcs_rename}{call}->(@_);
2152 sub rcs_recentchanges ($) {
2153 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2156 sub rcs_diff ($;$) {
2157 $hooks{rcs}{rcs_diff}{call}->(@_);
2160 sub rcs_getctime ($) {
2161 $hooks{rcs}{rcs_getctime}{call}->(@_);
2164 sub rcs_getmtime ($) {
2165 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2168 sub rcs_receive () {
2169 $hooks{rcs}{rcs_receive}{call}->();
2172 sub add_depends ($$;$) {
2175 my $deptype=shift || $DEPEND_CONTENT;
2177 # Is the pagespec a simple page name?
2178 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2179 $pagespec !~ /[\s*?()!]/) {
2180 $depends_simple{$page}{lc $pagespec} |= $deptype;
2184 # Add explicit dependencies for influences.
2185 my $sub=pagespec_translate($pagespec);
2186 return unless defined $sub;
2187 foreach my $p (keys %pagesources) {
2188 my $r=$sub->($p, location => $page);
2189 my $i=$r->influences;
2190 my $static=$r->influences_static;
2191 foreach my $k (keys %$i) {
2192 next unless $r || $static || $k eq $page;
2193 $depends_simple{$page}{lc $k} |= $i->{$k};
2198 $depends{$page}{$pagespec} |= $deptype;
2204 foreach my $type (@_) {
2205 if ($type eq 'presence') {
2206 $deptype |= $DEPEND_PRESENCE;
2208 elsif ($type eq 'links') {
2209 $deptype |= $DEPEND_LINKS;
2211 elsif ($type eq 'content') {
2212 $deptype |= $DEPEND_CONTENT;
2218 my $file_prune_regexp;
2219 sub file_pruned ($) {
2222 if (defined $config{include} && length $config{include}) {
2223 return 0 if $file =~ m/$config{include}/;
2226 if (! defined $file_prune_regexp) {
2227 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2228 $file_prune_regexp=qr/$file_prune_regexp/;
2230 return $file =~ m/$file_prune_regexp/;
2233 sub define_gettext () {
2234 # If translation is needed, redefine the gettext function to do it.
2235 # Otherwise, it becomes a quick no-op.
2238 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2239 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2240 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2242 $gettext_obj=eval q{
2243 use Locale::gettext q{textdomain};
2244 Locale::gettext->domain('ikiwiki')
2249 no warnings 'redefine';
2251 $getobj->() if $getobj;
2253 $gettext_obj->get(shift);
2260 $getobj->() if $getobj;
2262 $gettext_obj->nget(@_);
2265 return ($_[2] == 1 ? $_[0] : $_[1])
2283 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2287 # Injects a new function into the symbol table to replace an
2288 # exported function.
2291 # This is deep ugly perl foo, beware.
2294 if (! defined $params{parent}) {
2295 $params{parent}='::';
2296 $params{old}=\&{$params{name}};
2297 $params{name}=~s/.*:://;
2299 my $parent=$params{parent};
2300 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2301 $ns = $params{parent} . $ns;
2302 inject(%params, parent => $ns) unless $ns eq '::main::';
2303 *{$ns . $params{name}} = $params{call}
2304 if exists ${$ns}{$params{name}} &&
2305 \&{${$ns}{$params{name}}} == $params{old};
2311 sub add_link ($$;$) {
2316 push @{$links{$page}}, $link
2317 unless grep { $_ eq $link } @{$links{$page}};
2319 if (defined $type) {
2320 $typedlinks{$page}{$type}{$link} = 1;
2324 sub add_autofile ($$$) {
2327 my $generator=shift;
2329 $autofiles{$file}{plugin}=$plugin;
2330 $autofiles{$file}{generator}=$generator;
2334 return LWP::UserAgent->new(
2335 cookie_jar => $config{cookiejar},
2336 env_proxy => 1, # respect proxy env vars
2337 agent => $config{useragent},
2341 sub sortspec_translate ($$) {
2343 my $reverse = shift;
2349 (-?) # group 1: perhaps negated
2352 \w+\([^\)]*\) # command(params)
2354 [^\s]+ # or anything else
2362 if ($word =~ m/^(\w+)\((.*)\)$/) {
2363 # command with parameters
2367 elsif ($word !~ m/^\w+$/) {
2368 error(sprintf(gettext("invalid sort type %s"), $word));
2379 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2380 if (defined $params) {
2381 push @data, $params;
2382 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2385 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2389 error(sprintf(gettext("unknown sort type %s"), $word));
2393 if (! length $code) {
2394 # undefined sorting method... sort arbitrarily
2403 return eval 'sub { '.$code.' }';
2406 sub pagespec_translate ($) {
2409 # Convert spec to perl code.
2413 \s* # ignore whitespace
2414 ( # 1: match a single word
2421 \w+\([^\)]*\) # command(params)
2423 [^\s()]+ # any other text
2425 \s* # ignore whitespace
2428 if (lc $word eq 'and') {
2431 elsif (lc $word eq 'or') {
2434 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2437 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2438 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2440 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2443 push @data, qq{unknown function in pagespec "$word"};
2444 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2449 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2453 if (! length $code) {
2454 $code="IkiWiki::FailReason->new('empty pagespec')";
2458 return eval 'sub { my $page=shift; '.$code.' }';
2461 sub pagespec_match ($$;@) {
2466 # Backwards compatability with old calling convention.
2468 unshift @params, 'location';
2471 my $sub=pagespec_translate($spec);
2472 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2474 return $sub->($page, @params);
2477 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2479 # Not exported yet, but could be in future if it is generally useful.
2480 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2481 # which is "more internal".
2482 sub sort_pages ($$;@) {
2486 $sort = sortspec_translate($sort, $params{reverse});
2487 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2490 sub pagespec_match_list ($$;@) {
2495 # Backwards compatability with old calling convention.
2497 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2498 $params{list}=$page;
2499 $page=$params{location}; # ugh!
2502 my $sub=pagespec_translate($pagespec);
2503 error "syntax error in pagespec \"$pagespec\""
2505 my $sort=sortspec_translate($params{sort}, $params{reverse})
2506 if defined $params{sort};
2509 if (exists $params{list}) {
2510 @candidates=exists $params{filter}
2511 ? grep { ! $params{filter}->($_) } @{$params{list}}
2515 @candidates=exists $params{filter}
2516 ? grep { ! $params{filter}->($_) } keys %pagesources
2517 : keys %pagesources;
2520 # clear params, remainder is passed to pagespec
2521 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2522 my $num=$params{num};
2523 delete @params{qw{num deptype reverse sort filter list}};
2525 # when only the top matches will be returned, it's efficient to
2526 # sort before matching to pagespec,
2527 if (defined $num && defined $sort) {
2528 @candidates=IkiWiki::SortSpec::sort_pages(
2529 $sort, @candidates);
2535 my $accum=IkiWiki::SuccessReason->new();
2536 foreach my $p (@candidates) {
2537 my $r=$sub->($p, %params, location => $page);
2538 error(sprintf(gettext("cannot match pages: %s"), $r))
2539 if $r->isa("IkiWiki::ErrorReason");
2540 unless ($r || $r->influences_static) {
2541 $r->remove_influence($p);
2546 last if defined $num && ++$count == $num;
2550 # Add simple dependencies for accumulated influences.
2551 my $i=$accum->influences;
2552 foreach my $k (keys %$i) {
2553 $depends_simple{$page}{lc $k} |= $i->{$k};
2556 # when all matches will be returned, it's efficient to
2557 # sort after matching
2558 if (! defined $num && defined $sort) {
2559 return IkiWiki::SortSpec::sort_pages(
2567 sub pagespec_valid ($) {
2570 return defined pagespec_translate($spec);
2574 my $re=quotemeta(shift);
2580 package IkiWiki::FailReason;
2583 '""' => sub { $_[0][0] },
2585 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2586 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2587 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2591 our @ISA = 'IkiWiki::SuccessReason';
2593 package IkiWiki::SuccessReason;
2595 # A blessed array-ref:
2597 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2599 # - if absent or false, the influences of this evaluation are "static",
2600 # see the influences_static method
2601 # - if true, they are dynamic (not static)
2602 # [1]{any other key}:
2603 # the dependency types of influences, as returned by the influences method
2606 # in string context, it's the human-readable reason
2607 '""' => sub { $_[0][0] },
2608 # in boolean context, SuccessReason is 1 and FailReason is 0
2610 # negating a result gives the opposite result with the same influences
2611 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2612 # A & B = (A ? B : A) with the influences of both
2613 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2614 # A | B = (A ? A : B) with the influences of both
2615 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2619 # SuccessReason->new("human-readable reason", page => deptype, ...)
2624 return bless [$value, {@_}], $class;
2627 # influences(): return a reference to a copy of the hash
2628 # { page => dependency type } describing the pages that indirectly influenced
2629 # this result, but would not cause a dependency through ikiwiki's core
2632 # See [[todo/dependency_types]] for extensive discussion of what this means.
2634 # influences(page => deptype, ...): remove all influences, replace them
2635 # with the arguments, and return a reference to a copy of the new influences.
2639 $this->[1]={@_} if @_;
2640 my %i=%{$this->[1]};
2645 # True if this result has the same influences whichever page it matches,
2646 # For instance, whether bar matches backlink(foo) is influenced only by
2647 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2648 # which does not mention bar anywhere.
2650 # False if this result would have different influences when matching
2651 # different pages. For instance, when testing whether link(foo) matches bar,
2652 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2653 # bar's links could change the outcome; so its influences are not the same
2654 # as when testing whether link(foo) matches baz.
2656 # Static influences are one of the things that make pagespec_match_list
2657 # more efficient than repeated calls to pagespec_match.
2659 sub influences_static {
2660 return ! $_[0][1]->{""};
2663 # Change the influences of $this to be the influences of "$this & $other"
2664 # or "$this | $other".
2666 # If both $this and $other are either successful or have influences,
2667 # or this is an "or" operation, the result has all the influences from
2668 # either of the arguments. It has dynamic influences if either argument
2669 # has dynamic influences.
2671 # If this is an "and" operation, and at least one argument is a
2672 # FailReason with no influences, the result has no influences, and they
2673 # are not dynamic. For instance, link(foo) matching bar is influenced
2674 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2675 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2676 # bar, because it would be false however often you edit bar.
2678 sub merge_influences {
2683 # This "if" is odd because it needs to avoid negating $this
2684 # or $other, which would alter the objects in-place. Be careful.
2685 if (! $anded || (($this || %{$this->[1]}) &&
2686 ($other || %{$other->[1]}))) {
2687 foreach my $influence (keys %{$other->[1]}) {
2688 $this->[1]{$influence} |= $other->[1]{$influence};
2697 # Change $this so it is not considered to be influenced by $torm.
2699 sub remove_influence {
2703 delete $this->[1]{$torm};
2706 package IkiWiki::ErrorReason;
2708 our @ISA = 'IkiWiki::FailReason';
2710 package IkiWiki::PageSpec;
2716 if ($path =~ m!^\.(/|$)!) {
2718 $from=~s#/?[^/]+$## if defined $from;
2720 $path="$from/$path" if defined $from && length $from;
2724 $path = "" unless defined $path;
2733 sub match_glob ($$;@) {
2738 $glob=derel($glob, $params{location});
2740 # Instead of converting the glob to a regex every time,
2741 # cache the compiled regex to save time.
2742 my $re=$glob_cache{$glob};
2743 unless (defined $re) {
2744 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2747 if (! IkiWiki::isinternal($page) || $params{internal}) {
2748 return IkiWiki::SuccessReason->new("$glob matches $page");
2751 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2755 return IkiWiki::FailReason->new("$glob does not match $page");
2759 sub match_internal ($$;@) {
2760 return match_glob(shift, shift, @_, internal => 1)
2763 sub match_page ($$;@) {
2765 my $match=match_glob($page, shift, @_);
2767 my $source=exists $IkiWiki::pagesources{$page} ?
2768 $IkiWiki::pagesources{$page} :
2769 $IkiWiki::delpagesources{$page};
2770 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2771 if (! defined $type) {
2772 return IkiWiki::FailReason->new("$page is not a page");
2778 sub match_link ($$;@) {
2783 $link=derel($link, $params{location});
2784 my $from=exists $params{location} ? $params{location} : '';
2785 my $linktype=$params{linktype};
2787 if (defined $linktype) {
2788 $qualifier=" with type $linktype";
2791 my $links = $IkiWiki::links{$page};
2792 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2793 unless $links && @{$links};
2794 my $bestlink = IkiWiki::bestlink($from, $link);
2795 foreach my $p (@{$links}) {
2796 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2798 if (length $bestlink) {
2799 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2800 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2804 if (match_glob($p, $link, %params)) {
2805 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2807 my ($p_rel)=$p=~/^\/?(.*)/;
2809 if (match_glob($p_rel, $link, %params)) {
2810 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2814 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2817 sub match_backlink ($$;@) {
2821 if ($testpage eq '.') {
2822 $testpage = $params{'location'}
2824 my $ret=match_link($testpage, $page, @_);
2825 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2829 sub match_created_before ($$;@) {
2834 $testpage=derel($testpage, $params{location});
2836 if (exists $IkiWiki::pagectime{$testpage}) {
2837 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2838 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2841 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2845 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2849 sub match_created_after ($$;@) {
2854 $testpage=derel($testpage, $params{location});
2856 if (exists $IkiWiki::pagectime{$testpage}) {
2857 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2858 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2861 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2865 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2869 sub match_creation_day ($$;@) {
2872 if ($d !~ /^\d+$/) {
2873 return IkiWiki::ErrorReason->new("invalid day $d");
2875 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2876 return IkiWiki::SuccessReason->new('creation_day matched');
2879 return IkiWiki::FailReason->new('creation_day did not match');
2883 sub match_creation_month ($$;@) {
2886 if ($m !~ /^\d+$/) {
2887 return IkiWiki::ErrorReason->new("invalid month $m");
2889 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2890 return IkiWiki::SuccessReason->new('creation_month matched');
2893 return IkiWiki::FailReason->new('creation_month did not match');
2897 sub match_creation_year ($$;@) {
2900 if ($y !~ /^\d+$/) {
2901 return IkiWiki::ErrorReason->new("invalid year $y");
2903 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2904 return IkiWiki::SuccessReason->new('creation_year matched');
2907 return IkiWiki::FailReason->new('creation_year did not match');
2911 sub match_user ($$;@) {
2916 if (! exists $params{user}) {
2917 return IkiWiki::ErrorReason->new("no user specified");
2920 my $regexp=IkiWiki::glob2re($user);
2922 if (defined $params{user} && $params{user}=~$regexp) {
2923 return IkiWiki::SuccessReason->new("user is $user");
2925 elsif (! defined $params{user}) {
2926 return IkiWiki::FailReason->new("not logged in");
2929 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2933 sub match_admin ($$;@) {
2938 if (! exists $params{user}) {
2939 return IkiWiki::ErrorReason->new("no user specified");
2942 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2943 return IkiWiki::SuccessReason->new("user is an admin");
2945 elsif (! defined $params{user}) {
2946 return IkiWiki::FailReason->new("not logged in");
2949 return IkiWiki::FailReason->new("user is not an admin");
2953 sub match_ip ($$;@) {
2958 if (! exists $params{ip}) {
2959 return IkiWiki::ErrorReason->new("no IP specified");
2962 my $regexp=IkiWiki::glob2re(lc $ip);
2964 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2965 return IkiWiki::SuccessReason->new("IP is $ip");
2968 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2972 package IkiWiki::SortSpec;
2974 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2975 # are easily available in this namespace, for cmp functions to use them.
2982 IkiWiki::pagetitle(IkiWiki::basename($a))
2984 IkiWiki::pagetitle(IkiWiki::basename($b))
2987 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2988 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2989 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }