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)",
573 if ($config{libdirs}) {
574 @libdirs = @{$config{libdirs}};
576 if (length $config{libdir}) {
577 push @libdirs, $config{libdir};
582 sub defaultconfig () {
585 foreach my $key (keys %s) {
586 push @ret, $key, $s{$key}->{default};
591 # URL to top of wiki as a path starting with /, valid from any wiki page or
592 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
594 # URL to CGI script, similar to $local_url
598 # locale stuff; avoid LC_ALL since it overrides everything
599 if (defined $ENV{LC_ALL}) {
600 $ENV{LANG} = $ENV{LC_ALL};
603 if (defined $config{locale}) {
604 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
605 $ENV{LANG}=$config{locale};
610 if (! defined $config{wiki_file_regexp}) {
611 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
614 if (ref $config{ENV} eq 'HASH') {
615 foreach my $val (keys %{$config{ENV}}) {
616 $ENV{$val}=$config{ENV}{$val};
619 if (defined $config{timezone} && length $config{timezone}) {
620 $ENV{TZ}=$config{timezone};
623 $config{timezone}=$ENV{TZ};
626 if ($config{w3mmode}) {
627 eval q{use Cwd q{abs_path}};
629 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
630 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
631 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
632 unless $config{cgiurl} =~ m!file:///!;
633 $config{url}="file://".$config{destdir};
636 if ($config{cgi} && ! length $config{url}) {
637 error(gettext("Must specify url to wiki with --url when using --cgi"));
640 if (defined $config{url} && length $config{url}) {
642 my $baseurl = URI->new($config{url});
644 $local_url = $baseurl->path . "/";
645 $local_cgiurl = undef;
647 if (length $config{cgiurl}) {
648 my $cgiurl = URI->new($config{cgiurl});
650 $local_cgiurl = $cgiurl->path;
652 if ($cgiurl->scheme eq 'https' &&
653 $baseurl->scheme eq 'http') {
654 # We assume that the same content is available
655 # over both http and https, because if it
656 # wasn't, accessing the static content
657 # from the CGI would be mixed-content,
658 # which would be a security flaw.
660 if ($cgiurl->authority ne $baseurl->authority) {
661 # use protocol-relative URL for
663 $local_url = "$config{url}/";
664 $local_url =~ s{^http://}{//};
666 # else use host-relative URL for static content
668 # either way, CGI needs to be absolute
669 $local_cgiurl = $config{cgiurl};
671 elsif ($cgiurl->scheme ne $baseurl->scheme) {
672 # too far apart, fall back to absolute URLs
673 $local_url = "$config{url}/";
674 $local_cgiurl = $config{cgiurl};
676 elsif ($cgiurl->authority ne $baseurl->authority) {
677 # slightly too far apart, fall back to
678 # protocol-relative URLs
679 $local_url = "$config{url}/";
680 $local_url =~ s{^https?://}{//};
681 $local_cgiurl = $config{cgiurl};
682 $local_cgiurl =~ s{^https?://}{//};
684 # else keep host-relative URLs
687 $local_url =~ s{//$}{/};
690 $local_cgiurl = $config{cgiurl};
693 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
694 unless exists $config{wikistatedir} && defined $config{wikistatedir};
696 if (defined $config{umask}) {
697 my $u = possibly_foolish_untaint($config{umask});
699 if ($u =~ m/^\d+$/) {
702 elsif ($u eq 'private') {
705 elsif ($u eq 'group') {
708 elsif ($u eq 'public') {
712 error(sprintf(gettext("unsupported umask setting %s"), $u));
716 run_hooks(checkconfig => sub { shift->() });
724 foreach my $dir (@INC, getlibdirs()) {
725 next unless defined $dir && length $dir;
726 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
727 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
731 foreach my $dir (getlibdirs(), "$installdir/lib/ikiwiki") {
732 next unless defined $dir && length $dir;
733 foreach my $file (glob("$dir/plugins/*")) {
734 $ret{basename($file)}=1 if -x $file;
742 foreach my $dir (getlibdirs()) {
743 unshift @INC, possibly_foolish_untaint($dir);
746 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
751 if (exists $hooks{rcs}) {
752 error(gettext("cannot use multiple rcs plugins"));
754 loadplugin($config{rcs});
756 if (! exists $hooks{rcs}) {
760 run_hooks(getopt => sub { shift->() });
761 if (grep /^-/, @ARGV) {
762 print STDERR "Unknown option (or missing parameter): $_\n"
763 foreach grep /^-/, @ARGV;
770 sub loadplugin ($;$) {
774 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
776 foreach my $possiblytainteddir (getlibdirs(), "$installdir/lib/ikiwiki") {
777 my $dir = possibly_foolish_untaint($possiblytainteddir);
778 if (defined $dir && -x "$dir/plugins/$plugin") {
779 eval { require IkiWiki::Plugin::external };
782 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
784 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
785 $loaded_plugins{$plugin}=1;
790 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
793 error("Failed to load plugin $mod: $@");
795 $loaded_plugins{$plugin}=1;
802 log_message('err' => $message) if $config{syslog};
803 if (defined $cleaner) {
810 return unless $config{verbose};
811 return log_message(debug => @_);
816 sub log_message ($$) {
819 if ($config{syslog}) {
822 Sys::Syslog::setlogsock('unix');
823 Sys::Syslog::openlog('ikiwiki', '', 'user');
827 # keep a copy to avoid editing the original config repeatedly
828 my $wikiname = $config{wikiname};
829 utf8::encode($wikiname);
830 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
833 print STDERR "failed to syslog: $@" unless $log_failed;
839 elsif (! $config{cgi}) {
843 return print STDERR "@_\n";
847 sub possibly_foolish_untaint ($) {
849 my ($untainted)=$tainted=~/(.*)/s;
869 return exists $pagesources{$page} &&
870 $pagesources{$page} =~ /\._([^.]+)$/;
876 if ($file =~ /\.([^.]+)$/) {
877 return $1 if exists $hooks{htmlize}{$1};
879 my $base=basename($file);
880 if (exists $hooks{htmlize}{$base} &&
881 $hooks{htmlize}{$base}{noextension}) {
892 if (exists $pagename_cache{$file}) {
893 return $pagename_cache{$file};
896 my $type=pagetype($file);
898 $page=~s/\Q.$type\E*$//
899 if defined $type && !$hooks{htmlize}{$type}{keepextension}
900 && !$hooks{htmlize}{$type}{noextension};
901 if ($config{indexpages} && $page=~/(.*)\/index$/) {
905 $pagename_cache{$file} = $page;
909 sub newpagefile ($$) {
913 if (! $config{indexpages} || $page eq 'index') {
914 return $page.".".$type;
917 return $page."/index.".$type;
921 sub targetpage ($$;$) {
926 if (defined $filename) {
927 return $page."/".$filename.".".$ext;
929 elsif (! $config{usedirs} || $page eq 'index') {
930 return $page.".".$ext;
933 return $page."/index.".$ext;
940 return targetpage($page, $config{htmlext});
947 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
948 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
949 return "$dir/$file", stat(_) if -e "$dir/$file";
951 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
956 return (srcfile_stat(@_))[0];
959 sub add_literal_underlay ($) {
962 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
963 unshift @{$config{underlaydirs}}, $dir;
967 sub add_underlay ($) {
971 $dir="$config{underlaydirbase}/$dir";
974 add_literal_underlay($dir);
975 # why does it return 1? we just don't know
979 sub readfile ($;$$) {
985 error("cannot read a symlink ($file)");
989 open (my $in, "<", $file) || error("failed to read $file: $!");
990 binmode($in) if ($binary);
991 return \*$in if $wantfd;
993 # check for invalid utf-8, and toss it back to avoid crashes
994 if (! utf8::valid($ret)) {
995 $ret=encode_utf8($ret);
997 close $in || error("failed to read $file: $!");
1001 sub prep_writefile ($$) {
1006 while (length $test) {
1007 if (-l "$destdir/$test") {
1008 error("cannot write to a symlink ($test)");
1010 if (-f _ && $test ne $file) {
1011 # Remove conflicting file.
1012 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1013 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1015 unlink("$destdir/$test");
1021 $test=dirname($test);
1024 my $dir=dirname("$destdir/$file");
1027 foreach my $s (split(m!/+!, $dir)) {
1030 mkdir($d) || error("failed to create directory $d: $!");
1038 sub writefile ($$$;$$) {
1039 my $file=shift; # can include subdirs
1040 my $destdir=shift; # directory to put file in
1045 prep_writefile($file, $destdir);
1047 my $newfile="$destdir/$file.ikiwiki-new";
1049 error("cannot write to a symlink ($newfile)");
1052 my $cleanup = sub { unlink($newfile) };
1053 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1054 binmode($out) if ($binary);
1056 $writer->(\*$out, $cleanup);
1059 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1061 close $out || error("failed saving $newfile: $!", $cleanup);
1062 rename($newfile, "$destdir/$file") ||
1063 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1069 sub will_render ($$;$) {
1074 # Important security check for independently created files.
1075 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1076 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1077 my $from_other_page=0;
1078 # Expensive, but rarely runs.
1079 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1082 dirname($_) eq $dest
1083 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1089 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1090 unless $from_other_page;
1093 # If $dest exists as a directory, remove conflicting files in it
1094 # rendered from other pages.
1096 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1097 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1098 if (dirname($f) eq $dest) {
1099 unlink("$config{destdir}/$f");
1100 rmdir(dirname("$config{destdir}/$f"));
1106 if (! $clear || $cleared{$page}) {
1107 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1110 foreach my $old (@{$renderedfiles{$page}}) {
1111 delete $destsources{$old};
1113 $renderedfiles{$page}=[$dest];
1116 $destsources{$dest}=$page;
1126 if ($link=~s/^\/+//) {
1134 $l.="/" if length $l;
1137 if (exists $pagesources{$l}) {
1140 elsif (exists $pagecase{lc $l}) {
1141 return $pagecase{lc $l};
1143 } while $cwd=~s{/?[^/]+$}{};
1145 if (length $config{userdir}) {
1146 my $l = "$config{userdir}/".lc($link);
1147 if (exists $pagesources{$l}) {
1150 elsif (exists $pagecase{lc $l}) {
1151 return $pagecase{lc $l};
1155 #print STDERR "warning: page $page, broken link: $link\n";
1159 sub isinlinableimage ($) {
1162 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1165 sub pagetitle ($;$) {
1167 my $unescaped=shift;
1170 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1173 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1181 # support use w/o %config set
1182 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1183 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1189 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1190 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1197 my $cgiurl=$local_cgiurl;
1199 if (exists $params{cgiurl}) {
1200 $cgiurl=$params{cgiurl};
1201 delete $params{cgiurl};
1209 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1212 sub cgiurl_abs (@) {
1214 URI->new_abs(cgiurl(@_), $config{cgiurl});
1220 return $local_url if ! defined $page;
1222 $page=htmlpage($page);
1224 $page=~s/[^\/]+\//..\//g;
1232 return $url unless defined $urlbase && length $urlbase;
1235 URI->new_abs($url, $urlbase)->as_string;
1239 # Work around very innefficient behavior in File::Spec if abs2rel
1240 # is passed two relative paths. It's much faster if paths are
1241 # absolute! (Debian bug #376658; fixed in debian unstable now)
1246 my $ret=File::Spec->abs2rel($path, $base);
1247 $ret=~s/^// if defined $ret;
1251 sub displaytime ($;$$) {
1252 # Plugins can override this function to mark up the time to
1254 my $time=formattime($_[0], $_[1]);
1255 if ($config{html5}) {
1256 return '<time datetime="'.date_3339($_[0]).'"'.
1257 ($_[2] ? ' pubdate="pubdate"' : '').
1258 '>'.$time.'</time>';
1261 return '<span class="date">'.$time.'</span>';
1265 sub formattime ($;$) {
1266 # Plugins can override this function to format the time.
1269 if (! defined $format) {
1270 $format=$config{timeformat};
1273 return strftime_utf8($format, localtime($time));
1276 my $strftime_encoding;
1278 # strftime doesn't know about encodings, so make sure
1279 # its output is properly treated as utf8.
1280 # Note that this does not handle utf-8 in the format string.
1281 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1282 unless defined $strftime_encoding;
1284 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1285 : POSIX::strftime(@_);
1291 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1292 POSIX::setlocale(&POSIX::LC_TIME, "C");
1293 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1294 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1298 sub beautify_urlpath ($) {
1301 # Ensure url is not an empty link, and if necessary,
1302 # add ./ to avoid colon confusion.
1303 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1307 if ($config{usedirs}) {
1308 $url =~ s!/index.$config{htmlext}$!/!;
1323 if (! $destsources{$to}) {
1328 return $config{url}.beautify_urlpath("/".$to);
1331 if (! defined $from) {
1332 my $u = $local_url || '';
1334 return $u.beautify_urlpath("/".$to);
1337 my $link = abs2rel($to, dirname(htmlpage($from)));
1339 return beautify_urlpath($link);
1342 sub isselflink ($$) {
1343 # Plugins can override this function to support special types
1348 return $page eq $link;
1351 sub htmllink ($$$;@) {
1352 my $lpage=shift; # the page doing the linking
1353 my $page=shift; # the page that will contain the link (different for inline)
1360 if (! $opts{forcesubpage}) {
1361 $bestlink=bestlink($lpage, $link);
1364 $bestlink="$lpage/".lc($link);
1368 if (defined $opts{linktext}) {
1369 $linktext=$opts{linktext};
1372 $linktext=pagetitle(basename($link));
1375 return "<span class=\"selflink\">$linktext</span>"
1376 if length $bestlink && isselflink($page, $bestlink) &&
1377 ! defined $opts{anchor};
1379 if (! $destsources{$bestlink}) {
1380 $bestlink=htmlpage($bestlink);
1382 if (! $destsources{$bestlink}) {
1384 if (length $config{cgiurl}) {
1385 $cgilink = "<a href=\"".
1390 )."\" rel=\"nofollow\">?</a>";
1392 return "<span class=\"createlink\">$cgilink$linktext</span>"
1396 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1397 $bestlink=beautify_urlpath($bestlink);
1399 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1400 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1403 if (defined $opts{anchor}) {
1404 $bestlink.="#".$opts{anchor};
1408 foreach my $attr (qw{rel class title}) {
1409 if (defined $opts{$attr}) {
1410 push @attrs, " $attr=\"$opts{$attr}\"";
1414 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1419 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1422 sub openiduser ($) {
1425 if (defined $user && $user =~ m!^https?://! &&
1426 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1429 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1430 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1433 # backcompat with old version
1434 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1435 $display=$oid->display;
1438 # Convert "user.somehost.com" to "user [somehost.com]"
1439 # (also "user.somehost.co.uk")
1440 if ($display !~ /\[/) {
1441 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1443 # Convert "http://somehost.com/user" to "user [somehost.com]".
1444 # (also "https://somehost.com/user/")
1445 if ($display !~ /\[/) {
1446 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1448 $display=~s!^https?://!!; # make sure this is removed
1449 eval q{use CGI 'escapeHTML'};
1451 return escapeHTML($display);
1456 sub htmlize ($$$$) {
1462 my $oneline = $content !~ /\n/;
1464 if (exists $hooks{htmlize}{$type}) {
1465 $content=$hooks{htmlize}{$type}{call}->(
1467 content => $content,
1471 error("htmlization of $type not supported");
1474 run_hooks(sanitize => sub {
1477 destpage => $destpage,
1478 content => $content,
1483 # hack to get rid of enclosing junk added by markdown
1484 # and other htmlizers/sanitizers
1485 $content=~s/^<p>//i;
1486 $content=~s/<\/p>\n*$//i;
1497 run_hooks(linkify => sub {
1500 destpage => $destpage,
1501 content => $content,
1509 our $preprocess_preview=0;
1510 sub preprocess ($$$;$$) {
1511 my $page=shift; # the page the data comes from
1512 my $destpage=shift; # the page the data will appear in (different for inline)
1517 # Using local because it needs to be set within any nested calls
1519 local $preprocess_preview=$preview if defined $preview;
1526 $params="" if ! defined $params;
1528 if (length $escape) {
1529 return "[[$prefix$command $params]]";
1531 elsif (exists $hooks{preprocess}{$command}) {
1532 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1533 # Note: preserve order of params, some plugins may
1534 # consider it significant.
1536 while ($params =~ m{
1537 (?:([-.\w]+)=)? # 1: named parameter key?
1539 """(.*?)""" # 2: triple-quoted value
1541 "([^"]*?)" # 3: single-quoted value
1543 '''(.*?)''' # 4: triple-single-quote
1545 <<([a-zA-Z]+)\n # 5: heredoc start
1546 (.*?)\n\5 # 6: heredoc value
1548 (\S+) # 7: unquoted value
1550 (?:\s+|$) # delimiter to next param
1560 elsif (defined $3) {
1563 elsif (defined $4) {
1566 elsif (defined $7) {
1569 elsif (defined $6) {
1574 push @params, $key, $val;
1577 push @params, $val, '';
1580 if ($preprocessing{$page}++ > 8) {
1581 # Avoid loops of preprocessed pages preprocessing
1582 # other pages that preprocess them, etc.
1583 return "[[!$command <span class=\"error\">".
1584 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1585 $page, $preprocessing{$page}).
1591 $hooks{preprocess}{$command}{call}->(
1594 destpage => $destpage,
1595 preview => $preprocess_preview,
1601 $ret="[[!$command <span class=\"error\">".
1602 gettext("Error").": $error"."</span>]]";
1606 # use void context during scan pass
1608 $hooks{preprocess}{$command}{call}->(
1611 destpage => $destpage,
1612 preview => $preprocess_preview,
1617 $preprocessing{$page}--;
1621 return "[[$prefix$command $params]]";
1626 if ($config{prefix_directives}) {
1629 \[\[(!) # directive open; 2: prefix
1630 ([-\w]+) # 3: command
1631 ( # 4: the parameters..
1632 \s+ # Must have space if parameters present
1634 (?:[-.\w]+=)? # named parameter key?
1636 """.*?""" # triple-quoted value
1638 "[^"]*?" # single-quoted value
1640 '''.*?''' # triple-single-quote
1642 <<([a-zA-Z]+)\n # 5: heredoc start
1643 (?:.*?)\n\5 # heredoc value
1645 [^"\s\]]+ # unquoted value
1647 \s* # whitespace or end
1650 *)? # 0 or more parameters
1651 \]\] # directive closed
1657 \[\[(!?) # directive open; 2: optional prefix
1658 ([-\w]+) # 3: command
1660 ( # 4: the parameters..
1662 (?:[-.\w]+=)? # named parameter key?
1664 """.*?""" # triple-quoted value
1666 "[^"]*?" # single-quoted value
1668 '''.*?''' # triple-single-quote
1670 <<([a-zA-Z]+)\n # 5: heredoc start
1671 (?:.*?)\n\5 # heredoc value
1673 [^"\s\]]+ # unquoted value
1675 \s* # whitespace or end
1678 *) # 0 or more parameters
1679 \]\] # directive closed
1683 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1692 run_hooks(filter => sub {
1693 $content=shift->(page => $page, destpage => $destpage,
1694 content => $content);
1700 sub check_canedit ($$$;$) {
1707 run_hooks(canedit => sub {
1708 return if defined $canedit;
1709 my $ret=shift->($page, $q, $session);
1714 elsif (ref $ret eq 'CODE') {
1715 $ret->() unless $nonfatal;
1718 elsif (defined $ret) {
1719 error($ret) unless $nonfatal;
1724 return defined $canedit ? $canedit : 1;
1727 sub check_content (@) {
1730 return 1 if ! exists $hooks{checkcontent}; # optimisation
1732 if (exists $pagesources{$params{page}}) {
1734 my %old=map { $_ => 1 }
1735 split("\n", readfile(srcfile($pagesources{$params{page}})));
1736 foreach my $line (split("\n", $params{content})) {
1737 push @diff, $line if ! exists $old{$line};
1739 $params{diff}=join("\n", @diff);
1743 run_hooks(checkcontent => sub {
1744 return if defined $ok;
1745 my $ret=shift->(%params);
1750 elsif (ref $ret eq 'CODE') {
1751 $ret->() unless $params{nonfatal};
1754 elsif (defined $ret) {
1755 error($ret) unless $params{nonfatal};
1761 return defined $ok ? $ok : 1;
1764 sub check_canchange (@) {
1766 my $cgi = $params{cgi};
1767 my $session = $params{session};
1768 my @changes = @{$params{changes}};
1771 foreach my $change (@changes) {
1772 # This untaint is safe because we check file_pruned and
1774 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1775 $file=possibly_foolish_untaint($file);
1776 if (! defined $file || ! length $file ||
1777 file_pruned($file)) {
1778 error(gettext("bad file name %s"), $file);
1781 my $type=pagetype($file);
1782 my $page=pagename($file) if defined $type;
1784 if ($change->{action} eq 'add') {
1788 if ($change->{action} eq 'change' ||
1789 $change->{action} eq 'add') {
1790 if (defined $page) {
1791 check_canedit($page, $cgi, $session);
1795 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1796 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1797 check_canedit($file, $cgi, $session);
1802 elsif ($change->{action} eq 'remove') {
1803 # check_canremove tests to see if the file is present
1804 # on disk. This will fail when a single commit adds a
1805 # file and then removes it again. Avoid the problem
1806 # by not testing the removal in such pairs of changes.
1807 # (The add is still tested, just to make sure that
1808 # no data is added to the repo that a web edit
1810 next if $newfiles{$file};
1812 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1813 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1814 check_canedit(defined $page ? $page : $file, $cgi, $session);
1819 error "unknown action ".$change->{action};
1822 error sprintf(gettext("you are not allowed to change %s"), $file);
1830 # Take an exclusive lock on the wiki to prevent multiple concurrent
1831 # run issues. The lock will be dropped on program exit.
1832 if (! -d $config{wikistatedir}) {
1833 mkdir($config{wikistatedir});
1835 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1836 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1837 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1838 debug("failed to get lock; waiting...");
1839 if (! flock($wikilock, LOCK_EX)) {
1840 error("failed to get lock");
1847 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1848 return close($wikilock) if $wikilock;
1854 sub commit_hook_enabled () {
1855 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1856 error("cannot write to $config{wikistatedir}/commitlock: $!");
1857 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1858 close($commitlock) || error("failed closing commitlock: $!");
1861 close($commitlock) || error("failed closing commitlock: $!");
1865 sub disable_commit_hook () {
1866 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1867 error("cannot write to $config{wikistatedir}/commitlock: $!");
1868 if (! flock($commitlock, 2)) { # LOCK_EX
1869 error("failed to get commit lock");
1874 sub enable_commit_hook () {
1875 return close($commitlock) if $commitlock;
1880 %oldrenderedfiles=%pagectime=();
1881 my $rebuild=$config{rebuild};
1883 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1884 %destsources=%renderedfiles=%pagecase=%pagestate=
1885 %depends_simple=%typedlinks=%oldtypedlinks=();
1888 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1889 if (-e "$config{wikistatedir}/index") {
1890 system("ikiwiki-transition", "indexdb", $config{srcdir});
1891 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1894 # gettime on first build
1895 $config{gettime}=1 unless defined $config{gettime};
1900 my $index=Storable::fd_retrieve($in);
1901 if (! defined $index) {
1906 if (exists $index->{version} && ! ref $index->{version}) {
1907 $pages=$index->{page};
1908 %wikistate=%{$index->{state}};
1909 # Handle plugins that got disabled by loading a new setup.
1910 if (exists $config{setupfile}) {
1911 require IkiWiki::Setup;
1912 IkiWiki::Setup::disabled_plugins(
1913 grep { ! $loaded_plugins{$_} } keys %wikistate);
1921 foreach my $src (keys %$pages) {
1922 my $d=$pages->{$src};
1924 if (exists $d->{page} && ! $rebuild) {
1928 $page=pagename($src);
1930 $pagectime{$page}=$d->{ctime};
1931 $pagesources{$page}=$src;
1933 $pagemtime{$page}=$d->{mtime};
1934 $renderedfiles{$page}=$d->{dest};
1935 if (exists $d->{links} && ref $d->{links}) {
1936 $links{$page}=$d->{links};
1937 $oldlinks{$page}=[@{$d->{links}}];
1939 if (ref $d->{depends_simple} eq 'ARRAY') {
1941 $depends_simple{$page}={
1942 map { $_ => 1 } @{$d->{depends_simple}}
1945 elsif (exists $d->{depends_simple}) {
1946 $depends_simple{$page}=$d->{depends_simple};
1948 if (exists $d->{dependslist}) {
1951 map { $_ => $DEPEND_CONTENT }
1952 @{$d->{dependslist}}
1955 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1957 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1959 elsif (exists $d->{depends}) {
1960 $depends{$page}=$d->{depends};
1962 if (exists $d->{state}) {
1963 $pagestate{$page}=$d->{state};
1965 if (exists $d->{typedlinks}) {
1966 $typedlinks{$page}=$d->{typedlinks};
1968 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1969 next unless %$links;
1970 $oldtypedlinks{$page}{$type} = {%$links};
1974 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1976 foreach my $page (keys %pagesources) {
1977 $pagecase{lc $page}=$page;
1979 foreach my $page (keys %renderedfiles) {
1980 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1982 $lastrev=$index->{lastrev};
1983 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1988 run_hooks(savestate => sub { shift->() });
1990 my @plugins=keys %loaded_plugins;
1992 if (! -d $config{wikistatedir}) {
1993 mkdir($config{wikistatedir});
1995 my $newfile="$config{wikistatedir}/indexdb.new";
1996 my $cleanup = sub { unlink($newfile) };
1997 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
2000 foreach my $page (keys %pagemtime) {
2001 next unless $pagemtime{$page};
2002 my $src=$pagesources{$page};
2004 $index{page}{$src}={
2006 ctime => $pagectime{$page},
2007 mtime => $pagemtime{$page},
2008 dest => $renderedfiles{$page},
2009 links => $links{$page},
2012 if (exists $depends{$page}) {
2013 $index{page}{$src}{depends} = $depends{$page};
2016 if (exists $depends_simple{$page}) {
2017 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2020 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2021 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2024 if (exists $pagestate{$page}) {
2025 $index{page}{$src}{state}=$pagestate{$page};
2030 foreach my $id (@plugins) {
2031 $index{state}{$id}={}; # used to detect disabled plugins
2032 foreach my $key (keys %{$wikistate{$id}}) {
2033 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2037 $index{lastrev}=$lastrev;
2038 $index{underlayfiles}=\@underlayfiles;
2040 $index{version}="3";
2041 my $ret=Storable::nstore_fd(\%index, $out);
2042 return if ! defined $ret || ! $ret;
2043 close $out || error("failed saving to $newfile: $!", $cleanup);
2044 rename($newfile, "$config{wikistatedir}/indexdb") ||
2045 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2050 sub template_file ($) {
2053 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2055 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2056 $template=srcfile($pagesources{$tpage}, 1);
2060 $template=srcfile($tpage, 1);
2063 if (defined $template) {
2064 return $template, $tpage, 1 if wantarray;
2068 $name=~s:/::; # avoid path traversal
2069 foreach my $dir ($config{templatedir},
2070 "$installdir/share/ikiwiki/templates") {
2071 if (-e "$dir/$name") {
2072 $template="$dir/$name";
2076 if (defined $template) {
2077 return $template, $tpage if wantarray;
2085 sub template_depends ($$;@) {
2089 my ($filename, $tpage, $untrusted)=template_file($name);
2090 if (! defined $filename) {
2091 error(sprintf(gettext("template %s not found"), $name))
2094 if (defined $page && defined $tpage) {
2095 add_depends($page, $tpage);
2100 my $text_ref = shift;
2101 ${$text_ref} = decode_utf8(${$text_ref});
2102 run_hooks(readtemplate => sub {
2103 ${$text_ref} = shift->(
2106 content => ${$text_ref},
2107 untrusted => $untrusted,
2111 loop_context_vars => 1,
2112 die_on_bad_params => 0,
2113 parent_global_vars => 1,
2114 filename => $filename,
2116 ($untrusted ? (no_includes => 1) : ()),
2118 return @opts if wantarray;
2120 require HTML::Template;
2121 return HTML::Template->new(@opts);
2124 sub template ($;@) {
2125 template_depends(shift, undef, @_);
2128 sub templateactions ($$) {
2134 run_hooks(pageactions => sub {
2135 push @actions, map { { action => $_ } }
2136 grep { defined } shift->(page => $page);
2138 $template->param(actions => \@actions);
2140 if ($config{cgiurl} && exists $hooks{auth}) {
2141 $template->param(prefsurl => cgiurl(do => "prefs"));
2145 if ($have_actions || @actions) {
2146 $template->param(have_actions => 1);
2153 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2154 error 'hook requires type, call, and id parameters';
2157 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2159 $hooks{$param{type}}{$param{id}}=\%param;
2163 sub run_hooks ($$) {
2164 # Calls the given sub for each hook of the given type,
2165 # passing it the hook function to call.
2169 if (exists $hooks{$type}) {
2170 my (@first, @middle, @last);
2171 foreach my $id (keys %{$hooks{$type}}) {
2172 if ($hooks{$type}{$id}{first}) {
2175 elsif ($hooks{$type}{$id}{last}) {
2182 foreach my $id (@first, @middle, @last) {
2183 $sub->($hooks{$type}{$id}{call});
2191 $hooks{rcs}{rcs_update}{call}->(@_);
2194 sub rcs_prepedit ($) {
2195 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2198 sub rcs_commit (@) {
2199 $hooks{rcs}{rcs_commit}{call}->(@_);
2202 sub rcs_commit_staged (@) {
2203 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2207 $hooks{rcs}{rcs_add}{call}->(@_);
2210 sub rcs_remove ($) {
2211 $hooks{rcs}{rcs_remove}{call}->(@_);
2214 sub rcs_rename ($$) {
2215 $hooks{rcs}{rcs_rename}{call}->(@_);
2218 sub rcs_recentchanges ($) {
2219 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2222 sub rcs_diff ($;$) {
2223 $hooks{rcs}{rcs_diff}{call}->(@_);
2226 sub rcs_getctime ($) {
2227 $hooks{rcs}{rcs_getctime}{call}->(@_);
2230 sub rcs_getmtime ($) {
2231 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2234 sub rcs_receive () {
2235 $hooks{rcs}{rcs_receive}{call}->();
2238 sub add_depends ($$;$) {
2241 my $deptype=shift || $DEPEND_CONTENT;
2243 # Is the pagespec a simple page name?
2244 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2245 $pagespec !~ /[\s*?()!]/) {
2246 $depends_simple{$page}{lc $pagespec} |= $deptype;
2250 # Add explicit dependencies for influences.
2251 my $sub=pagespec_translate($pagespec);
2252 return unless defined $sub;
2253 foreach my $p (keys %pagesources) {
2254 my $r=$sub->($p, location => $page);
2255 my $i=$r->influences;
2256 my $static=$r->influences_static;
2257 foreach my $k (keys %$i) {
2258 next unless $r || $static || $k eq $page;
2259 $depends_simple{$page}{lc $k} |= $i->{$k};
2264 $depends{$page}{$pagespec} |= $deptype;
2270 foreach my $type (@_) {
2271 if ($type eq 'presence') {
2272 $deptype |= $DEPEND_PRESENCE;
2274 elsif ($type eq 'links') {
2275 $deptype |= $DEPEND_LINKS;
2277 elsif ($type eq 'content') {
2278 $deptype |= $DEPEND_CONTENT;
2284 my $file_prune_regexp;
2285 sub file_pruned ($) {
2288 if (defined $config{include} && length $config{include}) {
2289 return 0 if $file =~ m/$config{include}/;
2292 if (! defined $file_prune_regexp) {
2293 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2294 $file_prune_regexp=qr/$file_prune_regexp/;
2296 return $file =~ m/$file_prune_regexp/;
2299 sub define_gettext () {
2300 # If translation is needed, redefine the gettext function to do it.
2301 # Otherwise, it becomes a quick no-op.
2304 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2305 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2306 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2308 $gettext_obj=eval q{
2309 use Locale::gettext q{textdomain};
2310 Locale::gettext->domain('ikiwiki')
2315 no warnings 'redefine';
2317 $getobj->() if $getobj;
2319 $gettext_obj->get(shift);
2326 $getobj->() if $getobj;
2328 $gettext_obj->nget(@_);
2331 return ($_[2] == 1 ? $_[0] : $_[1])
2349 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2353 # Injects a new function into the symbol table to replace an
2354 # exported function.
2357 # This is deep ugly perl foo, beware.
2360 if (! defined $params{parent}) {
2361 $params{parent}='::';
2362 $params{old}=\&{$params{name}};
2363 $params{name}=~s/.*:://;
2365 my $parent=$params{parent};
2366 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2367 $ns = $params{parent} . $ns;
2368 inject(%params, parent => $ns) unless $ns eq '::main::';
2369 *{$ns . $params{name}} = $params{call}
2370 if exists ${$ns}{$params{name}} &&
2371 \&{${$ns}{$params{name}}} == $params{old};
2377 sub add_link ($$;$) {
2382 push @{$links{$page}}, $link
2383 unless grep { $_ eq $link } @{$links{$page}};
2385 if (defined $type) {
2386 $typedlinks{$page}{$type}{$link} = 1;
2390 sub add_autofile ($$$) {
2393 my $generator=shift;
2395 $autofiles{$file}{plugin}=$plugin;
2396 $autofiles{$file}{generator}=$generator;
2400 return LWP::UserAgent->new(
2401 cookie_jar => $config{cookiejar},
2402 env_proxy => 1, # respect proxy env vars
2403 agent => $config{useragent},
2407 sub sortspec_translate ($$) {
2409 my $reverse = shift;
2415 (-?) # group 1: perhaps negated
2418 \w+\([^\)]*\) # command(params)
2420 [^\s]+ # or anything else
2428 if ($word =~ m/^(\w+)\((.*)\)$/) {
2429 # command with parameters
2433 elsif ($word !~ m/^\w+$/) {
2434 error(sprintf(gettext("invalid sort type %s"), $word));
2445 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2446 if (defined $params) {
2447 push @data, $params;
2448 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2451 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2455 error(sprintf(gettext("unknown sort type %s"), $word));
2459 if (! length $code) {
2460 # undefined sorting method... sort arbitrarily
2469 return eval 'sub { '.$code.' }';
2472 sub pagespec_translate ($) {
2475 # Convert spec to perl code.
2479 \s* # ignore whitespace
2480 ( # 1: match a single word
2487 \w+\([^\)]*\) # command(params)
2489 [^\s()]+ # any other text
2491 \s* # ignore whitespace
2494 if (lc $word eq 'and') {
2497 elsif (lc $word eq 'or') {
2500 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2503 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2504 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2506 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2509 push @data, qq{unknown function in pagespec "$word"};
2510 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2515 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2519 if (! length $code) {
2520 $code="IkiWiki::FailReason->new('empty pagespec')";
2524 return eval 'sub { my $page=shift; '.$code.' }';
2527 sub pagespec_match ($$;@) {
2532 # Backwards compatability with old calling convention.
2534 unshift @params, 'location';
2537 my $sub=pagespec_translate($spec);
2538 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2540 return $sub->($page, @params);
2543 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2545 # Not exported yet, but could be in future if it is generally useful.
2546 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2547 # which is "more internal".
2548 sub sort_pages ($$;@) {
2552 $sort = sortspec_translate($sort, $params{reverse});
2553 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2556 sub pagespec_match_list ($$;@) {
2561 # Backwards compatability with old calling convention.
2563 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2564 $params{list}=$page;
2565 $page=$params{location}; # ugh!
2568 my $sub=pagespec_translate($pagespec);
2569 error "syntax error in pagespec \"$pagespec\""
2571 my $sort=sortspec_translate($params{sort}, $params{reverse})
2572 if defined $params{sort};
2575 if (exists $params{list}) {
2576 @candidates=exists $params{filter}
2577 ? grep { ! $params{filter}->($_) } @{$params{list}}
2581 @candidates=exists $params{filter}
2582 ? grep { ! $params{filter}->($_) } keys %pagesources
2583 : keys %pagesources;
2586 # clear params, remainder is passed to pagespec
2587 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2588 my $num=$params{num};
2589 delete @params{qw{num deptype reverse sort filter list}};
2591 # when only the top matches will be returned, it's efficient to
2592 # sort before matching to pagespec,
2593 if (defined $num && defined $sort) {
2594 @candidates=IkiWiki::SortSpec::sort_pages(
2595 $sort, @candidates);
2601 my $accum=IkiWiki::SuccessReason->new();
2602 foreach my $p (@candidates) {
2603 my $r=$sub->($p, %params, location => $page);
2604 error(sprintf(gettext("cannot match pages: %s"), $r))
2605 if $r->isa("IkiWiki::ErrorReason");
2606 unless ($r || $r->influences_static) {
2607 $r->remove_influence($p);
2612 last if defined $num && ++$count == $num;
2616 # Add simple dependencies for accumulated influences.
2617 my $i=$accum->influences;
2618 foreach my $k (keys %$i) {
2619 $depends_simple{$page}{lc $k} |= $i->{$k};
2622 # when all matches will be returned, it's efficient to
2623 # sort after matching
2624 if (! defined $num && defined $sort) {
2625 return IkiWiki::SortSpec::sort_pages(
2633 sub pagespec_valid ($) {
2636 return defined pagespec_translate($spec);
2640 my $re=quotemeta(shift);
2646 package IkiWiki::FailReason;
2649 '""' => sub { $_[0][0] },
2651 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2652 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2653 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2657 our @ISA = 'IkiWiki::SuccessReason';
2659 package IkiWiki::SuccessReason;
2661 # A blessed array-ref:
2663 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2665 # - if absent or false, the influences of this evaluation are "static",
2666 # see the influences_static method
2667 # - if true, they are dynamic (not static)
2668 # [1]{any other key}:
2669 # the dependency types of influences, as returned by the influences method
2672 # in string context, it's the human-readable reason
2673 '""' => sub { $_[0][0] },
2674 # in boolean context, SuccessReason is 1 and FailReason is 0
2676 # negating a result gives the opposite result with the same influences
2677 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2678 # A & B = (A ? B : A) with the influences of both
2679 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2680 # A | B = (A ? A : B) with the influences of both
2681 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2685 # SuccessReason->new("human-readable reason", page => deptype, ...)
2690 return bless [$value, {@_}], $class;
2693 # influences(): return a reference to a copy of the hash
2694 # { page => dependency type } describing the pages that indirectly influenced
2695 # this result, but would not cause a dependency through ikiwiki's core
2698 # See [[todo/dependency_types]] for extensive discussion of what this means.
2700 # influences(page => deptype, ...): remove all influences, replace them
2701 # with the arguments, and return a reference to a copy of the new influences.
2705 $this->[1]={@_} if @_;
2706 my %i=%{$this->[1]};
2711 # True if this result has the same influences whichever page it matches,
2712 # For instance, whether bar matches backlink(foo) is influenced only by
2713 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2714 # which does not mention bar anywhere.
2716 # False if this result would have different influences when matching
2717 # different pages. For instance, when testing whether link(foo) matches bar,
2718 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2719 # bar's links could change the outcome; so its influences are not the same
2720 # as when testing whether link(foo) matches baz.
2722 # Static influences are one of the things that make pagespec_match_list
2723 # more efficient than repeated calls to pagespec_match.
2725 sub influences_static {
2726 return ! $_[0][1]->{""};
2729 # Change the influences of $this to be the influences of "$this & $other"
2730 # or "$this | $other".
2732 # If both $this and $other are either successful or have influences,
2733 # or this is an "or" operation, the result has all the influences from
2734 # either of the arguments. It has dynamic influences if either argument
2735 # has dynamic influences.
2737 # If this is an "and" operation, and at least one argument is a
2738 # FailReason with no influences, the result has no influences, and they
2739 # are not dynamic. For instance, link(foo) matching bar is influenced
2740 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2741 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2742 # bar, because it would be false however often you edit bar.
2744 sub merge_influences {
2749 # This "if" is odd because it needs to avoid negating $this
2750 # or $other, which would alter the objects in-place. Be careful.
2751 if (! $anded || (($this || %{$this->[1]}) &&
2752 ($other || %{$other->[1]}))) {
2753 foreach my $influence (keys %{$other->[1]}) {
2754 $this->[1]{$influence} |= $other->[1]{$influence};
2763 # Change $this so it is not considered to be influenced by $torm.
2765 sub remove_influence {
2769 delete $this->[1]{$torm};
2772 package IkiWiki::ErrorReason;
2774 our @ISA = 'IkiWiki::FailReason';
2776 package IkiWiki::PageSpec;
2782 if ($path =~ m!^\.(/|$)!) {
2784 $from=~s#/?[^/]+$## if defined $from;
2786 $path="$from/$path" if defined $from && length $from;
2790 $path = "" unless defined $path;
2799 sub match_glob ($$;@) {
2804 $glob=derel($glob, $params{location});
2806 # Instead of converting the glob to a regex every time,
2807 # cache the compiled regex to save time.
2808 my $re=$glob_cache{$glob};
2809 unless (defined $re) {
2810 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2813 if (! IkiWiki::isinternal($page) || $params{internal}) {
2814 return IkiWiki::SuccessReason->new("$glob matches $page");
2817 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2821 return IkiWiki::FailReason->new("$glob does not match $page");
2825 sub match_internal ($$;@) {
2826 return match_glob(shift, shift, @_, internal => 1)
2829 sub match_page ($$;@) {
2831 my $match=match_glob($page, shift, @_);
2833 my $source=exists $IkiWiki::pagesources{$page} ?
2834 $IkiWiki::pagesources{$page} :
2835 $IkiWiki::delpagesources{$page};
2836 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2837 if (! defined $type) {
2838 return IkiWiki::FailReason->new("$page is not a page");
2844 sub match_link ($$;@) {
2849 $link=derel($link, $params{location});
2850 my $from=exists $params{location} ? $params{location} : '';
2851 my $linktype=$params{linktype};
2853 if (defined $linktype) {
2854 $qualifier=" with type $linktype";
2857 my $links = $IkiWiki::links{$page};
2858 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2859 unless $links && @{$links};
2860 my $bestlink = IkiWiki::bestlink($from, $link);
2861 foreach my $p (@{$links}) {
2862 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2864 if (length $bestlink) {
2865 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2866 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2870 if (match_glob($p, $link, %params)) {
2871 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2873 my ($p_rel)=$p=~/^\/?(.*)/;
2875 if (match_glob($p_rel, $link, %params)) {
2876 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2880 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2883 sub match_backlink ($$;@) {
2887 if ($testpage eq '.') {
2888 $testpage = $params{'location'}
2890 my $ret=match_link($testpage, $page, @_);
2891 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2895 sub match_created_before ($$;@) {
2900 $testpage=derel($testpage, $params{location});
2902 if (exists $IkiWiki::pagectime{$testpage}) {
2903 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2904 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2907 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2911 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2915 sub match_created_after ($$;@) {
2920 $testpage=derel($testpage, $params{location});
2922 if (exists $IkiWiki::pagectime{$testpage}) {
2923 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2924 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2927 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2931 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2935 sub match_creation_day ($$;@) {
2938 if ($d !~ /^\d+$/) {
2939 return IkiWiki::ErrorReason->new("invalid day $d");
2941 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2942 return IkiWiki::SuccessReason->new('creation_day matched');
2945 return IkiWiki::FailReason->new('creation_day did not match');
2949 sub match_creation_month ($$;@) {
2952 if ($m !~ /^\d+$/) {
2953 return IkiWiki::ErrorReason->new("invalid month $m");
2955 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2956 return IkiWiki::SuccessReason->new('creation_month matched');
2959 return IkiWiki::FailReason->new('creation_month did not match');
2963 sub match_creation_year ($$;@) {
2966 if ($y !~ /^\d+$/) {
2967 return IkiWiki::ErrorReason->new("invalid year $y");
2969 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2970 return IkiWiki::SuccessReason->new('creation_year matched');
2973 return IkiWiki::FailReason->new('creation_year did not match');
2977 sub match_user ($$;@) {
2982 if (! exists $params{user}) {
2983 return IkiWiki::ErrorReason->new("no user specified");
2986 my $regexp=IkiWiki::glob2re($user);
2988 if (defined $params{user} && $params{user}=~$regexp) {
2989 return IkiWiki::SuccessReason->new("user is $user");
2991 elsif (! defined $params{user}) {
2992 return IkiWiki::FailReason->new("not logged in");
2995 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2999 sub match_admin ($$;@) {
3004 if (! exists $params{user}) {
3005 return IkiWiki::ErrorReason->new("no user specified");
3008 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3009 return IkiWiki::SuccessReason->new("user is an admin");
3011 elsif (! defined $params{user}) {
3012 return IkiWiki::FailReason->new("not logged in");
3015 return IkiWiki::FailReason->new("user is not an admin");
3019 sub match_ip ($$;@) {
3024 if (! exists $params{ip}) {
3025 return IkiWiki::ErrorReason->new("no IP specified");
3028 my $regexp=IkiWiki::glob2re(lc $ip);
3030 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3031 return IkiWiki::SuccessReason->new("IP is $ip");
3034 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3038 package IkiWiki::SortSpec;
3040 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3041 # are easily available in this namespace, for cmp functions to use them.
3048 IkiWiki::pagetitle(IkiWiki::basename($a))
3050 IkiWiki::pagetitle(IkiWiki::basename($b))
3053 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3054 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3055 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }