8 use URI::Escape q{uri_escape_utf8};
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14 %pagestate %wikistate %renderedfiles %oldrenderedfiles
15 %pagesources %delpagesources %destsources %depends %depends_simple
16 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17 %oldtypedlinks %autofiles @underlayfiles $lastrev $phase};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21 deptype add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime strftime_utf8 will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link add_autofile useragent
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
37 # Phases of processing.
38 sub PHASE_SCAN () { 0 }
39 sub PHASE_RENDER () { 1 }
45 memoize("sortspec_translate");
46 memoize("pagespec_translate");
47 memoize("template_file");
53 description => "name of the wiki",
60 example => 'me@example.com',
61 description => "contact email for wiki",
68 description => "users who are wiki admins",
75 description => "users who are banned from the wiki",
82 example => "$ENV{HOME}/wiki",
83 description => "where the source of the wiki is located",
90 example => "/var/www/wiki",
91 description => "where to build the wiki",
98 example => "http://example.com/wiki",
99 description => "base url to the wiki",
106 example => "http://example.com/wiki/ikiwiki.cgi",
107 description => "url to the ikiwiki.cgi",
114 description => "do not adjust cgiurl if CGI is accessed via different URL",
117 rebuild => 0, # only affects CGI requests
122 example => "/var/www/wiki/ikiwiki.cgi",
123 description => "filename of cgi wrapper to generate",
130 description => "mode for cgi_wrapper (can safely be made suid)",
134 cgi_overload_delay => {
138 description => "number of seconds to delay CGI requests when overloaded",
142 cgi_overload_message => {
145 example => "Please wait",
146 description => "message to display when overloaded (may contain html)",
150 only_committed_changes => {
153 description => "enable optimization of only refreshing committed changes?",
160 description => "rcs backend to use",
161 safe => 0, # don't allow overriding
166 default => [qw{mdwn link inline meta htmlscrubber passwordauth
167 openid signinedit lockedit conditional
168 recentchanges parentlinks editpage
170 description => "plugins to enable by default",
177 description => "plugins to add to the default configuration",
184 description => "plugins to disable",
190 default => "$installdir/share/ikiwiki/templates",
191 description => "additional directory to search for template files",
198 default => "$installdir/share/ikiwiki/basewiki",
199 description => "base wiki source location",
206 default => "$installdir/share/ikiwiki",
207 description => "parent directory containing additional underlays",
214 description => "wrappers to generate",
221 description => "additional underlays to use",
228 description => "display verbose messages?",
235 description => "log to syslog?",
242 description => "create output files named page/index.html?",
243 safe => 0, # changing requires manual transition
246 prefix_directives => {
249 description => "use '!'-prefixed preprocessor directives?",
250 safe => 0, # changing requires manual transition
256 description => "use page/index.mdwn source files",
263 description => "enable Discussion pages?",
269 default => gettext("Discussion"),
270 description => "name of Discussion pages",
277 description => "use elements new in HTML5 like <section>?",
285 description => "only send cookies over SSL connections?",
293 description => "extension to use for new pages",
294 safe => 0, # not sanitized
300 description => "extension to use for html files",
301 safe => 0, # not sanitized
307 description => "strftime format string to display date",
315 example => "en_US.UTF-8",
316 description => "UTF-8 locale to use",
325 description => "put user pages below specified page",
332 description => "how many backlinks to show before hiding excess (0 to show all)",
339 description => "attempt to hardlink source files? (optimisation for large files)",
341 safe => 0, # paranoia
347 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
349 safe => 0, # paranoia
354 example => "ikiwiki",
355 description => "group for wrappers to run in",
357 safe => 0, # paranoia
363 example => "$ENV{HOME}/.ikiwiki/",
364 description => "extra library and plugin directory",
366 safe => 0, # directory
372 description => "environment variables",
373 safe => 0, # paranoia
379 example => "US/Eastern",
380 description => "time zone name",
387 example => '^\.htaccess$',
388 description => "regexp of normally excluded files to include",
396 example => '^(*\.private|Makefile)$',
397 description => "regexp of files that should be skipped",
402 wiki_file_prune_regexps => {
404 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
405 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
406 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
407 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
408 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
409 description => "regexps of source files to ignore",
415 description => "specifies the characters that are allowed in source filenames",
416 default => "-[:alnum:]+/.:_",
420 wiki_file_regexp => {
422 description => "regexp of legal source files",
426 web_commit_regexp => {
428 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
429 description => "regexp to parse web commits from logs",
436 description => "run as a cgi",
440 cgi_disable_uploads => {
443 description => "whether CGI should accept file uploads",
450 description => "run as a post-commit hook",
457 description => "running in rebuild mode",
464 description => "running in setup mode",
471 description => "running in clean mode",
478 description => "running in refresh mode",
485 description => "running in receive test mode",
489 wrapper_background_command => {
492 description => "background shell command to run",
498 description => "running in gettime mode",
505 description => "running in w3mmode",
512 description => "path to the .ikiwiki directory holding ikiwiki state",
519 description => "path to setup file",
526 description => "perl class to use to dump setup file",
530 allow_symlinks_before_srcdir => {
533 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
539 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
540 description => "cookie control",
541 safe => 0, # hooks into perl module internals
546 default => "ikiwiki/$version",
547 example => "Wget/1.13.4 (linux-gnu)",
548 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
552 responsive_layout => {
555 description => "theme has a responsive layout? (mobile-optimized)",
561 sub defaultconfig () {
564 foreach my $key (keys %s) {
565 push @ret, $key, $s{$key}->{default};
570 # URL to top of wiki as a path starting with /, valid from any wiki page or
571 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
573 # URL to CGI script, similar to $local_url
577 # locale stuff; avoid LC_ALL since it overrides everything
578 if (defined $ENV{LC_ALL}) {
579 $ENV{LANG} = $ENV{LC_ALL};
582 if (defined $config{locale}) {
583 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
584 $ENV{LANG}=$config{locale};
589 if (! defined $config{wiki_file_regexp}) {
590 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
593 if (ref $config{ENV} eq 'HASH') {
594 foreach my $val (keys %{$config{ENV}}) {
595 $ENV{$val}=$config{ENV}{$val};
598 if (defined $config{timezone} && length $config{timezone}) {
599 $ENV{TZ}=$config{timezone};
602 $config{timezone}=$ENV{TZ};
605 if ($config{w3mmode}) {
606 eval q{use Cwd q{abs_path}};
608 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
609 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
610 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
611 unless $config{cgiurl} =~ m!file:///!;
612 $config{url}="file://".$config{destdir};
615 if ($config{cgi} && ! length $config{url}) {
616 error(gettext("Must specify url to wiki with --url when using --cgi"));
619 if (defined $config{url} && length $config{url}) {
621 my $baseurl = URI->new($config{url});
623 $local_url = $baseurl->path . "/";
624 $local_cgiurl = undef;
626 if (length $config{cgiurl}) {
627 my $cgiurl = URI->new($config{cgiurl});
629 $local_cgiurl = $cgiurl->path;
631 if ($cgiurl->scheme eq 'https' &&
632 $baseurl->scheme eq 'http') {
633 # We assume that the same content is available
634 # over both http and https, because if it
635 # wasn't, accessing the static content
636 # from the CGI would be mixed-content,
637 # which would be a security flaw.
639 if ($cgiurl->authority ne $baseurl->authority) {
640 # use protocol-relative URL for
642 $local_url = "$config{url}/";
643 $local_url =~ s{^http://}{//};
645 # else use host-relative URL for static content
647 # either way, CGI needs to be absolute
648 $local_cgiurl = $config{cgiurl};
650 elsif ($cgiurl->scheme ne $baseurl->scheme) {
651 # too far apart, fall back to absolute URLs
652 $local_url = "$config{url}/";
653 $local_cgiurl = $config{cgiurl};
655 elsif ($cgiurl->authority ne $baseurl->authority) {
656 # slightly too far apart, fall back to
657 # protocol-relative URLs
658 $local_url = "$config{url}/";
659 $local_url =~ s{^https?://}{//};
660 $local_cgiurl = $config{cgiurl};
661 $local_cgiurl =~ s{^https?://}{//};
663 # else keep host-relative URLs
666 $local_url =~ s{//$}{/};
669 $local_cgiurl = $config{cgiurl};
672 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
673 unless exists $config{wikistatedir} && defined $config{wikistatedir};
675 if (defined $config{umask}) {
676 my $u = possibly_foolish_untaint($config{umask});
678 if ($u =~ m/^\d+$/) {
681 elsif ($u eq 'private') {
684 elsif ($u eq 'group') {
687 elsif ($u eq 'public') {
691 error(sprintf(gettext("unsupported umask setting %s"), $u));
695 run_hooks(checkconfig => sub { shift->() });
703 foreach my $dir (@INC, $config{libdir}) {
704 next unless defined $dir && length $dir;
705 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
706 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
710 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
711 next unless defined $dir && length $dir;
712 foreach my $file (glob("$dir/plugins/*")) {
713 $ret{basename($file)}=1 if -x $file;
721 if (defined $config{libdir} && length $config{libdir}) {
722 unshift @INC, possibly_foolish_untaint($config{libdir});
725 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
730 if (exists $hooks{rcs}) {
731 error(gettext("cannot use multiple rcs plugins"));
733 loadplugin($config{rcs});
735 if (! exists $hooks{rcs}) {
739 run_hooks(getopt => sub { shift->() });
740 if (grep /^-/, @ARGV) {
741 print STDERR "Unknown option (or missing parameter): $_\n"
742 foreach grep /^-/, @ARGV;
749 sub loadplugin ($;$) {
753 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
755 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
756 "$installdir/lib/ikiwiki") {
757 if (defined $dir && -x "$dir/plugins/$plugin") {
758 eval { require IkiWiki::Plugin::external };
761 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
763 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
764 $loaded_plugins{$plugin}=1;
769 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
772 error("Failed to load plugin $mod: $@");
774 $loaded_plugins{$plugin}=1;
781 log_message('err' => $message) if $config{syslog};
782 if (defined $cleaner) {
789 return unless $config{verbose};
790 return log_message(debug => @_);
795 sub log_message ($$) {
798 if ($config{syslog}) {
801 Sys::Syslog::setlogsock('unix');
802 Sys::Syslog::openlog('ikiwiki', '', 'user');
806 # keep a copy to avoid editing the original config repeatedly
807 my $wikiname = $config{wikiname};
808 utf8::encode($wikiname);
809 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
812 print STDERR "failed to syslog: $@" unless $log_failed;
818 elsif (! $config{cgi}) {
822 return print STDERR "@_\n";
826 sub possibly_foolish_untaint ($) {
828 my ($untainted)=$tainted=~/(.*)/s;
848 return exists $pagesources{$page} &&
849 $pagesources{$page} =~ /\._([^.]+)$/;
855 if ($file =~ /\.([^.]+)$/) {
856 return $1 if exists $hooks{htmlize}{$1};
858 my $base=basename($file);
859 if (exists $hooks{htmlize}{$base} &&
860 $hooks{htmlize}{$base}{noextension}) {
871 if (exists $pagename_cache{$file}) {
872 return $pagename_cache{$file};
875 my $type=pagetype($file);
877 $page=~s/\Q.$type\E*$//
878 if defined $type && !$hooks{htmlize}{$type}{keepextension}
879 && !$hooks{htmlize}{$type}{noextension};
880 if ($config{indexpages} && $page=~/(.*)\/index$/) {
884 $pagename_cache{$file} = $page;
888 sub newpagefile ($$) {
892 if (! $config{indexpages} || $page eq 'index') {
893 return $page.".".$type;
896 return $page."/index.".$type;
900 sub targetpage ($$;$) {
905 if (defined $filename) {
906 return $page."/".$filename.".".$ext;
908 elsif (! $config{usedirs} || $page eq 'index') {
909 return $page.".".$ext;
912 return $page."/index.".$ext;
919 return targetpage($page, $config{htmlext});
926 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
927 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
928 return "$dir/$file", stat(_) if -e "$dir/$file";
930 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
935 return (srcfile_stat(@_))[0];
938 sub add_literal_underlay ($) {
941 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
942 unshift @{$config{underlaydirs}}, $dir;
946 sub add_underlay ($) {
950 $dir="$config{underlaydirbase}/$dir";
953 add_literal_underlay($dir);
954 # why does it return 1? we just don't know
958 sub readfile ($;$$) {
964 error("cannot read a symlink ($file)");
968 open (my $in, "<", $file) || error("failed to read $file: $!");
969 binmode($in) if ($binary);
970 return \*$in if $wantfd;
972 # check for invalid utf-8, and toss it back to avoid crashes
973 if (! utf8::valid($ret)) {
974 $ret=encode_utf8($ret);
976 close $in || error("failed to read $file: $!");
980 sub prep_writefile ($$) {
985 while (length $test) {
986 if (-l "$destdir/$test") {
987 error("cannot write to a symlink ($test)");
989 if (-f _ && $test ne $file) {
990 # Remove conflicting file.
991 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
992 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
994 unlink("$destdir/$test");
1000 $test=dirname($test);
1003 my $dir=dirname("$destdir/$file");
1006 foreach my $s (split(m!/+!, $dir)) {
1009 mkdir($d) || error("failed to create directory $d: $!");
1017 sub writefile ($$$;$$) {
1018 my $file=shift; # can include subdirs
1019 my $destdir=shift; # directory to put file in
1024 prep_writefile($file, $destdir);
1026 my $newfile="$destdir/$file.ikiwiki-new";
1028 error("cannot write to a symlink ($newfile)");
1031 my $cleanup = sub { unlink($newfile) };
1032 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1033 binmode($out) if ($binary);
1035 $writer->(\*$out, $cleanup);
1038 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1040 close $out || error("failed saving $newfile: $!", $cleanup);
1041 rename($newfile, "$destdir/$file") ||
1042 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1048 sub will_render ($$;$) {
1053 # Important security check for independently created files.
1054 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1055 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1056 my $from_other_page=0;
1057 # Expensive, but rarely runs.
1058 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1061 dirname($_) eq $dest
1062 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1068 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1069 unless $from_other_page;
1072 # If $dest exists as a directory, remove conflicting files in it
1073 # rendered from other pages.
1075 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1076 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1077 if (dirname($f) eq $dest) {
1078 unlink("$config{destdir}/$f");
1079 rmdir(dirname("$config{destdir}/$f"));
1085 if (! $clear || $cleared{$page}) {
1086 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1089 foreach my $old (@{$renderedfiles{$page}}) {
1090 delete $destsources{$old};
1092 $renderedfiles{$page}=[$dest];
1095 $destsources{$dest}=$page;
1105 if ($link=~s/^\/+//) {
1113 $l.="/" if length $l;
1116 if (exists $pagesources{$l}) {
1119 elsif (exists $pagecase{lc $l}) {
1120 return $pagecase{lc $l};
1122 } while $cwd=~s{/?[^/]+$}{};
1124 if (length $config{userdir}) {
1125 my $l = "$config{userdir}/".lc($link);
1126 if (exists $pagesources{$l}) {
1129 elsif (exists $pagecase{lc $l}) {
1130 return $pagecase{lc $l};
1134 #print STDERR "warning: page $page, broken link: $link\n";
1138 sub isinlinableimage ($) {
1141 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1144 sub pagetitle ($;$) {
1146 my $unescaped=shift;
1149 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1152 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1160 # support use w/o %config set
1161 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1162 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1168 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1169 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1176 my $cgiurl=$local_cgiurl;
1178 if (exists $params{cgiurl}) {
1179 $cgiurl=$params{cgiurl};
1180 delete $params{cgiurl};
1188 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1191 sub cgiurl_abs (@) {
1193 URI->new_abs(cgiurl(@_), $config{cgiurl});
1199 return $local_url if ! defined $page;
1201 $page=htmlpage($page);
1203 $page=~s/[^\/]+\//..\//g;
1211 return $url unless defined $urlbase && length $urlbase;
1214 URI->new_abs($url, $urlbase)->as_string;
1218 # Work around very innefficient behavior in File::Spec if abs2rel
1219 # is passed two relative paths. It's much faster if paths are
1220 # absolute! (Debian bug #376658; fixed in debian unstable now)
1225 my $ret=File::Spec->abs2rel($path, $base);
1226 $ret=~s/^// if defined $ret;
1230 sub displaytime ($;$$) {
1231 # Plugins can override this function to mark up the time to
1233 my $time=formattime($_[0], $_[1]);
1234 if ($config{html5}) {
1235 return '<time datetime="'.date_3339($_[0]).'"'.
1236 ($_[2] ? ' pubdate="pubdate"' : '').
1237 '>'.$time.'</time>';
1240 return '<span class="date">'.$time.'</span>';
1244 sub formattime ($;$) {
1245 # Plugins can override this function to format the time.
1248 if (! defined $format) {
1249 $format=$config{timeformat};
1252 return strftime_utf8($format, localtime($time));
1255 my $strftime_encoding;
1257 # strftime doesn't know about encodings, so make sure
1258 # its output is properly treated as utf8.
1259 # Note that this does not handle utf-8 in the format string.
1260 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1261 unless defined $strftime_encoding;
1263 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1264 : POSIX::strftime(@_);
1270 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1271 POSIX::setlocale(&POSIX::LC_TIME, "C");
1272 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1273 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1277 sub beautify_urlpath ($) {
1280 # Ensure url is not an empty link, and if necessary,
1281 # add ./ to avoid colon confusion.
1282 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1286 if ($config{usedirs}) {
1287 $url =~ s!/index.$config{htmlext}$!/!;
1302 if (! $destsources{$to}) {
1307 return $config{url}.beautify_urlpath("/".$to);
1310 if (! defined $from) {
1311 my $u = $local_url || '';
1313 return $u.beautify_urlpath("/".$to);
1316 my $link = abs2rel($to, dirname(htmlpage($from)));
1318 return beautify_urlpath($link);
1321 sub isselflink ($$) {
1322 # Plugins can override this function to support special types
1327 return $page eq $link;
1330 sub htmllink ($$$;@) {
1331 my $lpage=shift; # the page doing the linking
1332 my $page=shift; # the page that will contain the link (different for inline)
1339 if (! $opts{forcesubpage}) {
1340 $bestlink=bestlink($lpage, $link);
1343 $bestlink="$lpage/".lc($link);
1347 if (defined $opts{linktext}) {
1348 $linktext=$opts{linktext};
1351 $linktext=pagetitle(basename($link));
1354 return "<span class=\"selflink\">$linktext</span>"
1355 if length $bestlink && isselflink($page, $bestlink) &&
1356 ! defined $opts{anchor};
1358 if (! $destsources{$bestlink}) {
1359 $bestlink=htmlpage($bestlink);
1361 if (! $destsources{$bestlink}) {
1363 if (length $config{cgiurl}) {
1364 $cgilink = "<a href=\"".
1369 )."\" rel=\"nofollow\">?</a>";
1371 return "<span class=\"createlink\">$cgilink$linktext</span>"
1375 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1376 $bestlink=beautify_urlpath($bestlink);
1378 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1379 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1382 if (defined $opts{anchor}) {
1383 $bestlink.="#".$opts{anchor};
1387 foreach my $attr (qw{rel class title}) {
1388 if (defined $opts{$attr}) {
1389 push @attrs, " $attr=\"$opts{$attr}\"";
1393 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1398 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1401 sub openiduser ($) {
1404 if (defined $user && $user =~ m!^https?://! &&
1405 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1408 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1409 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1412 # backcompat with old version
1413 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1414 $display=$oid->display;
1417 # Convert "user.somehost.com" to "user [somehost.com]"
1418 # (also "user.somehost.co.uk")
1419 if ($display !~ /\[/) {
1420 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1422 # Convert "http://somehost.com/user" to "user [somehost.com]".
1423 # (also "https://somehost.com/user/")
1424 if ($display !~ /\[/) {
1425 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1427 $display=~s!^https?://!!; # make sure this is removed
1428 eval q{use CGI 'escapeHTML'};
1430 return escapeHTML($display);
1435 sub htmlize ($$$$) {
1441 my $oneline = $content !~ /\n/;
1443 if (exists $hooks{htmlize}{$type}) {
1444 $content=$hooks{htmlize}{$type}{call}->(
1446 content => $content,
1450 error("htmlization of $type not supported");
1453 run_hooks(sanitize => sub {
1456 destpage => $destpage,
1457 content => $content,
1462 # hack to get rid of enclosing junk added by markdown
1463 # and other htmlizers/sanitizers
1464 $content=~s/^<p>//i;
1465 $content=~s/<\/p>\n*$//i;
1476 run_hooks(linkify => sub {
1479 destpage => $destpage,
1480 content => $content,
1488 our $preprocess_preview=0;
1489 sub preprocess ($$$;$$) {
1490 my $page=shift; # the page the data comes from
1491 my $destpage=shift; # the page the data will appear in (different for inline)
1496 # Using local because it needs to be set within any nested calls
1498 local $preprocess_preview=$preview if defined $preview;
1505 $params="" if ! defined $params;
1507 if (length $escape) {
1508 return "[[$prefix$command $params]]";
1510 elsif (exists $hooks{preprocess}{$command}) {
1511 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1512 # Note: preserve order of params, some plugins may
1513 # consider it significant.
1515 while ($params =~ m{
1516 (?:([-.\w]+)=)? # 1: named parameter key?
1518 """(.*?)""" # 2: triple-quoted value
1520 "([^"]*?)" # 3: single-quoted value
1522 '''(.*?)''' # 4: triple-single-quote
1524 <<([a-zA-Z]+)\n # 5: heredoc start
1525 (.*?)\n\5 # 6: heredoc value
1527 (\S+) # 7: unquoted value
1529 (?:\s+|$) # delimiter to next param
1539 elsif (defined $3) {
1542 elsif (defined $4) {
1545 elsif (defined $7) {
1548 elsif (defined $6) {
1553 push @params, $key, $val;
1556 push @params, $val, '';
1559 if ($preprocessing{$page}++ > 8) {
1560 # Avoid loops of preprocessed pages preprocessing
1561 # other pages that preprocess them, etc.
1562 return "[[!$command <span class=\"error\">".
1563 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1564 $page, $preprocessing{$page}).
1570 $hooks{preprocess}{$command}{call}->(
1573 destpage => $destpage,
1574 preview => $preprocess_preview,
1580 $ret="[[!$command <span class=\"error\">".
1581 gettext("Error").": $error"."</span>]]";
1585 # use void context during scan pass
1587 $hooks{preprocess}{$command}{call}->(
1590 destpage => $destpage,
1591 preview => $preprocess_preview,
1596 $preprocessing{$page}--;
1600 return "[[$prefix$command $params]]";
1605 if ($config{prefix_directives}) {
1608 \[\[(!) # directive open; 2: prefix
1609 ([-\w]+) # 3: command
1610 ( # 4: the parameters..
1611 \s+ # Must have space if parameters present
1613 (?:[-.\w]+=)? # named parameter key?
1615 """.*?""" # triple-quoted value
1617 "[^"]*?" # single-quoted value
1619 '''.*?''' # triple-single-quote
1621 <<([a-zA-Z]+)\n # 5: heredoc start
1622 (?:.*?)\n\5 # heredoc value
1624 [^"\s\]]+ # unquoted value
1626 \s* # whitespace or end
1629 *)? # 0 or more parameters
1630 \]\] # directive closed
1636 \[\[(!?) # directive open; 2: optional prefix
1637 ([-\w]+) # 3: command
1639 ( # 4: the parameters..
1641 (?:[-.\w]+=)? # named parameter key?
1643 """.*?""" # triple-quoted value
1645 "[^"]*?" # single-quoted value
1647 '''.*?''' # triple-single-quote
1649 <<([a-zA-Z]+)\n # 5: heredoc start
1650 (?:.*?)\n\5 # heredoc value
1652 [^"\s\]]+ # unquoted value
1654 \s* # whitespace or end
1657 *) # 0 or more parameters
1658 \]\] # directive closed
1662 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1671 run_hooks(filter => sub {
1672 $content=shift->(page => $page, destpage => $destpage,
1673 content => $content);
1679 sub check_canedit ($$$;$) {
1686 run_hooks(canedit => sub {
1687 return if defined $canedit;
1688 my $ret=shift->($page, $q, $session);
1693 elsif (ref $ret eq 'CODE') {
1694 $ret->() unless $nonfatal;
1697 elsif (defined $ret) {
1698 error($ret) unless $nonfatal;
1703 return defined $canedit ? $canedit : 1;
1706 sub check_content (@) {
1709 return 1 if ! exists $hooks{checkcontent}; # optimisation
1711 if (exists $pagesources{$params{page}}) {
1713 my %old=map { $_ => 1 }
1714 split("\n", readfile(srcfile($pagesources{$params{page}})));
1715 foreach my $line (split("\n", $params{content})) {
1716 push @diff, $line if ! exists $old{$line};
1718 $params{diff}=join("\n", @diff);
1722 run_hooks(checkcontent => sub {
1723 return if defined $ok;
1724 my $ret=shift->(%params);
1729 elsif (ref $ret eq 'CODE') {
1730 $ret->() unless $params{nonfatal};
1733 elsif (defined $ret) {
1734 error($ret) unless $params{nonfatal};
1740 return defined $ok ? $ok : 1;
1743 sub check_canchange (@) {
1745 my $cgi = $params{cgi};
1746 my $session = $params{session};
1747 my @changes = @{$params{changes}};
1750 foreach my $change (@changes) {
1751 # This untaint is safe because we check file_pruned and
1753 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1754 $file=possibly_foolish_untaint($file);
1755 if (! defined $file || ! length $file ||
1756 file_pruned($file)) {
1757 error(gettext("bad file name %s"), $file);
1760 my $type=pagetype($file);
1761 my $page=pagename($file) if defined $type;
1763 if ($change->{action} eq 'add') {
1767 if ($change->{action} eq 'change' ||
1768 $change->{action} eq 'add') {
1769 if (defined $page) {
1770 check_canedit($page, $cgi, $session);
1774 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1775 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1776 check_canedit($file, $cgi, $session);
1781 elsif ($change->{action} eq 'remove') {
1782 # check_canremove tests to see if the file is present
1783 # on disk. This will fail when a single commit adds a
1784 # file and then removes it again. Avoid the problem
1785 # by not testing the removal in such pairs of changes.
1786 # (The add is still tested, just to make sure that
1787 # no data is added to the repo that a web edit
1789 next if $newfiles{$file};
1791 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1792 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1793 check_canedit(defined $page ? $page : $file, $cgi, $session);
1798 error "unknown action ".$change->{action};
1801 error sprintf(gettext("you are not allowed to change %s"), $file);
1809 # Take an exclusive lock on the wiki to prevent multiple concurrent
1810 # run issues. The lock will be dropped on program exit.
1811 if (! -d $config{wikistatedir}) {
1812 mkdir($config{wikistatedir});
1814 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1815 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1816 if (! flock($wikilock, 2)) { # LOCK_EX
1817 error("failed to get lock");
1823 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1824 return close($wikilock) if $wikilock;
1830 sub commit_hook_enabled () {
1831 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1832 error("cannot write to $config{wikistatedir}/commitlock: $!");
1833 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1834 close($commitlock) || error("failed closing commitlock: $!");
1837 close($commitlock) || error("failed closing commitlock: $!");
1841 sub disable_commit_hook () {
1842 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1843 error("cannot write to $config{wikistatedir}/commitlock: $!");
1844 if (! flock($commitlock, 2)) { # LOCK_EX
1845 error("failed to get commit lock");
1850 sub enable_commit_hook () {
1851 return close($commitlock) if $commitlock;
1856 %oldrenderedfiles=%pagectime=();
1857 my $rebuild=$config{rebuild};
1859 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1860 %destsources=%renderedfiles=%pagecase=%pagestate=
1861 %depends_simple=%typedlinks=%oldtypedlinks=();
1864 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1865 if (-e "$config{wikistatedir}/index") {
1866 system("ikiwiki-transition", "indexdb", $config{srcdir});
1867 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1870 # gettime on first build
1871 $config{gettime}=1 unless defined $config{gettime};
1876 my $index=Storable::fd_retrieve($in);
1877 if (! defined $index) {
1882 if (exists $index->{version} && ! ref $index->{version}) {
1883 $pages=$index->{page};
1884 %wikistate=%{$index->{state}};
1885 # Handle plugins that got disabled by loading a new setup.
1886 if (exists $config{setupfile}) {
1887 require IkiWiki::Setup;
1888 IkiWiki::Setup::disabled_plugins(
1889 grep { ! $loaded_plugins{$_} } keys %wikistate);
1897 foreach my $src (keys %$pages) {
1898 my $d=$pages->{$src};
1900 if (exists $d->{page} && ! $rebuild) {
1904 $page=pagename($src);
1906 $pagectime{$page}=$d->{ctime};
1907 $pagesources{$page}=$src;
1909 $pagemtime{$page}=$d->{mtime};
1910 $renderedfiles{$page}=$d->{dest};
1911 if (exists $d->{links} && ref $d->{links}) {
1912 $links{$page}=$d->{links};
1913 $oldlinks{$page}=[@{$d->{links}}];
1915 if (ref $d->{depends_simple} eq 'ARRAY') {
1917 $depends_simple{$page}={
1918 map { $_ => 1 } @{$d->{depends_simple}}
1921 elsif (exists $d->{depends_simple}) {
1922 $depends_simple{$page}=$d->{depends_simple};
1924 if (exists $d->{dependslist}) {
1927 map { $_ => $DEPEND_CONTENT }
1928 @{$d->{dependslist}}
1931 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1933 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1935 elsif (exists $d->{depends}) {
1936 $depends{$page}=$d->{depends};
1938 if (exists $d->{state}) {
1939 $pagestate{$page}=$d->{state};
1941 if (exists $d->{typedlinks}) {
1942 $typedlinks{$page}=$d->{typedlinks};
1944 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1945 next unless %$links;
1946 $oldtypedlinks{$page}{$type} = {%$links};
1950 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1952 foreach my $page (keys %pagesources) {
1953 $pagecase{lc $page}=$page;
1955 foreach my $page (keys %renderedfiles) {
1956 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1958 $lastrev=$index->{lastrev};
1959 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1964 run_hooks(savestate => sub { shift->() });
1966 my @plugins=keys %loaded_plugins;
1968 if (! -d $config{wikistatedir}) {
1969 mkdir($config{wikistatedir});
1971 my $newfile="$config{wikistatedir}/indexdb.new";
1972 my $cleanup = sub { unlink($newfile) };
1973 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1976 foreach my $page (keys %pagemtime) {
1977 next unless $pagemtime{$page};
1978 my $src=$pagesources{$page};
1980 $index{page}{$src}={
1982 ctime => $pagectime{$page},
1983 mtime => $pagemtime{$page},
1984 dest => $renderedfiles{$page},
1985 links => $links{$page},
1988 if (exists $depends{$page}) {
1989 $index{page}{$src}{depends} = $depends{$page};
1992 if (exists $depends_simple{$page}) {
1993 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1996 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1997 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2000 if (exists $pagestate{$page}) {
2001 $index{page}{$src}{state}=$pagestate{$page};
2006 foreach my $id (@plugins) {
2007 $index{state}{$id}={}; # used to detect disabled plugins
2008 foreach my $key (keys %{$wikistate{$id}}) {
2009 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2013 $index{lastrev}=$lastrev;
2014 $index{underlayfiles}=\@underlayfiles;
2016 $index{version}="3";
2017 my $ret=Storable::nstore_fd(\%index, $out);
2018 return if ! defined $ret || ! $ret;
2019 close $out || error("failed saving to $newfile: $!", $cleanup);
2020 rename($newfile, "$config{wikistatedir}/indexdb") ||
2021 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2026 sub template_file ($) {
2029 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2031 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2032 $template=srcfile($pagesources{$tpage}, 1);
2036 $template=srcfile($tpage, 1);
2039 if (defined $template) {
2040 return $template, $tpage, 1 if wantarray;
2044 $name=~s:/::; # avoid path traversal
2045 foreach my $dir ($config{templatedir},
2046 "$installdir/share/ikiwiki/templates") {
2047 if (-e "$dir/$name") {
2048 $template="$dir/$name";
2052 if (defined $template) {
2053 return $template, $tpage if wantarray;
2061 sub template_depends ($$;@) {
2065 my ($filename, $tpage, $untrusted)=template_file($name);
2066 if (! defined $filename) {
2067 error(sprintf(gettext("template %s not found"), $name))
2070 if (defined $page && defined $tpage) {
2071 add_depends($page, $tpage);
2076 my $text_ref = shift;
2077 ${$text_ref} = decode_utf8(${$text_ref});
2078 run_hooks(readtemplate => sub {
2079 ${$text_ref} = shift->(
2082 content => ${$text_ref},
2083 untrusted => $untrusted,
2087 loop_context_vars => 1,
2088 die_on_bad_params => 0,
2089 parent_global_vars => 1,
2090 filename => $filename,
2092 ($untrusted ? (no_includes => 1) : ()),
2094 return @opts if wantarray;
2096 require HTML::Template;
2097 return HTML::Template->new(@opts);
2100 sub template ($;@) {
2101 template_depends(shift, undef, @_);
2104 sub templateactions ($$) {
2110 run_hooks(pageactions => sub {
2111 push @actions, map { { action => $_ } }
2112 grep { defined } shift->(page => $page);
2114 $template->param(actions => \@actions);
2116 if ($config{cgiurl} && exists $hooks{auth}) {
2117 $template->param(prefsurl => cgiurl(do => "prefs"));
2121 if ($have_actions || @actions) {
2122 $template->param(have_actions => 1);
2129 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2130 error 'hook requires type, call, and id parameters';
2133 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2135 $hooks{$param{type}}{$param{id}}=\%param;
2139 sub run_hooks ($$) {
2140 # Calls the given sub for each hook of the given type,
2141 # passing it the hook function to call.
2145 if (exists $hooks{$type}) {
2146 my (@first, @middle, @last);
2147 foreach my $id (keys %{$hooks{$type}}) {
2148 if ($hooks{$type}{$id}{first}) {
2151 elsif ($hooks{$type}{$id}{last}) {
2158 foreach my $id (@first, @middle, @last) {
2159 $sub->($hooks{$type}{$id}{call});
2167 $hooks{rcs}{rcs_update}{call}->(@_);
2170 sub rcs_prepedit ($) {
2171 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2174 sub rcs_commit (@) {
2175 $hooks{rcs}{rcs_commit}{call}->(@_);
2178 sub rcs_commit_staged (@) {
2179 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2183 $hooks{rcs}{rcs_add}{call}->(@_);
2186 sub rcs_remove ($) {
2187 $hooks{rcs}{rcs_remove}{call}->(@_);
2190 sub rcs_rename ($$) {
2191 $hooks{rcs}{rcs_rename}{call}->(@_);
2194 sub rcs_recentchanges ($) {
2195 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2198 sub rcs_diff ($;$) {
2199 $hooks{rcs}{rcs_diff}{call}->(@_);
2202 sub rcs_getctime ($) {
2203 $hooks{rcs}{rcs_getctime}{call}->(@_);
2206 sub rcs_getmtime ($) {
2207 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2210 sub rcs_receive () {
2211 $hooks{rcs}{rcs_receive}{call}->();
2214 sub add_depends ($$;$) {
2217 my $deptype=shift || $DEPEND_CONTENT;
2219 # Is the pagespec a simple page name?
2220 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2221 $pagespec !~ /[\s*?()!]/) {
2222 $depends_simple{$page}{lc $pagespec} |= $deptype;
2226 # Add explicit dependencies for influences.
2227 my $sub=pagespec_translate($pagespec);
2228 return unless defined $sub;
2229 foreach my $p (keys %pagesources) {
2230 my $r=$sub->($p, location => $page);
2231 my $i=$r->influences;
2232 my $static=$r->influences_static;
2233 foreach my $k (keys %$i) {
2234 next unless $r || $static || $k eq $page;
2235 $depends_simple{$page}{lc $k} |= $i->{$k};
2240 $depends{$page}{$pagespec} |= $deptype;
2246 foreach my $type (@_) {
2247 if ($type eq 'presence') {
2248 $deptype |= $DEPEND_PRESENCE;
2250 elsif ($type eq 'links') {
2251 $deptype |= $DEPEND_LINKS;
2253 elsif ($type eq 'content') {
2254 $deptype |= $DEPEND_CONTENT;
2260 my $file_prune_regexp;
2261 sub file_pruned ($) {
2264 if (defined $config{include} && length $config{include}) {
2265 return 0 if $file =~ m/$config{include}/;
2268 if (! defined $file_prune_regexp) {
2269 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2270 $file_prune_regexp=qr/$file_prune_regexp/;
2272 return $file =~ m/$file_prune_regexp/;
2275 sub define_gettext () {
2276 # If translation is needed, redefine the gettext function to do it.
2277 # Otherwise, it becomes a quick no-op.
2280 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2281 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2282 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2284 $gettext_obj=eval q{
2285 use Locale::gettext q{textdomain};
2286 Locale::gettext->domain('ikiwiki')
2291 no warnings 'redefine';
2293 $getobj->() if $getobj;
2295 $gettext_obj->get(shift);
2302 $getobj->() if $getobj;
2304 $gettext_obj->nget(@_);
2307 return ($_[2] == 1 ? $_[0] : $_[1])
2325 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2329 # Injects a new function into the symbol table to replace an
2330 # exported function.
2333 # This is deep ugly perl foo, beware.
2336 if (! defined $params{parent}) {
2337 $params{parent}='::';
2338 $params{old}=\&{$params{name}};
2339 $params{name}=~s/.*:://;
2341 my $parent=$params{parent};
2342 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2343 $ns = $params{parent} . $ns;
2344 inject(%params, parent => $ns) unless $ns eq '::main::';
2345 *{$ns . $params{name}} = $params{call}
2346 if exists ${$ns}{$params{name}} &&
2347 \&{${$ns}{$params{name}}} == $params{old};
2353 sub add_link ($$;$) {
2358 push @{$links{$page}}, $link
2359 unless grep { $_ eq $link } @{$links{$page}};
2361 if (defined $type) {
2362 $typedlinks{$page}{$type}{$link} = 1;
2366 sub add_autofile ($$$) {
2369 my $generator=shift;
2371 $autofiles{$file}{plugin}=$plugin;
2372 $autofiles{$file}{generator}=$generator;
2376 return LWP::UserAgent->new(
2377 cookie_jar => $config{cookiejar},
2378 env_proxy => 1, # respect proxy env vars
2379 agent => $config{useragent},
2383 sub sortspec_translate ($$) {
2385 my $reverse = shift;
2391 (-?) # group 1: perhaps negated
2394 \w+\([^\)]*\) # command(params)
2396 [^\s]+ # or anything else
2404 if ($word =~ m/^(\w+)\((.*)\)$/) {
2405 # command with parameters
2409 elsif ($word !~ m/^\w+$/) {
2410 error(sprintf(gettext("invalid sort type %s"), $word));
2421 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2422 if (defined $params) {
2423 push @data, $params;
2424 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2427 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2431 error(sprintf(gettext("unknown sort type %s"), $word));
2435 if (! length $code) {
2436 # undefined sorting method... sort arbitrarily
2445 return eval 'sub { '.$code.' }';
2448 sub pagespec_translate ($) {
2451 # Convert spec to perl code.
2455 \s* # ignore whitespace
2456 ( # 1: match a single word
2463 \w+\([^\)]*\) # command(params)
2465 [^\s()]+ # any other text
2467 \s* # ignore whitespace
2470 if (lc $word eq 'and') {
2473 elsif (lc $word eq 'or') {
2476 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2479 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2480 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2482 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2485 push @data, qq{unknown function in pagespec "$word"};
2486 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2491 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2495 if (! length $code) {
2496 $code="IkiWiki::FailReason->new('empty pagespec')";
2500 return eval 'sub { my $page=shift; '.$code.' }';
2503 sub pagespec_match ($$;@) {
2508 # Backwards compatability with old calling convention.
2510 unshift @params, 'location';
2513 my $sub=pagespec_translate($spec);
2514 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2516 return $sub->($page, @params);
2519 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2521 # Not exported yet, but could be in future if it is generally useful.
2522 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2523 # which is "more internal".
2524 sub sort_pages ($$;@) {
2528 $sort = sortspec_translate($sort, $params{reverse});
2529 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2532 sub pagespec_match_list ($$;@) {
2537 # Backwards compatability with old calling convention.
2539 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2540 $params{list}=$page;
2541 $page=$params{location}; # ugh!
2544 my $sub=pagespec_translate($pagespec);
2545 error "syntax error in pagespec \"$pagespec\""
2547 my $sort=sortspec_translate($params{sort}, $params{reverse})
2548 if defined $params{sort};
2551 if (exists $params{list}) {
2552 @candidates=exists $params{filter}
2553 ? grep { ! $params{filter}->($_) } @{$params{list}}
2557 @candidates=exists $params{filter}
2558 ? grep { ! $params{filter}->($_) } keys %pagesources
2559 : keys %pagesources;
2562 # clear params, remainder is passed to pagespec
2563 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2564 my $num=$params{num};
2565 delete @params{qw{num deptype reverse sort filter list}};
2567 # when only the top matches will be returned, it's efficient to
2568 # sort before matching to pagespec,
2569 if (defined $num && defined $sort) {
2570 @candidates=IkiWiki::SortSpec::sort_pages(
2571 $sort, @candidates);
2577 my $accum=IkiWiki::SuccessReason->new();
2578 foreach my $p (@candidates) {
2579 my $r=$sub->($p, %params, location => $page);
2580 error(sprintf(gettext("cannot match pages: %s"), $r))
2581 if $r->isa("IkiWiki::ErrorReason");
2582 unless ($r || $r->influences_static) {
2583 $r->remove_influence($p);
2588 last if defined $num && ++$count == $num;
2592 # Add simple dependencies for accumulated influences.
2593 my $i=$accum->influences;
2594 foreach my $k (keys %$i) {
2595 $depends_simple{$page}{lc $k} |= $i->{$k};
2598 # when all matches will be returned, it's efficient to
2599 # sort after matching
2600 if (! defined $num && defined $sort) {
2601 return IkiWiki::SortSpec::sort_pages(
2609 sub pagespec_valid ($) {
2612 return defined pagespec_translate($spec);
2616 my $re=quotemeta(shift);
2622 package IkiWiki::FailReason;
2625 '""' => sub { $_[0][0] },
2627 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2628 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2629 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2633 our @ISA = 'IkiWiki::SuccessReason';
2635 package IkiWiki::SuccessReason;
2637 # A blessed array-ref:
2639 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2641 # - if absent or false, the influences of this evaluation are "static",
2642 # see the influences_static method
2643 # - if true, they are dynamic (not static)
2644 # [1]{any other key}:
2645 # the dependency types of influences, as returned by the influences method
2648 # in string context, it's the human-readable reason
2649 '""' => sub { $_[0][0] },
2650 # in boolean context, SuccessReason is 1 and FailReason is 0
2652 # negating a result gives the opposite result with the same influences
2653 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2654 # A & B = (A ? B : A) with the influences of both
2655 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2656 # A | B = (A ? A : B) with the influences of both
2657 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2661 # SuccessReason->new("human-readable reason", page => deptype, ...)
2666 return bless [$value, {@_}], $class;
2669 # influences(): return a reference to a copy of the hash
2670 # { page => dependency type } describing the pages that indirectly influenced
2671 # this result, but would not cause a dependency through ikiwiki's core
2674 # See [[todo/dependency_types]] for extensive discussion of what this means.
2676 # influences(page => deptype, ...): remove all influences, replace them
2677 # with the arguments, and return a reference to a copy of the new influences.
2681 $this->[1]={@_} if @_;
2682 my %i=%{$this->[1]};
2687 # True if this result has the same influences whichever page it matches,
2688 # For instance, whether bar matches backlink(foo) is influenced only by
2689 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2690 # which does not mention bar anywhere.
2692 # False if this result would have different influences when matching
2693 # different pages. For instance, when testing whether link(foo) matches bar,
2694 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2695 # bar's links could change the outcome; so its influences are not the same
2696 # as when testing whether link(foo) matches baz.
2698 # Static influences are one of the things that make pagespec_match_list
2699 # more efficient than repeated calls to pagespec_match.
2701 sub influences_static {
2702 return ! $_[0][1]->{""};
2705 # Change the influences of $this to be the influences of "$this & $other"
2706 # or "$this | $other".
2708 # If both $this and $other are either successful or have influences,
2709 # or this is an "or" operation, the result has all the influences from
2710 # either of the arguments. It has dynamic influences if either argument
2711 # has dynamic influences.
2713 # If this is an "and" operation, and at least one argument is a
2714 # FailReason with no influences, the result has no influences, and they
2715 # are not dynamic. For instance, link(foo) matching bar is influenced
2716 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2717 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2718 # bar, because it would be false however often you edit bar.
2720 sub merge_influences {
2725 # This "if" is odd because it needs to avoid negating $this
2726 # or $other, which would alter the objects in-place. Be careful.
2727 if (! $anded || (($this || %{$this->[1]}) &&
2728 ($other || %{$other->[1]}))) {
2729 foreach my $influence (keys %{$other->[1]}) {
2730 $this->[1]{$influence} |= $other->[1]{$influence};
2739 # Change $this so it is not considered to be influenced by $torm.
2741 sub remove_influence {
2745 delete $this->[1]{$torm};
2748 package IkiWiki::ErrorReason;
2750 our @ISA = 'IkiWiki::FailReason';
2752 package IkiWiki::PageSpec;
2758 if ($path =~ m!^\.(/|$)!) {
2760 $from=~s#/?[^/]+$## if defined $from;
2762 $path="$from/$path" if defined $from && length $from;
2766 $path = "" unless defined $path;
2775 sub match_glob ($$;@) {
2780 $glob=derel($glob, $params{location});
2782 # Instead of converting the glob to a regex every time,
2783 # cache the compiled regex to save time.
2784 my $re=$glob_cache{$glob};
2785 unless (defined $re) {
2786 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2789 if (! IkiWiki::isinternal($page) || $params{internal}) {
2790 return IkiWiki::SuccessReason->new("$glob matches $page");
2793 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2797 return IkiWiki::FailReason->new("$glob does not match $page");
2801 sub match_internal ($$;@) {
2802 return match_glob(shift, shift, @_, internal => 1)
2805 sub match_page ($$;@) {
2807 my $match=match_glob($page, shift, @_);
2809 my $source=exists $IkiWiki::pagesources{$page} ?
2810 $IkiWiki::pagesources{$page} :
2811 $IkiWiki::delpagesources{$page};
2812 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2813 if (! defined $type) {
2814 return IkiWiki::FailReason->new("$page is not a page");
2820 sub match_link ($$;@) {
2825 $link=derel($link, $params{location});
2826 my $from=exists $params{location} ? $params{location} : '';
2827 my $linktype=$params{linktype};
2829 if (defined $linktype) {
2830 $qualifier=" with type $linktype";
2833 my $links = $IkiWiki::links{$page};
2834 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2835 unless $links && @{$links};
2836 my $bestlink = IkiWiki::bestlink($from, $link);
2837 foreach my $p (@{$links}) {
2838 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2840 if (length $bestlink) {
2841 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2842 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2846 if (match_glob($p, $link, %params)) {
2847 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2849 my ($p_rel)=$p=~/^\/?(.*)/;
2851 if (match_glob($p_rel, $link, %params)) {
2852 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2856 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2859 sub match_backlink ($$;@) {
2863 if ($testpage eq '.') {
2864 $testpage = $params{'location'}
2866 my $ret=match_link($testpage, $page, @_);
2867 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2871 sub match_created_before ($$;@) {
2876 $testpage=derel($testpage, $params{location});
2878 if (exists $IkiWiki::pagectime{$testpage}) {
2879 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2880 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2883 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2887 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2891 sub match_created_after ($$;@) {
2896 $testpage=derel($testpage, $params{location});
2898 if (exists $IkiWiki::pagectime{$testpage}) {
2899 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2900 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2903 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2907 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2911 sub match_creation_day ($$;@) {
2914 if ($d !~ /^\d+$/) {
2915 return IkiWiki::ErrorReason->new("invalid day $d");
2917 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2918 return IkiWiki::SuccessReason->new('creation_day matched');
2921 return IkiWiki::FailReason->new('creation_day did not match');
2925 sub match_creation_month ($$;@) {
2928 if ($m !~ /^\d+$/) {
2929 return IkiWiki::ErrorReason->new("invalid month $m");
2931 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2932 return IkiWiki::SuccessReason->new('creation_month matched');
2935 return IkiWiki::FailReason->new('creation_month did not match');
2939 sub match_creation_year ($$;@) {
2942 if ($y !~ /^\d+$/) {
2943 return IkiWiki::ErrorReason->new("invalid year $y");
2945 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2946 return IkiWiki::SuccessReason->new('creation_year matched');
2949 return IkiWiki::FailReason->new('creation_year did not match');
2953 sub match_user ($$;@) {
2958 if (! exists $params{user}) {
2959 return IkiWiki::ErrorReason->new("no user specified");
2962 my $regexp=IkiWiki::glob2re($user);
2964 if (defined $params{user} && $params{user}=~$regexp) {
2965 return IkiWiki::SuccessReason->new("user is $user");
2967 elsif (! defined $params{user}) {
2968 return IkiWiki::FailReason->new("not logged in");
2971 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2975 sub match_admin ($$;@) {
2980 if (! exists $params{user}) {
2981 return IkiWiki::ErrorReason->new("no user specified");
2984 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2985 return IkiWiki::SuccessReason->new("user is an admin");
2987 elsif (! defined $params{user}) {
2988 return IkiWiki::FailReason->new("not logged in");
2991 return IkiWiki::FailReason->new("user is not an admin");
2995 sub match_ip ($$;@) {
3000 if (! exists $params{ip}) {
3001 return IkiWiki::ErrorReason->new("no IP specified");
3004 my $regexp=IkiWiki::glob2re(lc $ip);
3006 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3007 return IkiWiki::SuccessReason->new("IP is $ip");
3010 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3014 package IkiWiki::SortSpec;
3016 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3017 # are easily available in this namespace, for cmp functions to use them.
3024 IkiWiki::pagetitle(IkiWiki::basename($a))
3026 IkiWiki::pagetitle(IkiWiki::basename($b))
3029 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3030 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3031 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }