9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %wikistate %renderedfiles %oldrenderedfiles
16 %pagesources %delpagesources %destsources %depends %depends_simple
17 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
18 %oldtypedlinks %autofiles @underlayfiles $lastrev $phase};
20 use Exporter q{import};
21 our @EXPORT = qw(hook debug error htmlpage template template_depends
22 deptype add_depends pagespec_match pagespec_match_list bestlink
23 htmllink readfile writefile pagetype srcfile pagename
24 displaytime strftime_utf8 will_render gettext ngettext urlto targetpage
25 add_underlay pagetitle titlepage linkpage newpagefile
26 inject add_link add_autofile useragent
27 %config %links %pagestate %wikistate %renderedfiles
28 %pagesources %destsources %typedlinks);
29 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
30 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
31 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
33 # Page dependency types.
34 our $DEPEND_CONTENT=1;
35 our $DEPEND_PRESENCE=2;
38 # Phases of processing.
39 sub PHASE_SCAN () { 0 }
40 sub PHASE_RENDER () { 1 }
46 memoize("sortspec_translate");
47 memoize("pagespec_translate");
48 memoize("template_file");
54 description => "name of the wiki",
61 example => 'me@example.com',
62 description => "contact email for wiki",
69 description => "users who are wiki admins",
76 description => "users who are banned from the wiki",
83 example => "$ENV{HOME}/wiki",
84 description => "where the source of the wiki is located",
91 example => "/var/www/wiki",
92 description => "where to build the wiki",
99 example => "http://example.com/wiki",
100 description => "base url to the wiki",
107 example => "http://example.com/wiki/ikiwiki.cgi",
108 description => "url to the ikiwiki.cgi",
115 description => "do not adjust cgiurl if CGI is accessed via different URL",
118 rebuild => 0, # only affects CGI requests
123 example => "/var/www/wiki/ikiwiki.cgi",
124 description => "filename of cgi wrapper to generate",
131 description => "mode for cgi_wrapper (can safely be made suid)",
135 cgi_overload_delay => {
139 description => "number of seconds to delay CGI requests when overloaded",
143 cgi_overload_message => {
146 example => "Please wait",
147 description => "message to display when overloaded (may contain html)",
151 only_committed_changes => {
154 description => "enable optimization of only refreshing committed changes?",
161 description => "rcs backend to use",
162 safe => 0, # don't allow overriding
167 default => [qw{mdwn link inline meta htmlscrubber passwordauth
168 openid signinedit lockedit conditional
169 recentchanges parentlinks editpage
171 description => "plugins to enable by default",
178 description => "plugins to add to the default configuration",
185 description => "plugins to disable",
191 default => "$installdir/share/ikiwiki/templates",
192 description => "additional directory to search for template files",
199 default => "$installdir/share/ikiwiki/basewiki",
200 description => "base wiki source location",
207 default => "$installdir/share/ikiwiki",
208 description => "parent directory containing additional underlays",
215 description => "wrappers to generate",
222 description => "additional underlays to use",
229 description => "display verbose messages?",
236 description => "log to syslog?",
243 description => "create output files named page/index.html?",
244 safe => 0, # changing requires manual transition
247 prefix_directives => {
250 description => "use '!'-prefixed preprocessor directives?",
251 safe => 0, # changing requires manual transition
257 description => "use page/index.mdwn source files",
264 description => "enable Discussion pages?",
270 default => gettext("Discussion"),
271 description => "name of Discussion pages",
278 description => "use elements new in HTML5 like <section>?",
286 description => "only send cookies over SSL connections?",
294 description => "extension to use for new pages",
295 safe => 0, # not sanitized
301 description => "extension to use for html files",
302 safe => 0, # not sanitized
308 description => "strftime format string to display date",
316 example => "en_US.UTF-8",
317 description => "UTF-8 locale to use",
326 description => "put user pages below specified page",
333 description => "how many backlinks to show before hiding excess (0 to show all)",
340 description => "attempt to hardlink source files? (optimisation for large files)",
342 safe => 0, # paranoia
348 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
350 safe => 0, # paranoia
355 example => "ikiwiki",
356 description => "group for wrappers to run in",
358 safe => 0, # paranoia
364 example => ["$ENV{HOME}/.local/share/ikiwiki"],
365 description => "extra library and plugin directories",
367 safe => 0, # directory
373 example => "$ENV{HOME}/.ikiwiki/",
374 description => "extra library and plugin directory (searched after libdirs)",
376 safe => 0, # directory
382 description => "environment variables",
383 safe => 0, # paranoia
389 example => "US/Eastern",
390 description => "time zone name",
397 example => '^\.htaccess$',
398 description => "regexp of normally excluded files to include",
406 example => '^(*\.private|Makefile)$',
407 description => "regexp of files that should be skipped",
412 wiki_file_prune_regexps => {
414 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
415 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
416 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
417 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
418 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
419 description => "regexps of source files to ignore",
425 description => "specifies the characters that are allowed in source filenames",
426 default => "-[:alnum:]+/.:_",
430 wiki_file_regexp => {
432 description => "regexp of legal source files",
436 web_commit_regexp => {
438 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
439 description => "regexp to parse web commits from logs",
446 description => "run as a cgi",
450 cgi_disable_uploads => {
453 description => "whether CGI should accept file uploads",
460 description => "run as a post-commit hook",
467 description => "running in rebuild mode",
474 description => "running in setup mode",
481 description => "running in clean mode",
488 description => "running in refresh mode",
495 description => "running in receive test mode",
499 wrapper_background_command => {
502 description => "background shell command to run",
508 description => "running in gettime mode",
515 description => "running in w3mmode",
522 description => "path to the .ikiwiki directory holding ikiwiki state",
529 description => "path to setup file",
536 description => "perl class to use to dump setup file",
540 allow_symlinks_before_srcdir => {
543 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
549 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
550 description => "cookie control",
551 safe => 0, # hooks into perl module internals
556 default => "ikiwiki/$version",
557 example => "Wget/1.13.4 (linux-gnu)",
558 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
562 responsive_layout => {
565 description => "theme has a responsive layout? (mobile-optimized)",
572 my @libdirs = @{$config{libdirs}};
573 if (length $config{libdir}) {
574 push @libdirs, $config{libdir};
579 sub defaultconfig () {
582 foreach my $key (keys %s) {
583 push @ret, $key, $s{$key}->{default};
588 # URL to top of wiki as a path starting with /, valid from any wiki page or
589 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
591 # URL to CGI script, similar to $local_url
595 # locale stuff; avoid LC_ALL since it overrides everything
596 if (defined $ENV{LC_ALL}) {
597 $ENV{LANG} = $ENV{LC_ALL};
600 if (defined $config{locale}) {
601 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
602 $ENV{LANG}=$config{locale};
607 if (! defined $config{wiki_file_regexp}) {
608 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
611 if (ref $config{ENV} eq 'HASH') {
612 foreach my $val (keys %{$config{ENV}}) {
613 $ENV{$val}=$config{ENV}{$val};
616 if (defined $config{timezone} && length $config{timezone}) {
617 $ENV{TZ}=$config{timezone};
620 $config{timezone}=$ENV{TZ};
623 if ($config{w3mmode}) {
624 eval q{use Cwd q{abs_path}};
626 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
627 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
628 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
629 unless $config{cgiurl} =~ m!file:///!;
630 $config{url}="file://".$config{destdir};
633 if ($config{cgi} && ! length $config{url}) {
634 error(gettext("Must specify url to wiki with --url when using --cgi"));
637 if (defined $config{url} && length $config{url}) {
639 my $baseurl = URI->new($config{url});
641 $local_url = $baseurl->path . "/";
642 $local_cgiurl = undef;
644 if (length $config{cgiurl}) {
645 my $cgiurl = URI->new($config{cgiurl});
647 $local_cgiurl = $cgiurl->path;
649 if ($cgiurl->scheme eq 'https' &&
650 $baseurl->scheme eq 'http') {
651 # We assume that the same content is available
652 # over both http and https, because if it
653 # wasn't, accessing the static content
654 # from the CGI would be mixed-content,
655 # which would be a security flaw.
657 if ($cgiurl->authority ne $baseurl->authority) {
658 # use protocol-relative URL for
660 $local_url = "$config{url}/";
661 $local_url =~ s{^http://}{//};
663 # else use host-relative URL for static content
665 # either way, CGI needs to be absolute
666 $local_cgiurl = $config{cgiurl};
668 elsif ($cgiurl->scheme ne $baseurl->scheme) {
669 # too far apart, fall back to absolute URLs
670 $local_url = "$config{url}/";
671 $local_cgiurl = $config{cgiurl};
673 elsif ($cgiurl->authority ne $baseurl->authority) {
674 # slightly too far apart, fall back to
675 # protocol-relative URLs
676 $local_url = "$config{url}/";
677 $local_url =~ s{^https?://}{//};
678 $local_cgiurl = $config{cgiurl};
679 $local_cgiurl =~ s{^https?://}{//};
681 # else keep host-relative URLs
684 $local_url =~ s{//$}{/};
687 $local_cgiurl = $config{cgiurl};
690 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
691 unless exists $config{wikistatedir} && defined $config{wikistatedir};
693 if (defined $config{umask}) {
694 my $u = possibly_foolish_untaint($config{umask});
696 if ($u =~ m/^\d+$/) {
699 elsif ($u eq 'private') {
702 elsif ($u eq 'group') {
705 elsif ($u eq 'public') {
709 error(sprintf(gettext("unsupported umask setting %s"), $u));
713 run_hooks(checkconfig => sub { shift->() });
721 foreach my $dir (@INC, getlibdirs()) {
722 next unless defined $dir && length $dir;
723 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
724 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
728 foreach my $dir (getlibdirs(), "$installdir/lib/ikiwiki") {
729 next unless defined $dir && length $dir;
730 foreach my $file (glob("$dir/plugins/*")) {
731 $ret{basename($file)}=1 if -x $file;
739 foreach my $dir (getlibdirs()) {
740 unshift @INC, possibly_foolish_untaint($dir);
743 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
748 if (exists $hooks{rcs}) {
749 error(gettext("cannot use multiple rcs plugins"));
751 loadplugin($config{rcs});
753 if (! exists $hooks{rcs}) {
757 run_hooks(getopt => sub { shift->() });
758 if (grep /^-/, @ARGV) {
759 print STDERR "Unknown option (or missing parameter): $_\n"
760 foreach grep /^-/, @ARGV;
767 sub loadplugin ($;$) {
771 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
773 foreach my $possiblytainteddir (getlibdirs(), "$installdir/lib/ikiwiki") {
774 my $dir = possibly_foolish_untaint($possiblytainteddir);
775 if (defined $dir && -x "$dir/plugins/$plugin") {
776 eval { require IkiWiki::Plugin::external };
779 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
781 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
782 $loaded_plugins{$plugin}=1;
787 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
790 error("Failed to load plugin $mod: $@");
792 $loaded_plugins{$plugin}=1;
799 log_message('err' => $message) if $config{syslog};
800 if (defined $cleaner) {
807 return unless $config{verbose};
808 return log_message(debug => @_);
813 sub log_message ($$) {
816 if ($config{syslog}) {
819 Sys::Syslog::setlogsock('unix');
820 Sys::Syslog::openlog('ikiwiki', '', 'user');
824 # keep a copy to avoid editing the original config repeatedly
825 my $wikiname = $config{wikiname};
826 utf8::encode($wikiname);
827 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
830 print STDERR "failed to syslog: $@" unless $log_failed;
836 elsif (! $config{cgi}) {
840 return print STDERR "@_\n";
844 sub possibly_foolish_untaint ($) {
846 my ($untainted)=$tainted=~/(.*)/s;
866 return exists $pagesources{$page} &&
867 $pagesources{$page} =~ /\._([^.]+)$/;
873 if ($file =~ /\.([^.]+)$/) {
874 return $1 if exists $hooks{htmlize}{$1};
876 my $base=basename($file);
877 if (exists $hooks{htmlize}{$base} &&
878 $hooks{htmlize}{$base}{noextension}) {
889 if (exists $pagename_cache{$file}) {
890 return $pagename_cache{$file};
893 my $type=pagetype($file);
895 $page=~s/\Q.$type\E*$//
896 if defined $type && !$hooks{htmlize}{$type}{keepextension}
897 && !$hooks{htmlize}{$type}{noextension};
898 if ($config{indexpages} && $page=~/(.*)\/index$/) {
902 $pagename_cache{$file} = $page;
906 sub newpagefile ($$) {
910 if (! $config{indexpages} || $page eq 'index') {
911 return $page.".".$type;
914 return $page."/index.".$type;
918 sub targetpage ($$;$) {
923 if (defined $filename) {
924 return $page."/".$filename.".".$ext;
926 elsif (! $config{usedirs} || $page eq 'index') {
927 return $page.".".$ext;
930 return $page."/index.".$ext;
937 return targetpage($page, $config{htmlext});
944 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
945 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
946 return "$dir/$file", stat(_) if -e "$dir/$file";
948 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
953 return (srcfile_stat(@_))[0];
956 sub add_literal_underlay ($) {
959 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
960 unshift @{$config{underlaydirs}}, $dir;
964 sub add_underlay ($) {
968 $dir="$config{underlaydirbase}/$dir";
971 add_literal_underlay($dir);
972 # why does it return 1? we just don't know
976 sub readfile ($;$$) {
982 error("cannot read a symlink ($file)");
986 open (my $in, "<", $file) || error("failed to read $file: $!");
987 binmode($in) if ($binary);
988 return \*$in if $wantfd;
990 # check for invalid utf-8, and toss it back to avoid crashes
991 if (! utf8::valid($ret)) {
992 $ret=encode_utf8($ret);
994 close $in || error("failed to read $file: $!");
998 sub prep_writefile ($$) {
1003 while (length $test) {
1004 if (-l "$destdir/$test") {
1005 error("cannot write to a symlink ($test)");
1007 if (-f _ && $test ne $file) {
1008 # Remove conflicting file.
1009 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1010 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1012 unlink("$destdir/$test");
1018 $test=dirname($test);
1021 my $dir=dirname("$destdir/$file");
1024 foreach my $s (split(m!/+!, $dir)) {
1027 mkdir($d) || error("failed to create directory $d: $!");
1035 sub writefile ($$$;$$) {
1036 my $file=shift; # can include subdirs
1037 my $destdir=shift; # directory to put file in
1042 prep_writefile($file, $destdir);
1044 my $newfile="$destdir/$file.ikiwiki-new";
1046 error("cannot write to a symlink ($newfile)");
1049 my $cleanup = sub { unlink($newfile) };
1050 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1051 binmode($out) if ($binary);
1053 $writer->(\*$out, $cleanup);
1056 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1058 close $out || error("failed saving $newfile: $!", $cleanup);
1059 rename($newfile, "$destdir/$file") ||
1060 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1066 sub will_render ($$;$) {
1071 # Important security check for independently created files.
1072 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1073 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1074 my $from_other_page=0;
1075 # Expensive, but rarely runs.
1076 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1079 dirname($_) eq $dest
1080 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1086 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1087 unless $from_other_page;
1090 # If $dest exists as a directory, remove conflicting files in it
1091 # rendered from other pages.
1093 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1094 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1095 if (dirname($f) eq $dest) {
1096 unlink("$config{destdir}/$f");
1097 rmdir(dirname("$config{destdir}/$f"));
1103 if (! $clear || $cleared{$page}) {
1104 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1107 foreach my $old (@{$renderedfiles{$page}}) {
1108 delete $destsources{$old};
1110 $renderedfiles{$page}=[$dest];
1113 $destsources{$dest}=$page;
1123 if ($link=~s/^\/+//) {
1131 $l.="/" if length $l;
1134 if (exists $pagesources{$l}) {
1137 elsif (exists $pagecase{lc $l}) {
1138 return $pagecase{lc $l};
1140 } while $cwd=~s{/?[^/]+$}{};
1142 if (length $config{userdir}) {
1143 my $l = "$config{userdir}/".lc($link);
1144 if (exists $pagesources{$l}) {
1147 elsif (exists $pagecase{lc $l}) {
1148 return $pagecase{lc $l};
1152 #print STDERR "warning: page $page, broken link: $link\n";
1156 sub isinlinableimage ($) {
1159 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1162 sub pagetitle ($;$) {
1164 my $unescaped=shift;
1167 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1170 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1178 # support use w/o %config set
1179 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1180 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1186 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1187 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1194 my $cgiurl=$local_cgiurl;
1196 if (exists $params{cgiurl}) {
1197 $cgiurl=$params{cgiurl};
1198 delete $params{cgiurl};
1206 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1209 sub cgiurl_abs (@) {
1211 URI->new_abs(cgiurl(@_), $config{cgiurl});
1217 return $local_url if ! defined $page;
1219 $page=htmlpage($page);
1221 $page=~s/[^\/]+\//..\//g;
1229 return $url unless defined $urlbase && length $urlbase;
1232 URI->new_abs($url, $urlbase)->as_string;
1236 # Work around very innefficient behavior in File::Spec if abs2rel
1237 # is passed two relative paths. It's much faster if paths are
1238 # absolute! (Debian bug #376658; fixed in debian unstable now)
1243 my $ret=File::Spec->abs2rel($path, $base);
1244 $ret=~s/^// if defined $ret;
1248 sub displaytime ($;$$) {
1249 # Plugins can override this function to mark up the time to
1251 my $time=formattime($_[0], $_[1]);
1252 if ($config{html5}) {
1253 return '<time datetime="'.date_3339($_[0]).'"'.
1254 ($_[2] ? ' pubdate="pubdate"' : '').
1255 '>'.$time.'</time>';
1258 return '<span class="date">'.$time.'</span>';
1262 sub formattime ($;$) {
1263 # Plugins can override this function to format the time.
1266 if (! defined $format) {
1267 $format=$config{timeformat};
1270 return strftime_utf8($format, localtime($time));
1273 my $strftime_encoding;
1275 # strftime doesn't know about encodings, so make sure
1276 # its output is properly treated as utf8.
1277 # Note that this does not handle utf-8 in the format string.
1278 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1279 unless defined $strftime_encoding;
1281 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1282 : POSIX::strftime(@_);
1288 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1289 POSIX::setlocale(&POSIX::LC_TIME, "C");
1290 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1291 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1295 sub beautify_urlpath ($) {
1298 # Ensure url is not an empty link, and if necessary,
1299 # add ./ to avoid colon confusion.
1300 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1304 if ($config{usedirs}) {
1305 $url =~ s!/index.$config{htmlext}$!/!;
1320 if (! $destsources{$to}) {
1325 return $config{url}.beautify_urlpath("/".$to);
1328 if (! defined $from) {
1329 my $u = $local_url || '';
1331 return $u.beautify_urlpath("/".$to);
1334 my $link = abs2rel($to, dirname(htmlpage($from)));
1336 return beautify_urlpath($link);
1339 sub isselflink ($$) {
1340 # Plugins can override this function to support special types
1345 return $page eq $link;
1348 sub htmllink ($$$;@) {
1349 my $lpage=shift; # the page doing the linking
1350 my $page=shift; # the page that will contain the link (different for inline)
1357 if (! $opts{forcesubpage}) {
1358 $bestlink=bestlink($lpage, $link);
1361 $bestlink="$lpage/".lc($link);
1365 if (defined $opts{linktext}) {
1366 $linktext=$opts{linktext};
1369 $linktext=pagetitle(basename($link));
1372 return "<span class=\"selflink\">$linktext</span>"
1373 if length $bestlink && isselflink($page, $bestlink) &&
1374 ! defined $opts{anchor};
1376 if (! $destsources{$bestlink}) {
1377 $bestlink=htmlpage($bestlink);
1379 if (! $destsources{$bestlink}) {
1381 if (length $config{cgiurl}) {
1382 $cgilink = "<a href=\"".
1387 )."\" rel=\"nofollow\">?</a>";
1389 return "<span class=\"createlink\">$cgilink$linktext</span>"
1393 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1394 $bestlink=beautify_urlpath($bestlink);
1396 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1397 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1400 if (defined $opts{anchor}) {
1401 $bestlink.="#".$opts{anchor};
1405 foreach my $attr (qw{rel class title}) {
1406 if (defined $opts{$attr}) {
1407 push @attrs, " $attr=\"$opts{$attr}\"";
1411 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1416 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1419 sub openiduser ($) {
1422 if (defined $user && $user =~ m!^https?://! &&
1423 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1426 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1427 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1430 # backcompat with old version
1431 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1432 $display=$oid->display;
1435 # Convert "user.somehost.com" to "user [somehost.com]"
1436 # (also "user.somehost.co.uk")
1437 if ($display !~ /\[/) {
1438 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1440 # Convert "http://somehost.com/user" to "user [somehost.com]".
1441 # (also "https://somehost.com/user/")
1442 if ($display !~ /\[/) {
1443 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1445 $display=~s!^https?://!!; # make sure this is removed
1446 eval q{use CGI 'escapeHTML'};
1448 return escapeHTML($display);
1453 sub htmlize ($$$$) {
1459 my $oneline = $content !~ /\n/;
1461 if (exists $hooks{htmlize}{$type}) {
1462 $content=$hooks{htmlize}{$type}{call}->(
1464 content => $content,
1468 error("htmlization of $type not supported");
1471 run_hooks(sanitize => sub {
1474 destpage => $destpage,
1475 content => $content,
1480 # hack to get rid of enclosing junk added by markdown
1481 # and other htmlizers/sanitizers
1482 $content=~s/^<p>//i;
1483 $content=~s/<\/p>\n*$//i;
1494 run_hooks(linkify => sub {
1497 destpage => $destpage,
1498 content => $content,
1506 our $preprocess_preview=0;
1507 sub preprocess ($$$;$$) {
1508 my $page=shift; # the page the data comes from
1509 my $destpage=shift; # the page the data will appear in (different for inline)
1514 # Using local because it needs to be set within any nested calls
1516 local $preprocess_preview=$preview if defined $preview;
1523 $params="" if ! defined $params;
1525 if (length $escape) {
1526 return "[[$prefix$command $params]]";
1528 elsif (exists $hooks{preprocess}{$command}) {
1529 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1530 # Note: preserve order of params, some plugins may
1531 # consider it significant.
1533 while ($params =~ m{
1534 (?:([-.\w]+)=)? # 1: named parameter key?
1536 """(.*?)""" # 2: triple-quoted value
1538 "([^"]*?)" # 3: single-quoted value
1540 '''(.*?)''' # 4: triple-single-quote
1542 <<([a-zA-Z]+)\n # 5: heredoc start
1543 (.*?)\n\5 # 6: heredoc value
1545 (\S+) # 7: unquoted value
1547 (?:\s+|$) # delimiter to next param
1557 elsif (defined $3) {
1560 elsif (defined $4) {
1563 elsif (defined $7) {
1566 elsif (defined $6) {
1571 push @params, $key, $val;
1574 push @params, $val, '';
1577 if ($preprocessing{$page}++ > 8) {
1578 # Avoid loops of preprocessed pages preprocessing
1579 # other pages that preprocess them, etc.
1580 return "[[!$command <span class=\"error\">".
1581 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1582 $page, $preprocessing{$page}).
1588 $hooks{preprocess}{$command}{call}->(
1591 destpage => $destpage,
1592 preview => $preprocess_preview,
1598 $ret="[[!$command <span class=\"error\">".
1599 gettext("Error").": $error"."</span>]]";
1603 # use void context during scan pass
1605 $hooks{preprocess}{$command}{call}->(
1608 destpage => $destpage,
1609 preview => $preprocess_preview,
1614 $preprocessing{$page}--;
1618 return "[[$prefix$command $params]]";
1623 if ($config{prefix_directives}) {
1626 \[\[(!) # directive open; 2: prefix
1627 ([-\w]+) # 3: command
1628 ( # 4: the parameters..
1629 \s+ # Must have space if parameters present
1631 (?:[-.\w]+=)? # named parameter key?
1633 """.*?""" # triple-quoted value
1635 "[^"]*?" # single-quoted value
1637 '''.*?''' # triple-single-quote
1639 <<([a-zA-Z]+)\n # 5: heredoc start
1640 (?:.*?)\n\5 # heredoc value
1642 [^"\s\]]+ # unquoted value
1644 \s* # whitespace or end
1647 *)? # 0 or more parameters
1648 \]\] # directive closed
1654 \[\[(!?) # directive open; 2: optional prefix
1655 ([-\w]+) # 3: command
1657 ( # 4: the parameters..
1659 (?:[-.\w]+=)? # named parameter key?
1661 """.*?""" # triple-quoted value
1663 "[^"]*?" # single-quoted value
1665 '''.*?''' # triple-single-quote
1667 <<([a-zA-Z]+)\n # 5: heredoc start
1668 (?:.*?)\n\5 # heredoc value
1670 [^"\s\]]+ # unquoted value
1672 \s* # whitespace or end
1675 *) # 0 or more parameters
1676 \]\] # directive closed
1680 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1689 run_hooks(filter => sub {
1690 $content=shift->(page => $page, destpage => $destpage,
1691 content => $content);
1697 sub check_canedit ($$$;$) {
1704 run_hooks(canedit => sub {
1705 return if defined $canedit;
1706 my $ret=shift->($page, $q, $session);
1711 elsif (ref $ret eq 'CODE') {
1712 $ret->() unless $nonfatal;
1715 elsif (defined $ret) {
1716 error($ret) unless $nonfatal;
1721 return defined $canedit ? $canedit : 1;
1724 sub check_content (@) {
1727 return 1 if ! exists $hooks{checkcontent}; # optimisation
1729 if (exists $pagesources{$params{page}}) {
1731 my %old=map { $_ => 1 }
1732 split("\n", readfile(srcfile($pagesources{$params{page}})));
1733 foreach my $line (split("\n", $params{content})) {
1734 push @diff, $line if ! exists $old{$line};
1736 $params{diff}=join("\n", @diff);
1740 run_hooks(checkcontent => sub {
1741 return if defined $ok;
1742 my $ret=shift->(%params);
1747 elsif (ref $ret eq 'CODE') {
1748 $ret->() unless $params{nonfatal};
1751 elsif (defined $ret) {
1752 error($ret) unless $params{nonfatal};
1758 return defined $ok ? $ok : 1;
1761 sub check_canchange (@) {
1763 my $cgi = $params{cgi};
1764 my $session = $params{session};
1765 my @changes = @{$params{changes}};
1768 foreach my $change (@changes) {
1769 # This untaint is safe because we check file_pruned and
1771 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1772 $file=possibly_foolish_untaint($file);
1773 if (! defined $file || ! length $file ||
1774 file_pruned($file)) {
1775 error(gettext("bad file name %s"), $file);
1778 my $type=pagetype($file);
1779 my $page=pagename($file) if defined $type;
1781 if ($change->{action} eq 'add') {
1785 if ($change->{action} eq 'change' ||
1786 $change->{action} eq 'add') {
1787 if (defined $page) {
1788 check_canedit($page, $cgi, $session);
1792 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1793 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1794 check_canedit($file, $cgi, $session);
1799 elsif ($change->{action} eq 'remove') {
1800 # check_canremove tests to see if the file is present
1801 # on disk. This will fail when a single commit adds a
1802 # file and then removes it again. Avoid the problem
1803 # by not testing the removal in such pairs of changes.
1804 # (The add is still tested, just to make sure that
1805 # no data is added to the repo that a web edit
1807 next if $newfiles{$file};
1809 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1810 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1811 check_canedit(defined $page ? $page : $file, $cgi, $session);
1816 error "unknown action ".$change->{action};
1819 error sprintf(gettext("you are not allowed to change %s"), $file);
1827 # Take an exclusive lock on the wiki to prevent multiple concurrent
1828 # run issues. The lock will be dropped on program exit.
1829 if (! -d $config{wikistatedir}) {
1830 mkdir($config{wikistatedir});
1832 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1833 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1834 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1835 debug("failed to get lock; waiting...");
1836 if (! flock($wikilock, LOCK_EX)) {
1837 error("failed to get lock");
1844 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1845 return close($wikilock) if $wikilock;
1851 sub commit_hook_enabled () {
1852 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1853 error("cannot write to $config{wikistatedir}/commitlock: $!");
1854 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1855 close($commitlock) || error("failed closing commitlock: $!");
1858 close($commitlock) || error("failed closing commitlock: $!");
1862 sub disable_commit_hook () {
1863 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1864 error("cannot write to $config{wikistatedir}/commitlock: $!");
1865 if (! flock($commitlock, 2)) { # LOCK_EX
1866 error("failed to get commit lock");
1871 sub enable_commit_hook () {
1872 return close($commitlock) if $commitlock;
1877 %oldrenderedfiles=%pagectime=();
1878 my $rebuild=$config{rebuild};
1880 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1881 %destsources=%renderedfiles=%pagecase=%pagestate=
1882 %depends_simple=%typedlinks=%oldtypedlinks=();
1885 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1886 if (-e "$config{wikistatedir}/index") {
1887 system("ikiwiki-transition", "indexdb", $config{srcdir});
1888 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1891 # gettime on first build
1892 $config{gettime}=1 unless defined $config{gettime};
1897 my $index=Storable::fd_retrieve($in);
1898 if (! defined $index) {
1903 if (exists $index->{version} && ! ref $index->{version}) {
1904 $pages=$index->{page};
1905 %wikistate=%{$index->{state}};
1906 # Handle plugins that got disabled by loading a new setup.
1907 if (exists $config{setupfile}) {
1908 require IkiWiki::Setup;
1909 IkiWiki::Setup::disabled_plugins(
1910 grep { ! $loaded_plugins{$_} } keys %wikistate);
1918 foreach my $src (keys %$pages) {
1919 my $d=$pages->{$src};
1921 if (exists $d->{page} && ! $rebuild) {
1925 $page=pagename($src);
1927 $pagectime{$page}=$d->{ctime};
1928 $pagesources{$page}=$src;
1930 $pagemtime{$page}=$d->{mtime};
1931 $renderedfiles{$page}=$d->{dest};
1932 if (exists $d->{links} && ref $d->{links}) {
1933 $links{$page}=$d->{links};
1934 $oldlinks{$page}=[@{$d->{links}}];
1936 if (ref $d->{depends_simple} eq 'ARRAY') {
1938 $depends_simple{$page}={
1939 map { $_ => 1 } @{$d->{depends_simple}}
1942 elsif (exists $d->{depends_simple}) {
1943 $depends_simple{$page}=$d->{depends_simple};
1945 if (exists $d->{dependslist}) {
1948 map { $_ => $DEPEND_CONTENT }
1949 @{$d->{dependslist}}
1952 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1954 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1956 elsif (exists $d->{depends}) {
1957 $depends{$page}=$d->{depends};
1959 if (exists $d->{state}) {
1960 $pagestate{$page}=$d->{state};
1962 if (exists $d->{typedlinks}) {
1963 $typedlinks{$page}=$d->{typedlinks};
1965 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1966 next unless %$links;
1967 $oldtypedlinks{$page}{$type} = {%$links};
1971 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1973 foreach my $page (keys %pagesources) {
1974 $pagecase{lc $page}=$page;
1976 foreach my $page (keys %renderedfiles) {
1977 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1979 $lastrev=$index->{lastrev};
1980 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1985 run_hooks(savestate => sub { shift->() });
1987 my @plugins=keys %loaded_plugins;
1989 if (! -d $config{wikistatedir}) {
1990 mkdir($config{wikistatedir});
1992 my $newfile="$config{wikistatedir}/indexdb.new";
1993 my $cleanup = sub { unlink($newfile) };
1994 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1997 foreach my $page (keys %pagemtime) {
1998 next unless $pagemtime{$page};
1999 my $src=$pagesources{$page};
2001 $index{page}{$src}={
2003 ctime => $pagectime{$page},
2004 mtime => $pagemtime{$page},
2005 dest => $renderedfiles{$page},
2006 links => $links{$page},
2009 if (exists $depends{$page}) {
2010 $index{page}{$src}{depends} = $depends{$page};
2013 if (exists $depends_simple{$page}) {
2014 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2017 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2018 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2021 if (exists $pagestate{$page}) {
2022 $index{page}{$src}{state}=$pagestate{$page};
2027 foreach my $id (@plugins) {
2028 $index{state}{$id}={}; # used to detect disabled plugins
2029 foreach my $key (keys %{$wikistate{$id}}) {
2030 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2034 $index{lastrev}=$lastrev;
2035 $index{underlayfiles}=\@underlayfiles;
2037 $index{version}="3";
2038 my $ret=Storable::nstore_fd(\%index, $out);
2039 return if ! defined $ret || ! $ret;
2040 close $out || error("failed saving to $newfile: $!", $cleanup);
2041 rename($newfile, "$config{wikistatedir}/indexdb") ||
2042 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2047 sub template_file ($) {
2050 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2052 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2053 $template=srcfile($pagesources{$tpage}, 1);
2057 $template=srcfile($tpage, 1);
2060 if (defined $template) {
2061 return $template, $tpage, 1 if wantarray;
2065 $name=~s:/::; # avoid path traversal
2066 foreach my $dir ($config{templatedir},
2067 "$installdir/share/ikiwiki/templates") {
2068 if (-e "$dir/$name") {
2069 $template="$dir/$name";
2073 if (defined $template) {
2074 return $template, $tpage if wantarray;
2082 sub template_depends ($$;@) {
2086 my ($filename, $tpage, $untrusted)=template_file($name);
2087 if (! defined $filename) {
2088 error(sprintf(gettext("template %s not found"), $name))
2091 if (defined $page && defined $tpage) {
2092 add_depends($page, $tpage);
2097 my $text_ref = shift;
2098 ${$text_ref} = decode_utf8(${$text_ref});
2099 run_hooks(readtemplate => sub {
2100 ${$text_ref} = shift->(
2103 content => ${$text_ref},
2104 untrusted => $untrusted,
2108 loop_context_vars => 1,
2109 die_on_bad_params => 0,
2110 parent_global_vars => 1,
2111 filename => $filename,
2113 ($untrusted ? (no_includes => 1) : ()),
2115 return @opts if wantarray;
2117 require HTML::Template;
2118 return HTML::Template->new(@opts);
2121 sub template ($;@) {
2122 template_depends(shift, undef, @_);
2125 sub templateactions ($$) {
2131 run_hooks(pageactions => sub {
2132 push @actions, map { { action => $_ } }
2133 grep { defined } shift->(page => $page);
2135 $template->param(actions => \@actions);
2137 if ($config{cgiurl} && exists $hooks{auth}) {
2138 $template->param(prefsurl => cgiurl(do => "prefs"));
2142 if ($have_actions || @actions) {
2143 $template->param(have_actions => 1);
2150 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2151 error 'hook requires type, call, and id parameters';
2154 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2156 $hooks{$param{type}}{$param{id}}=\%param;
2160 sub run_hooks ($$) {
2161 # Calls the given sub for each hook of the given type,
2162 # passing it the hook function to call.
2166 if (exists $hooks{$type}) {
2167 my (@first, @middle, @last);
2168 foreach my $id (keys %{$hooks{$type}}) {
2169 if ($hooks{$type}{$id}{first}) {
2172 elsif ($hooks{$type}{$id}{last}) {
2179 foreach my $id (@first, @middle, @last) {
2180 $sub->($hooks{$type}{$id}{call});
2188 $hooks{rcs}{rcs_update}{call}->(@_);
2191 sub rcs_prepedit ($) {
2192 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2195 sub rcs_commit (@) {
2196 $hooks{rcs}{rcs_commit}{call}->(@_);
2199 sub rcs_commit_staged (@) {
2200 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2204 $hooks{rcs}{rcs_add}{call}->(@_);
2207 sub rcs_remove ($) {
2208 $hooks{rcs}{rcs_remove}{call}->(@_);
2211 sub rcs_rename ($$) {
2212 $hooks{rcs}{rcs_rename}{call}->(@_);
2215 sub rcs_recentchanges ($) {
2216 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2219 sub rcs_diff ($;$) {
2220 $hooks{rcs}{rcs_diff}{call}->(@_);
2223 sub rcs_getctime ($) {
2224 $hooks{rcs}{rcs_getctime}{call}->(@_);
2227 sub rcs_getmtime ($) {
2228 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2231 sub rcs_receive () {
2232 $hooks{rcs}{rcs_receive}{call}->();
2235 sub add_depends ($$;$) {
2238 my $deptype=shift || $DEPEND_CONTENT;
2240 # Is the pagespec a simple page name?
2241 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2242 $pagespec !~ /[\s*?()!]/) {
2243 $depends_simple{$page}{lc $pagespec} |= $deptype;
2247 # Add explicit dependencies for influences.
2248 my $sub=pagespec_translate($pagespec);
2249 return unless defined $sub;
2250 foreach my $p (keys %pagesources) {
2251 my $r=$sub->($p, location => $page);
2252 my $i=$r->influences;
2253 my $static=$r->influences_static;
2254 foreach my $k (keys %$i) {
2255 next unless $r || $static || $k eq $page;
2256 $depends_simple{$page}{lc $k} |= $i->{$k};
2261 $depends{$page}{$pagespec} |= $deptype;
2267 foreach my $type (@_) {
2268 if ($type eq 'presence') {
2269 $deptype |= $DEPEND_PRESENCE;
2271 elsif ($type eq 'links') {
2272 $deptype |= $DEPEND_LINKS;
2274 elsif ($type eq 'content') {
2275 $deptype |= $DEPEND_CONTENT;
2281 my $file_prune_regexp;
2282 sub file_pruned ($) {
2285 if (defined $config{include} && length $config{include}) {
2286 return 0 if $file =~ m/$config{include}/;
2289 if (! defined $file_prune_regexp) {
2290 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2291 $file_prune_regexp=qr/$file_prune_regexp/;
2293 return $file =~ m/$file_prune_regexp/;
2296 sub define_gettext () {
2297 # If translation is needed, redefine the gettext function to do it.
2298 # Otherwise, it becomes a quick no-op.
2301 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2302 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2303 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2305 $gettext_obj=eval q{
2306 use Locale::gettext q{textdomain};
2307 Locale::gettext->domain('ikiwiki')
2312 no warnings 'redefine';
2314 $getobj->() if $getobj;
2316 $gettext_obj->get(shift);
2323 $getobj->() if $getobj;
2325 $gettext_obj->nget(@_);
2328 return ($_[2] == 1 ? $_[0] : $_[1])
2346 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2350 # Injects a new function into the symbol table to replace an
2351 # exported function.
2354 # This is deep ugly perl foo, beware.
2357 if (! defined $params{parent}) {
2358 $params{parent}='::';
2359 $params{old}=\&{$params{name}};
2360 $params{name}=~s/.*:://;
2362 my $parent=$params{parent};
2363 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2364 $ns = $params{parent} . $ns;
2365 inject(%params, parent => $ns) unless $ns eq '::main::';
2366 *{$ns . $params{name}} = $params{call}
2367 if exists ${$ns}{$params{name}} &&
2368 \&{${$ns}{$params{name}}} == $params{old};
2374 sub add_link ($$;$) {
2379 push @{$links{$page}}, $link
2380 unless grep { $_ eq $link } @{$links{$page}};
2382 if (defined $type) {
2383 $typedlinks{$page}{$type}{$link} = 1;
2387 sub add_autofile ($$$) {
2390 my $generator=shift;
2392 $autofiles{$file}{plugin}=$plugin;
2393 $autofiles{$file}{generator}=$generator;
2397 return LWP::UserAgent->new(
2398 cookie_jar => $config{cookiejar},
2399 env_proxy => 1, # respect proxy env vars
2400 agent => $config{useragent},
2404 sub sortspec_translate ($$) {
2406 my $reverse = shift;
2412 (-?) # group 1: perhaps negated
2415 \w+\([^\)]*\) # command(params)
2417 [^\s]+ # or anything else
2425 if ($word =~ m/^(\w+)\((.*)\)$/) {
2426 # command with parameters
2430 elsif ($word !~ m/^\w+$/) {
2431 error(sprintf(gettext("invalid sort type %s"), $word));
2442 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2443 if (defined $params) {
2444 push @data, $params;
2445 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2448 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2452 error(sprintf(gettext("unknown sort type %s"), $word));
2456 if (! length $code) {
2457 # undefined sorting method... sort arbitrarily
2466 return eval 'sub { '.$code.' }';
2469 sub pagespec_translate ($) {
2472 # Convert spec to perl code.
2476 \s* # ignore whitespace
2477 ( # 1: match a single word
2484 \w+\([^\)]*\) # command(params)
2486 [^\s()]+ # any other text
2488 \s* # ignore whitespace
2491 if (lc $word eq 'and') {
2494 elsif (lc $word eq 'or') {
2497 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2500 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2501 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2503 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2506 push @data, qq{unknown function in pagespec "$word"};
2507 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2512 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2516 if (! length $code) {
2517 $code="IkiWiki::FailReason->new('empty pagespec')";
2521 return eval 'sub { my $page=shift; '.$code.' }';
2524 sub pagespec_match ($$;@) {
2529 # Backwards compatability with old calling convention.
2531 unshift @params, 'location';
2534 my $sub=pagespec_translate($spec);
2535 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2537 return $sub->($page, @params);
2540 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2542 # Not exported yet, but could be in future if it is generally useful.
2543 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2544 # which is "more internal".
2545 sub sort_pages ($$;@) {
2549 $sort = sortspec_translate($sort, $params{reverse});
2550 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2553 sub pagespec_match_list ($$;@) {
2558 # Backwards compatability with old calling convention.
2560 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2561 $params{list}=$page;
2562 $page=$params{location}; # ugh!
2565 my $sub=pagespec_translate($pagespec);
2566 error "syntax error in pagespec \"$pagespec\""
2568 my $sort=sortspec_translate($params{sort}, $params{reverse})
2569 if defined $params{sort};
2572 if (exists $params{list}) {
2573 @candidates=exists $params{filter}
2574 ? grep { ! $params{filter}->($_) } @{$params{list}}
2578 @candidates=exists $params{filter}
2579 ? grep { ! $params{filter}->($_) } keys %pagesources
2580 : keys %pagesources;
2583 # clear params, remainder is passed to pagespec
2584 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2585 my $num=$params{num};
2586 delete @params{qw{num deptype reverse sort filter list}};
2588 # when only the top matches will be returned, it's efficient to
2589 # sort before matching to pagespec,
2590 if (defined $num && defined $sort) {
2591 @candidates=IkiWiki::SortSpec::sort_pages(
2592 $sort, @candidates);
2598 my $accum=IkiWiki::SuccessReason->new();
2599 foreach my $p (@candidates) {
2600 my $r=$sub->($p, %params, location => $page);
2601 error(sprintf(gettext("cannot match pages: %s"), $r))
2602 if $r->isa("IkiWiki::ErrorReason");
2603 unless ($r || $r->influences_static) {
2604 $r->remove_influence($p);
2609 last if defined $num && ++$count == $num;
2613 # Add simple dependencies for accumulated influences.
2614 my $i=$accum->influences;
2615 foreach my $k (keys %$i) {
2616 $depends_simple{$page}{lc $k} |= $i->{$k};
2619 # when all matches will be returned, it's efficient to
2620 # sort after matching
2621 if (! defined $num && defined $sort) {
2622 return IkiWiki::SortSpec::sort_pages(
2630 sub pagespec_valid ($) {
2633 return defined pagespec_translate($spec);
2637 my $re=quotemeta(shift);
2643 package IkiWiki::FailReason;
2646 '""' => sub { $_[0][0] },
2648 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2649 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2650 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2654 our @ISA = 'IkiWiki::SuccessReason';
2656 package IkiWiki::SuccessReason;
2658 # A blessed array-ref:
2660 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2662 # - if absent or false, the influences of this evaluation are "static",
2663 # see the influences_static method
2664 # - if true, they are dynamic (not static)
2665 # [1]{any other key}:
2666 # the dependency types of influences, as returned by the influences method
2669 # in string context, it's the human-readable reason
2670 '""' => sub { $_[0][0] },
2671 # in boolean context, SuccessReason is 1 and FailReason is 0
2673 # negating a result gives the opposite result with the same influences
2674 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2675 # A & B = (A ? B : A) with the influences of both
2676 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2677 # A | B = (A ? A : B) with the influences of both
2678 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2682 # SuccessReason->new("human-readable reason", page => deptype, ...)
2687 return bless [$value, {@_}], $class;
2690 # influences(): return a reference to a copy of the hash
2691 # { page => dependency type } describing the pages that indirectly influenced
2692 # this result, but would not cause a dependency through ikiwiki's core
2695 # See [[todo/dependency_types]] for extensive discussion of what this means.
2697 # influences(page => deptype, ...): remove all influences, replace them
2698 # with the arguments, and return a reference to a copy of the new influences.
2702 $this->[1]={@_} if @_;
2703 my %i=%{$this->[1]};
2708 # True if this result has the same influences whichever page it matches,
2709 # For instance, whether bar matches backlink(foo) is influenced only by
2710 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2711 # which does not mention bar anywhere.
2713 # False if this result would have different influences when matching
2714 # different pages. For instance, when testing whether link(foo) matches bar,
2715 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2716 # bar's links could change the outcome; so its influences are not the same
2717 # as when testing whether link(foo) matches baz.
2719 # Static influences are one of the things that make pagespec_match_list
2720 # more efficient than repeated calls to pagespec_match.
2722 sub influences_static {
2723 return ! $_[0][1]->{""};
2726 # Change the influences of $this to be the influences of "$this & $other"
2727 # or "$this | $other".
2729 # If both $this and $other are either successful or have influences,
2730 # or this is an "or" operation, the result has all the influences from
2731 # either of the arguments. It has dynamic influences if either argument
2732 # has dynamic influences.
2734 # If this is an "and" operation, and at least one argument is a
2735 # FailReason with no influences, the result has no influences, and they
2736 # are not dynamic. For instance, link(foo) matching bar is influenced
2737 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2738 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2739 # bar, because it would be false however often you edit bar.
2741 sub merge_influences {
2746 # This "if" is odd because it needs to avoid negating $this
2747 # or $other, which would alter the objects in-place. Be careful.
2748 if (! $anded || (($this || %{$this->[1]}) &&
2749 ($other || %{$other->[1]}))) {
2750 foreach my $influence (keys %{$other->[1]}) {
2751 $this->[1]{$influence} |= $other->[1]{$influence};
2760 # Change $this so it is not considered to be influenced by $torm.
2762 sub remove_influence {
2766 delete $this->[1]{$torm};
2769 package IkiWiki::ErrorReason;
2771 our @ISA = 'IkiWiki::FailReason';
2773 package IkiWiki::PageSpec;
2779 if ($path =~ m!^\.(/|$)!) {
2781 $from=~s#/?[^/]+$## if defined $from;
2783 $path="$from/$path" if defined $from && length $from;
2787 $path = "" unless defined $path;
2796 sub match_glob ($$;@) {
2801 $glob=derel($glob, $params{location});
2803 # Instead of converting the glob to a regex every time,
2804 # cache the compiled regex to save time.
2805 my $re=$glob_cache{$glob};
2806 unless (defined $re) {
2807 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2810 if (! IkiWiki::isinternal($page) || $params{internal}) {
2811 return IkiWiki::SuccessReason->new("$glob matches $page");
2814 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2818 return IkiWiki::FailReason->new("$glob does not match $page");
2822 sub match_internal ($$;@) {
2823 return match_glob(shift, shift, @_, internal => 1)
2826 sub match_page ($$;@) {
2828 my $match=match_glob($page, shift, @_);
2830 my $source=exists $IkiWiki::pagesources{$page} ?
2831 $IkiWiki::pagesources{$page} :
2832 $IkiWiki::delpagesources{$page};
2833 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2834 if (! defined $type) {
2835 return IkiWiki::FailReason->new("$page is not a page");
2841 sub match_link ($$;@) {
2846 $link=derel($link, $params{location});
2847 my $from=exists $params{location} ? $params{location} : '';
2848 my $linktype=$params{linktype};
2850 if (defined $linktype) {
2851 $qualifier=" with type $linktype";
2854 my $links = $IkiWiki::links{$page};
2855 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2856 unless $links && @{$links};
2857 my $bestlink = IkiWiki::bestlink($from, $link);
2858 foreach my $p (@{$links}) {
2859 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2861 if (length $bestlink) {
2862 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2863 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2867 if (match_glob($p, $link, %params)) {
2868 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2870 my ($p_rel)=$p=~/^\/?(.*)/;
2872 if (match_glob($p_rel, $link, %params)) {
2873 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2877 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2880 sub match_backlink ($$;@) {
2884 if ($testpage eq '.') {
2885 $testpage = $params{'location'}
2887 my $ret=match_link($testpage, $page, @_);
2888 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2892 sub match_created_before ($$;@) {
2897 $testpage=derel($testpage, $params{location});
2899 if (exists $IkiWiki::pagectime{$testpage}) {
2900 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2901 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2904 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2908 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2912 sub match_created_after ($$;@) {
2917 $testpage=derel($testpage, $params{location});
2919 if (exists $IkiWiki::pagectime{$testpage}) {
2920 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2921 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2924 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2928 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2932 sub match_creation_day ($$;@) {
2935 if ($d !~ /^\d+$/) {
2936 return IkiWiki::ErrorReason->new("invalid day $d");
2938 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2939 return IkiWiki::SuccessReason->new('creation_day matched');
2942 return IkiWiki::FailReason->new('creation_day did not match');
2946 sub match_creation_month ($$;@) {
2949 if ($m !~ /^\d+$/) {
2950 return IkiWiki::ErrorReason->new("invalid month $m");
2952 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2953 return IkiWiki::SuccessReason->new('creation_month matched');
2956 return IkiWiki::FailReason->new('creation_month did not match');
2960 sub match_creation_year ($$;@) {
2963 if ($y !~ /^\d+$/) {
2964 return IkiWiki::ErrorReason->new("invalid year $y");
2966 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2967 return IkiWiki::SuccessReason->new('creation_year matched');
2970 return IkiWiki::FailReason->new('creation_year did not match');
2974 sub match_user ($$;@) {
2979 if (! exists $params{user}) {
2980 return IkiWiki::ErrorReason->new("no user specified");
2983 my $regexp=IkiWiki::glob2re($user);
2985 if (defined $params{user} && $params{user}=~$regexp) {
2986 return IkiWiki::SuccessReason->new("user is $user");
2988 elsif (! defined $params{user}) {
2989 return IkiWiki::FailReason->new("not logged in");
2992 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2996 sub match_admin ($$;@) {
3001 if (! exists $params{user}) {
3002 return IkiWiki::ErrorReason->new("no user specified");
3005 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3006 return IkiWiki::SuccessReason->new("user is an admin");
3008 elsif (! defined $params{user}) {
3009 return IkiWiki::FailReason->new("not logged in");
3012 return IkiWiki::FailReason->new("user is not an admin");
3016 sub match_ip ($$;@) {
3021 if (! exists $params{ip}) {
3022 return IkiWiki::ErrorReason->new("no IP specified");
3025 my $regexp=IkiWiki::glob2re(lc $ip);
3027 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3028 return IkiWiki::SuccessReason->new("IP is $ip");
3031 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3035 package IkiWiki::SortSpec;
3037 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3038 # are easily available in this namespace, for cmp functions to use them.
3045 IkiWiki::pagetitle(IkiWiki::basename($a))
3047 IkiWiki::pagetitle(IkiWiki::basename($b))
3050 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3051 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3052 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }