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 => "generate HTML5?",
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",
554 sub defaultconfig () {
557 foreach my $key (keys %s) {
558 push @ret, $key, $s{$key}->{default};
563 # URL to top of wiki as a path starting with /, valid from any wiki page or
564 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
566 # URL to CGI script, similar to $local_url
570 # locale stuff; avoid LC_ALL since it overrides everything
571 if (defined $ENV{LC_ALL}) {
572 $ENV{LANG} = $ENV{LC_ALL};
575 if (defined $config{locale}) {
576 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
577 $ENV{LANG}=$config{locale};
582 if (! defined $config{wiki_file_regexp}) {
583 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
586 if (ref $config{ENV} eq 'HASH') {
587 foreach my $val (keys %{$config{ENV}}) {
588 $ENV{$val}=$config{ENV}{$val};
591 if (defined $config{timezone} && length $config{timezone}) {
592 $ENV{TZ}=$config{timezone};
595 $config{timezone}=$ENV{TZ};
598 if ($config{w3mmode}) {
599 eval q{use Cwd q{abs_path}};
601 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
602 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
603 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
604 unless $config{cgiurl} =~ m!file:///!;
605 $config{url}="file://".$config{destdir};
608 if ($config{cgi} && ! length $config{url}) {
609 error(gettext("Must specify url to wiki with --url when using --cgi"));
612 if (defined $config{url} && length $config{url}) {
614 my $baseurl = URI->new($config{url});
616 $local_url = $baseurl->path . "/";
617 $local_cgiurl = undef;
619 if (length $config{cgiurl}) {
620 my $cgiurl = URI->new($config{cgiurl});
622 $local_cgiurl = $cgiurl->path;
624 if ($cgiurl->scheme eq 'https' &&
625 $baseurl->scheme eq 'http') {
626 # We assume that the same content is available
627 # over both http and https, because if it
628 # wasn't, accessing the static content
629 # from the CGI would be mixed-content,
630 # which would be a security flaw.
632 if ($cgiurl->authority ne $baseurl->authority) {
633 # use protocol-relative URL for
635 $local_url = "$config{url}/";
636 $local_url =~ s{^http://}{//};
638 # else use host-relative URL for static content
640 # either way, CGI needs to be absolute
641 $local_cgiurl = $config{cgiurl};
643 elsif ($cgiurl->scheme ne $baseurl->scheme) {
644 # too far apart, fall back to absolute URLs
645 $local_url = "$config{url}/";
646 $local_cgiurl = $config{cgiurl};
648 elsif ($cgiurl->authority ne $baseurl->authority) {
649 # slightly too far apart, fall back to
650 # protocol-relative URLs
651 $local_url = "$config{url}/";
652 $local_url =~ s{^https?://}{//};
653 $local_cgiurl = $config{cgiurl};
654 $local_cgiurl =~ s{^https?://}{//};
656 # else keep host-relative URLs
659 $local_url =~ s{//$}{/};
662 $local_cgiurl = $config{cgiurl};
665 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
666 unless exists $config{wikistatedir} && defined $config{wikistatedir};
668 if (defined $config{umask}) {
669 my $u = possibly_foolish_untaint($config{umask});
671 if ($u =~ m/^\d+$/) {
674 elsif ($u eq 'private') {
677 elsif ($u eq 'group') {
680 elsif ($u eq 'public') {
684 error(sprintf(gettext("unsupported umask setting %s"), $u));
688 run_hooks(checkconfig => sub { shift->() });
696 foreach my $dir (@INC, $config{libdir}) {
697 next unless defined $dir && length $dir;
698 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
699 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
703 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
704 next unless defined $dir && length $dir;
705 foreach my $file (glob("$dir/plugins/*")) {
706 $ret{basename($file)}=1 if -x $file;
714 if (defined $config{libdir} && length $config{libdir}) {
715 unshift @INC, possibly_foolish_untaint($config{libdir});
718 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
723 if (exists $hooks{rcs}) {
724 error(gettext("cannot use multiple rcs plugins"));
726 loadplugin($config{rcs});
728 if (! exists $hooks{rcs}) {
732 run_hooks(getopt => sub { shift->() });
733 if (grep /^-/, @ARGV) {
734 print STDERR "Unknown option (or missing parameter): $_\n"
735 foreach grep /^-/, @ARGV;
742 sub loadplugin ($;$) {
746 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
748 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
749 "$installdir/lib/ikiwiki") {
750 if (defined $dir && -x "$dir/plugins/$plugin") {
751 eval { require IkiWiki::Plugin::external };
754 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
756 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
757 $loaded_plugins{$plugin}=1;
762 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
765 error("Failed to load plugin $mod: $@");
767 $loaded_plugins{$plugin}=1;
774 log_message('err' => $message) if $config{syslog};
775 if (defined $cleaner) {
782 return unless $config{verbose};
783 return log_message(debug => @_);
788 sub log_message ($$) {
791 if ($config{syslog}) {
794 Sys::Syslog::setlogsock('unix');
795 Sys::Syslog::openlog('ikiwiki', '', 'user');
799 # keep a copy to avoid editing the original config repeatedly
800 my $wikiname = $config{wikiname};
801 utf8::encode($wikiname);
802 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
805 print STDERR "failed to syslog: $@" unless $log_failed;
811 elsif (! $config{cgi}) {
815 return print STDERR "@_\n";
819 sub possibly_foolish_untaint ($) {
821 my ($untainted)=$tainted=~/(.*)/s;
841 return exists $pagesources{$page} &&
842 $pagesources{$page} =~ /\._([^.]+)$/;
848 if ($file =~ /\.([^.]+)$/) {
849 return $1 if exists $hooks{htmlize}{$1};
851 my $base=basename($file);
852 if (exists $hooks{htmlize}{$base} &&
853 $hooks{htmlize}{$base}{noextension}) {
864 if (exists $pagename_cache{$file}) {
865 return $pagename_cache{$file};
868 my $type=pagetype($file);
870 $page=~s/\Q.$type\E*$//
871 if defined $type && !$hooks{htmlize}{$type}{keepextension}
872 && !$hooks{htmlize}{$type}{noextension};
873 if ($config{indexpages} && $page=~/(.*)\/index$/) {
877 $pagename_cache{$file} = $page;
881 sub newpagefile ($$) {
885 if (! $config{indexpages} || $page eq 'index') {
886 return $page.".".$type;
889 return $page."/index.".$type;
893 sub targetpage ($$;$) {
898 if (defined $filename) {
899 return $page."/".$filename.".".$ext;
901 elsif (! $config{usedirs} || $page eq 'index') {
902 return $page.".".$ext;
905 return $page."/index.".$ext;
912 return targetpage($page, $config{htmlext});
919 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
920 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
921 return "$dir/$file", stat(_) if -e "$dir/$file";
923 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
928 return (srcfile_stat(@_))[0];
931 sub add_literal_underlay ($) {
934 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
935 unshift @{$config{underlaydirs}}, $dir;
939 sub add_underlay ($) {
943 $dir="$config{underlaydirbase}/$dir";
946 add_literal_underlay($dir);
947 # why does it return 1? we just don't know
951 sub readfile ($;$$) {
957 error("cannot read a symlink ($file)");
961 open (my $in, "<", $file) || error("failed to read $file: $!");
962 binmode($in) if ($binary);
963 return \*$in if $wantfd;
965 # check for invalid utf-8, and toss it back to avoid crashes
966 if (! utf8::valid($ret)) {
967 $ret=encode_utf8($ret);
969 close $in || error("failed to read $file: $!");
973 sub prep_writefile ($$) {
978 while (length $test) {
979 if (-l "$destdir/$test") {
980 error("cannot write to a symlink ($test)");
982 if (-f _ && $test ne $file) {
983 # Remove conflicting file.
984 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
985 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
987 unlink("$destdir/$test");
993 $test=dirname($test);
996 my $dir=dirname("$destdir/$file");
999 foreach my $s (split(m!/+!, $dir)) {
1002 mkdir($d) || error("failed to create directory $d: $!");
1010 sub writefile ($$$;$$) {
1011 my $file=shift; # can include subdirs
1012 my $destdir=shift; # directory to put file in
1017 prep_writefile($file, $destdir);
1019 my $newfile="$destdir/$file.ikiwiki-new";
1021 error("cannot write to a symlink ($newfile)");
1024 my $cleanup = sub { unlink($newfile) };
1025 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1026 binmode($out) if ($binary);
1028 $writer->(\*$out, $cleanup);
1031 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1033 close $out || error("failed saving $newfile: $!", $cleanup);
1034 rename($newfile, "$destdir/$file") ||
1035 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1041 sub will_render ($$;$) {
1046 # Important security check for independently created files.
1047 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1048 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1049 my $from_other_page=0;
1050 # Expensive, but rarely runs.
1051 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1054 dirname($_) eq $dest
1055 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1061 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1062 unless $from_other_page;
1065 # If $dest exists as a directory, remove conflicting files in it
1066 # rendered from other pages.
1068 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1069 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1070 if (dirname($f) eq $dest) {
1071 unlink("$config{destdir}/$f");
1072 rmdir(dirname("$config{destdir}/$f"));
1078 if (! $clear || $cleared{$page}) {
1079 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1082 foreach my $old (@{$renderedfiles{$page}}) {
1083 delete $destsources{$old};
1085 $renderedfiles{$page}=[$dest];
1088 $destsources{$dest}=$page;
1098 if ($link=~s/^\/+//) {
1106 $l.="/" if length $l;
1109 if (exists $pagesources{$l}) {
1112 elsif (exists $pagecase{lc $l}) {
1113 return $pagecase{lc $l};
1115 } while $cwd=~s{/?[^/]+$}{};
1117 if (length $config{userdir}) {
1118 my $l = "$config{userdir}/".lc($link);
1119 if (exists $pagesources{$l}) {
1122 elsif (exists $pagecase{lc $l}) {
1123 return $pagecase{lc $l};
1127 #print STDERR "warning: page $page, broken link: $link\n";
1131 sub isinlinableimage ($) {
1134 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1137 sub pagetitle ($;$) {
1139 my $unescaped=shift;
1142 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1145 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1153 # support use w/o %config set
1154 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1155 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1161 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1162 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1169 my $cgiurl=$local_cgiurl;
1171 if (exists $params{cgiurl}) {
1172 $cgiurl=$params{cgiurl};
1173 delete $params{cgiurl};
1181 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1184 sub cgiurl_abs (@) {
1186 URI->new_abs(cgiurl(@_), $config{cgiurl});
1192 return $local_url if ! defined $page;
1194 $page=htmlpage($page);
1196 $page=~s/[^\/]+\//..\//g;
1204 return $url unless defined $urlbase && length $urlbase;
1207 URI->new_abs($url, $urlbase)->as_string;
1211 # Work around very innefficient behavior in File::Spec if abs2rel
1212 # is passed two relative paths. It's much faster if paths are
1213 # absolute! (Debian bug #376658; fixed in debian unstable now)
1218 my $ret=File::Spec->abs2rel($path, $base);
1219 $ret=~s/^// if defined $ret;
1223 sub displaytime ($;$$) {
1224 # Plugins can override this function to mark up the time to
1226 my $time=formattime($_[0], $_[1]);
1227 if ($config{html5}) {
1228 return '<time datetime="'.date_3339($_[0]).'"'.
1229 ($_[2] ? ' pubdate="pubdate"' : '').
1230 '>'.$time.'</time>';
1233 return '<span class="date">'.$time.'</span>';
1237 sub formattime ($;$) {
1238 # Plugins can override this function to format the time.
1241 if (! defined $format) {
1242 $format=$config{timeformat};
1245 return strftime_utf8($format, localtime($time));
1248 my $strftime_encoding;
1250 # strftime doesn't know about encodings, so make sure
1251 # its output is properly treated as utf8.
1252 # Note that this does not handle utf-8 in the format string.
1253 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1254 unless defined $strftime_encoding;
1256 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1257 : POSIX::strftime(@_);
1263 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1264 POSIX::setlocale(&POSIX::LC_TIME, "C");
1265 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1266 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1270 sub beautify_urlpath ($) {
1273 # Ensure url is not an empty link, and if necessary,
1274 # add ./ to avoid colon confusion.
1275 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1279 if ($config{usedirs}) {
1280 $url =~ s!/index.$config{htmlext}$!/!;
1295 if (! $destsources{$to}) {
1300 return $config{url}.beautify_urlpath("/".$to);
1303 if (! defined $from) {
1304 my $u = $local_url || '';
1306 return $u.beautify_urlpath("/".$to);
1309 my $link = abs2rel($to, dirname(htmlpage($from)));
1311 return beautify_urlpath($link);
1314 sub isselflink ($$) {
1315 # Plugins can override this function to support special types
1320 return $page eq $link;
1323 sub htmllink ($$$;@) {
1324 my $lpage=shift; # the page doing the linking
1325 my $page=shift; # the page that will contain the link (different for inline)
1332 if (! $opts{forcesubpage}) {
1333 $bestlink=bestlink($lpage, $link);
1336 $bestlink="$lpage/".lc($link);
1340 if (defined $opts{linktext}) {
1341 $linktext=$opts{linktext};
1344 $linktext=pagetitle(basename($link));
1347 return "<span class=\"selflink\">$linktext</span>"
1348 if length $bestlink && isselflink($page, $bestlink) &&
1349 ! defined $opts{anchor};
1351 if (! $destsources{$bestlink}) {
1352 $bestlink=htmlpage($bestlink);
1354 if (! $destsources{$bestlink}) {
1356 if (length $config{cgiurl}) {
1357 $cgilink = "<a href=\"".
1362 )."\" rel=\"nofollow\">?</a>";
1364 return "<span class=\"createlink\">$cgilink$linktext</span>"
1368 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1369 $bestlink=beautify_urlpath($bestlink);
1371 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1372 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1375 if (defined $opts{anchor}) {
1376 $bestlink.="#".$opts{anchor};
1380 foreach my $attr (qw{rel class title}) {
1381 if (defined $opts{$attr}) {
1382 push @attrs, " $attr=\"$opts{$attr}\"";
1386 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1391 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1394 sub openiduser ($) {
1397 if (defined $user && $user =~ m!^https?://! &&
1398 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1401 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1402 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1405 # backcompat with old version
1406 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1407 $display=$oid->display;
1410 # Convert "user.somehost.com" to "user [somehost.com]"
1411 # (also "user.somehost.co.uk")
1412 if ($display !~ /\[/) {
1413 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1415 # Convert "http://somehost.com/user" to "user [somehost.com]".
1416 # (also "https://somehost.com/user/")
1417 if ($display !~ /\[/) {
1418 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1420 $display=~s!^https?://!!; # make sure this is removed
1421 eval q{use CGI 'escapeHTML'};
1423 return escapeHTML($display);
1428 sub htmlize ($$$$) {
1434 my $oneline = $content !~ /\n/;
1436 if (exists $hooks{htmlize}{$type}) {
1437 $content=$hooks{htmlize}{$type}{call}->(
1439 content => $content,
1443 error("htmlization of $type not supported");
1446 run_hooks(sanitize => sub {
1449 destpage => $destpage,
1450 content => $content,
1455 # hack to get rid of enclosing junk added by markdown
1456 # and other htmlizers/sanitizers
1457 $content=~s/^<p>//i;
1458 $content=~s/<\/p>\n*$//i;
1469 run_hooks(linkify => sub {
1472 destpage => $destpage,
1473 content => $content,
1481 our $preprocess_preview=0;
1482 sub preprocess ($$$;$$) {
1483 my $page=shift; # the page the data comes from
1484 my $destpage=shift; # the page the data will appear in (different for inline)
1489 # Using local because it needs to be set within any nested calls
1491 local $preprocess_preview=$preview if defined $preview;
1498 $params="" if ! defined $params;
1500 if (length $escape) {
1501 return "[[$prefix$command $params]]";
1503 elsif (exists $hooks{preprocess}{$command}) {
1504 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1505 # Note: preserve order of params, some plugins may
1506 # consider it significant.
1508 while ($params =~ m{
1509 (?:([-.\w]+)=)? # 1: named parameter key?
1511 """(.*?)""" # 2: triple-quoted value
1513 "([^"]*?)" # 3: single-quoted value
1515 '''(.*?)''' # 4: triple-single-quote
1517 <<([a-zA-Z]+)\n # 5: heredoc start
1518 (.*?)\n\5 # 6: heredoc value
1520 (\S+) # 7: unquoted value
1522 (?:\s+|$) # delimiter to next param
1532 elsif (defined $3) {
1535 elsif (defined $4) {
1538 elsif (defined $7) {
1541 elsif (defined $6) {
1546 push @params, $key, $val;
1549 push @params, $val, '';
1552 if ($preprocessing{$page}++ > 8) {
1553 # Avoid loops of preprocessed pages preprocessing
1554 # other pages that preprocess them, etc.
1555 return "[[!$command <span class=\"error\">".
1556 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1557 $page, $preprocessing{$page}).
1563 $hooks{preprocess}{$command}{call}->(
1566 destpage => $destpage,
1567 preview => $preprocess_preview,
1573 $ret="[[!$command <span class=\"error\">".
1574 gettext("Error").": $error"."</span>]]";
1578 # use void context during scan pass
1580 $hooks{preprocess}{$command}{call}->(
1583 destpage => $destpage,
1584 preview => $preprocess_preview,
1589 $preprocessing{$page}--;
1593 return "[[$prefix$command $params]]";
1598 if ($config{prefix_directives}) {
1601 \[\[(!) # directive open; 2: prefix
1602 ([-\w]+) # 3: command
1603 ( # 4: the parameters..
1604 \s+ # Must have space if parameters present
1606 (?:[-.\w]+=)? # named parameter key?
1608 """.*?""" # triple-quoted value
1610 "[^"]*?" # single-quoted value
1612 '''.*?''' # triple-single-quote
1614 <<([a-zA-Z]+)\n # 5: heredoc start
1615 (?:.*?)\n\5 # heredoc value
1617 [^"\s\]]+ # unquoted value
1619 \s* # whitespace or end
1622 *)? # 0 or more parameters
1623 \]\] # directive closed
1629 \[\[(!?) # directive open; 2: optional prefix
1630 ([-\w]+) # 3: command
1632 ( # 4: the parameters..
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
1655 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1664 run_hooks(filter => sub {
1665 $content=shift->(page => $page, destpage => $destpage,
1666 content => $content);
1672 sub check_canedit ($$$;$) {
1679 run_hooks(canedit => sub {
1680 return if defined $canedit;
1681 my $ret=shift->($page, $q, $session);
1686 elsif (ref $ret eq 'CODE') {
1687 $ret->() unless $nonfatal;
1690 elsif (defined $ret) {
1691 error($ret) unless $nonfatal;
1696 return defined $canedit ? $canedit : 1;
1699 sub check_content (@) {
1702 return 1 if ! exists $hooks{checkcontent}; # optimisation
1704 if (exists $pagesources{$params{page}}) {
1706 my %old=map { $_ => 1 }
1707 split("\n", readfile(srcfile($pagesources{$params{page}})));
1708 foreach my $line (split("\n", $params{content})) {
1709 push @diff, $line if ! exists $old{$line};
1711 $params{diff}=join("\n", @diff);
1715 run_hooks(checkcontent => sub {
1716 return if defined $ok;
1717 my $ret=shift->(%params);
1722 elsif (ref $ret eq 'CODE') {
1723 $ret->() unless $params{nonfatal};
1726 elsif (defined $ret) {
1727 error($ret) unless $params{nonfatal};
1733 return defined $ok ? $ok : 1;
1736 sub check_canchange (@) {
1738 my $cgi = $params{cgi};
1739 my $session = $params{session};
1740 my @changes = @{$params{changes}};
1743 foreach my $change (@changes) {
1744 # This untaint is safe because we check file_pruned and
1746 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1747 $file=possibly_foolish_untaint($file);
1748 if (! defined $file || ! length $file ||
1749 file_pruned($file)) {
1750 error(gettext("bad file name %s"), $file);
1753 my $type=pagetype($file);
1754 my $page=pagename($file) if defined $type;
1756 if ($change->{action} eq 'add') {
1760 if ($change->{action} eq 'change' ||
1761 $change->{action} eq 'add') {
1762 if (defined $page) {
1763 check_canedit($page, $cgi, $session);
1767 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1768 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1769 check_canedit($file, $cgi, $session);
1774 elsif ($change->{action} eq 'remove') {
1775 # check_canremove tests to see if the file is present
1776 # on disk. This will fail when a single commit adds a
1777 # file and then removes it again. Avoid the problem
1778 # by not testing the removal in such pairs of changes.
1779 # (The add is still tested, just to make sure that
1780 # no data is added to the repo that a web edit
1782 next if $newfiles{$file};
1784 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1785 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1786 check_canedit(defined $page ? $page : $file, $cgi, $session);
1791 error "unknown action ".$change->{action};
1794 error sprintf(gettext("you are not allowed to change %s"), $file);
1802 # Take an exclusive lock on the wiki to prevent multiple concurrent
1803 # run issues. The lock will be dropped on program exit.
1804 if (! -d $config{wikistatedir}) {
1805 mkdir($config{wikistatedir});
1807 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1808 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1809 if (! flock($wikilock, 2)) { # LOCK_EX
1810 error("failed to get lock");
1816 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1817 return close($wikilock) if $wikilock;
1823 sub commit_hook_enabled () {
1824 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1825 error("cannot write to $config{wikistatedir}/commitlock: $!");
1826 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1827 close($commitlock) || error("failed closing commitlock: $!");
1830 close($commitlock) || error("failed closing commitlock: $!");
1834 sub disable_commit_hook () {
1835 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1836 error("cannot write to $config{wikistatedir}/commitlock: $!");
1837 if (! flock($commitlock, 2)) { # LOCK_EX
1838 error("failed to get commit lock");
1843 sub enable_commit_hook () {
1844 return close($commitlock) if $commitlock;
1849 %oldrenderedfiles=%pagectime=();
1850 my $rebuild=$config{rebuild};
1852 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1853 %destsources=%renderedfiles=%pagecase=%pagestate=
1854 %depends_simple=%typedlinks=%oldtypedlinks=();
1857 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1858 if (-e "$config{wikistatedir}/index") {
1859 system("ikiwiki-transition", "indexdb", $config{srcdir});
1860 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1863 # gettime on first build
1864 $config{gettime}=1 unless defined $config{gettime};
1869 my $index=Storable::fd_retrieve($in);
1870 if (! defined $index) {
1875 if (exists $index->{version} && ! ref $index->{version}) {
1876 $pages=$index->{page};
1877 %wikistate=%{$index->{state}};
1878 # Handle plugins that got disabled by loading a new setup.
1879 if (exists $config{setupfile}) {
1880 require IkiWiki::Setup;
1881 IkiWiki::Setup::disabled_plugins(
1882 grep { ! $loaded_plugins{$_} } keys %wikistate);
1890 foreach my $src (keys %$pages) {
1891 my $d=$pages->{$src};
1893 if (exists $d->{page} && ! $rebuild) {
1897 $page=pagename($src);
1899 $pagectime{$page}=$d->{ctime};
1900 $pagesources{$page}=$src;
1902 $pagemtime{$page}=$d->{mtime};
1903 $renderedfiles{$page}=$d->{dest};
1904 if (exists $d->{links} && ref $d->{links}) {
1905 $links{$page}=$d->{links};
1906 $oldlinks{$page}=[@{$d->{links}}];
1908 if (ref $d->{depends_simple} eq 'ARRAY') {
1910 $depends_simple{$page}={
1911 map { $_ => 1 } @{$d->{depends_simple}}
1914 elsif (exists $d->{depends_simple}) {
1915 $depends_simple{$page}=$d->{depends_simple};
1917 if (exists $d->{dependslist}) {
1920 map { $_ => $DEPEND_CONTENT }
1921 @{$d->{dependslist}}
1924 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1926 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1928 elsif (exists $d->{depends}) {
1929 $depends{$page}=$d->{depends};
1931 if (exists $d->{state}) {
1932 $pagestate{$page}=$d->{state};
1934 if (exists $d->{typedlinks}) {
1935 $typedlinks{$page}=$d->{typedlinks};
1937 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1938 next unless %$links;
1939 $oldtypedlinks{$page}{$type} = {%$links};
1943 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1945 foreach my $page (keys %pagesources) {
1946 $pagecase{lc $page}=$page;
1948 foreach my $page (keys %renderedfiles) {
1949 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1951 $lastrev=$index->{lastrev};
1952 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1957 run_hooks(savestate => sub { shift->() });
1959 my @plugins=keys %loaded_plugins;
1961 if (! -d $config{wikistatedir}) {
1962 mkdir($config{wikistatedir});
1964 my $newfile="$config{wikistatedir}/indexdb.new";
1965 my $cleanup = sub { unlink($newfile) };
1966 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1969 foreach my $page (keys %pagemtime) {
1970 next unless $pagemtime{$page};
1971 my $src=$pagesources{$page};
1973 $index{page}{$src}={
1975 ctime => $pagectime{$page},
1976 mtime => $pagemtime{$page},
1977 dest => $renderedfiles{$page},
1978 links => $links{$page},
1981 if (exists $depends{$page}) {
1982 $index{page}{$src}{depends} = $depends{$page};
1985 if (exists $depends_simple{$page}) {
1986 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1989 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1990 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1993 if (exists $pagestate{$page}) {
1994 $index{page}{$src}{state}=$pagestate{$page};
1999 foreach my $id (@plugins) {
2000 $index{state}{$id}={}; # used to detect disabled plugins
2001 foreach my $key (keys %{$wikistate{$id}}) {
2002 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2006 $index{lastrev}=$lastrev;
2007 $index{underlayfiles}=\@underlayfiles;
2009 $index{version}="3";
2010 my $ret=Storable::nstore_fd(\%index, $out);
2011 return if ! defined $ret || ! $ret;
2012 close $out || error("failed saving to $newfile: $!", $cleanup);
2013 rename($newfile, "$config{wikistatedir}/indexdb") ||
2014 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2019 sub template_file ($) {
2022 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2024 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2025 $template=srcfile($pagesources{$tpage}, 1);
2029 $template=srcfile($tpage, 1);
2032 if (defined $template) {
2033 return $template, $tpage, 1 if wantarray;
2037 $name=~s:/::; # avoid path traversal
2038 foreach my $dir ($config{templatedir},
2039 "$installdir/share/ikiwiki/templates") {
2040 if (-e "$dir/$name") {
2041 $template="$dir/$name";
2045 if (defined $template) {
2046 return $template, $tpage if wantarray;
2054 sub template_depends ($$;@) {
2058 my ($filename, $tpage, $untrusted)=template_file($name);
2059 if (! defined $filename) {
2060 error(sprintf(gettext("template %s not found"), $name))
2063 if (defined $page && defined $tpage) {
2064 add_depends($page, $tpage);
2069 my $text_ref = shift;
2070 ${$text_ref} = decode_utf8(${$text_ref});
2071 run_hooks(readtemplate => sub {
2072 ${$text_ref} = shift->(
2075 content => ${$text_ref},
2076 untrusted => $untrusted,
2080 loop_context_vars => 1,
2081 die_on_bad_params => 0,
2082 parent_global_vars => 1,
2083 filename => $filename,
2085 ($untrusted ? (no_includes => 1) : ()),
2087 return @opts if wantarray;
2089 require HTML::Template;
2090 return HTML::Template->new(@opts);
2093 sub template ($;@) {
2094 template_depends(shift, undef, @_);
2097 sub templateactions ($$) {
2103 run_hooks(pageactions => sub {
2104 push @actions, map { { action => $_ } }
2105 grep { defined } shift->(page => $page);
2107 $template->param(actions => \@actions);
2109 if ($config{cgiurl} && exists $hooks{auth}) {
2110 $template->param(prefsurl => cgiurl(do => "prefs"));
2114 if ($have_actions || @actions) {
2115 $template->param(have_actions => 1);
2122 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2123 error 'hook requires type, call, and id parameters';
2126 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2128 $hooks{$param{type}}{$param{id}}=\%param;
2132 sub run_hooks ($$) {
2133 # Calls the given sub for each hook of the given type,
2134 # passing it the hook function to call.
2138 if (exists $hooks{$type}) {
2139 my (@first, @middle, @last);
2140 foreach my $id (keys %{$hooks{$type}}) {
2141 if ($hooks{$type}{$id}{first}) {
2144 elsif ($hooks{$type}{$id}{last}) {
2151 foreach my $id (@first, @middle, @last) {
2152 $sub->($hooks{$type}{$id}{call});
2160 $hooks{rcs}{rcs_update}{call}->(@_);
2163 sub rcs_prepedit ($) {
2164 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2167 sub rcs_commit (@) {
2168 $hooks{rcs}{rcs_commit}{call}->(@_);
2171 sub rcs_commit_staged (@) {
2172 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2176 $hooks{rcs}{rcs_add}{call}->(@_);
2179 sub rcs_remove ($) {
2180 $hooks{rcs}{rcs_remove}{call}->(@_);
2183 sub rcs_rename ($$) {
2184 $hooks{rcs}{rcs_rename}{call}->(@_);
2187 sub rcs_recentchanges ($) {
2188 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2191 sub rcs_diff ($;$) {
2192 $hooks{rcs}{rcs_diff}{call}->(@_);
2195 sub rcs_getctime ($) {
2196 $hooks{rcs}{rcs_getctime}{call}->(@_);
2199 sub rcs_getmtime ($) {
2200 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2203 sub rcs_receive () {
2204 $hooks{rcs}{rcs_receive}{call}->();
2207 sub add_depends ($$;$) {
2210 my $deptype=shift || $DEPEND_CONTENT;
2212 # Is the pagespec a simple page name?
2213 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2214 $pagespec !~ /[\s*?()!]/) {
2215 $depends_simple{$page}{lc $pagespec} |= $deptype;
2219 # Add explicit dependencies for influences.
2220 my $sub=pagespec_translate($pagespec);
2221 return unless defined $sub;
2222 foreach my $p (keys %pagesources) {
2223 my $r=$sub->($p, location => $page);
2224 my $i=$r->influences;
2225 my $static=$r->influences_static;
2226 foreach my $k (keys %$i) {
2227 next unless $r || $static || $k eq $page;
2228 $depends_simple{$page}{lc $k} |= $i->{$k};
2233 $depends{$page}{$pagespec} |= $deptype;
2239 foreach my $type (@_) {
2240 if ($type eq 'presence') {
2241 $deptype |= $DEPEND_PRESENCE;
2243 elsif ($type eq 'links') {
2244 $deptype |= $DEPEND_LINKS;
2246 elsif ($type eq 'content') {
2247 $deptype |= $DEPEND_CONTENT;
2253 my $file_prune_regexp;
2254 sub file_pruned ($) {
2257 if (defined $config{include} && length $config{include}) {
2258 return 0 if $file =~ m/$config{include}/;
2261 if (! defined $file_prune_regexp) {
2262 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2263 $file_prune_regexp=qr/$file_prune_regexp/;
2265 return $file =~ m/$file_prune_regexp/;
2268 sub define_gettext () {
2269 # If translation is needed, redefine the gettext function to do it.
2270 # Otherwise, it becomes a quick no-op.
2273 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2274 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2275 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2277 $gettext_obj=eval q{
2278 use Locale::gettext q{textdomain};
2279 Locale::gettext->domain('ikiwiki')
2284 no warnings 'redefine';
2286 $getobj->() if $getobj;
2288 $gettext_obj->get(shift);
2295 $getobj->() if $getobj;
2297 $gettext_obj->nget(@_);
2300 return ($_[2] == 1 ? $_[0] : $_[1])
2318 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2322 # Injects a new function into the symbol table to replace an
2323 # exported function.
2326 # This is deep ugly perl foo, beware.
2329 if (! defined $params{parent}) {
2330 $params{parent}='::';
2331 $params{old}=\&{$params{name}};
2332 $params{name}=~s/.*:://;
2334 my $parent=$params{parent};
2335 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2336 $ns = $params{parent} . $ns;
2337 inject(%params, parent => $ns) unless $ns eq '::main::';
2338 *{$ns . $params{name}} = $params{call}
2339 if exists ${$ns}{$params{name}} &&
2340 \&{${$ns}{$params{name}}} == $params{old};
2346 sub add_link ($$;$) {
2351 push @{$links{$page}}, $link
2352 unless grep { $_ eq $link } @{$links{$page}};
2354 if (defined $type) {
2355 $typedlinks{$page}{$type}{$link} = 1;
2359 sub add_autofile ($$$) {
2362 my $generator=shift;
2364 $autofiles{$file}{plugin}=$plugin;
2365 $autofiles{$file}{generator}=$generator;
2369 return LWP::UserAgent->new(
2370 cookie_jar => $config{cookiejar},
2371 env_proxy => 1, # respect proxy env vars
2372 agent => $config{useragent},
2376 sub sortspec_translate ($$) {
2378 my $reverse = shift;
2384 (-?) # group 1: perhaps negated
2387 \w+\([^\)]*\) # command(params)
2389 [^\s]+ # or anything else
2397 if ($word =~ m/^(\w+)\((.*)\)$/) {
2398 # command with parameters
2402 elsif ($word !~ m/^\w+$/) {
2403 error(sprintf(gettext("invalid sort type %s"), $word));
2414 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2415 if (defined $params) {
2416 push @data, $params;
2417 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2420 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2424 error(sprintf(gettext("unknown sort type %s"), $word));
2428 if (! length $code) {
2429 # undefined sorting method... sort arbitrarily
2438 return eval 'sub { '.$code.' }';
2441 sub pagespec_translate ($) {
2444 # Convert spec to perl code.
2448 \s* # ignore whitespace
2449 ( # 1: match a single word
2456 \w+\([^\)]*\) # command(params)
2458 [^\s()]+ # any other text
2460 \s* # ignore whitespace
2463 if (lc $word eq 'and') {
2466 elsif (lc $word eq 'or') {
2469 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2472 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2473 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2475 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2478 push @data, qq{unknown function in pagespec "$word"};
2479 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2484 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2488 if (! length $code) {
2489 $code="IkiWiki::FailReason->new('empty pagespec')";
2493 return eval 'sub { my $page=shift; '.$code.' }';
2496 sub pagespec_match ($$;@) {
2501 # Backwards compatability with old calling convention.
2503 unshift @params, 'location';
2506 my $sub=pagespec_translate($spec);
2507 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2509 return $sub->($page, @params);
2512 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2514 # Not exported yet, but could be in future if it is generally useful.
2515 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2516 # which is "more internal".
2517 sub sort_pages ($$;@) {
2521 $sort = sortspec_translate($sort, $params{reverse});
2522 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2525 sub pagespec_match_list ($$;@) {
2530 # Backwards compatability with old calling convention.
2532 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2533 $params{list}=$page;
2534 $page=$params{location}; # ugh!
2537 my $sub=pagespec_translate($pagespec);
2538 error "syntax error in pagespec \"$pagespec\""
2540 my $sort=sortspec_translate($params{sort}, $params{reverse})
2541 if defined $params{sort};
2544 if (exists $params{list}) {
2545 @candidates=exists $params{filter}
2546 ? grep { ! $params{filter}->($_) } @{$params{list}}
2550 @candidates=exists $params{filter}
2551 ? grep { ! $params{filter}->($_) } keys %pagesources
2552 : keys %pagesources;
2555 # clear params, remainder is passed to pagespec
2556 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2557 my $num=$params{num};
2558 delete @params{qw{num deptype reverse sort filter list}};
2560 # when only the top matches will be returned, it's efficient to
2561 # sort before matching to pagespec,
2562 if (defined $num && defined $sort) {
2563 @candidates=IkiWiki::SortSpec::sort_pages(
2564 $sort, @candidates);
2570 my $accum=IkiWiki::SuccessReason->new();
2571 foreach my $p (@candidates) {
2572 my $r=$sub->($p, %params, location => $page);
2573 error(sprintf(gettext("cannot match pages: %s"), $r))
2574 if $r->isa("IkiWiki::ErrorReason");
2575 unless ($r || $r->influences_static) {
2576 $r->remove_influence($p);
2581 last if defined $num && ++$count == $num;
2585 # Add simple dependencies for accumulated influences.
2586 my $i=$accum->influences;
2587 foreach my $k (keys %$i) {
2588 $depends_simple{$page}{lc $k} |= $i->{$k};
2591 # when all matches will be returned, it's efficient to
2592 # sort after matching
2593 if (! defined $num && defined $sort) {
2594 return IkiWiki::SortSpec::sort_pages(
2602 sub pagespec_valid ($) {
2605 return defined pagespec_translate($spec);
2609 my $re=quotemeta(shift);
2615 package IkiWiki::FailReason;
2618 '""' => sub { $_[0][0] },
2620 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2621 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2622 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2626 our @ISA = 'IkiWiki::SuccessReason';
2628 package IkiWiki::SuccessReason;
2630 # A blessed array-ref:
2632 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2634 # - if absent or false, the influences of this evaluation are "static",
2635 # see the influences_static method
2636 # - if true, they are dynamic (not static)
2637 # [1]{any other key}:
2638 # the dependency types of influences, as returned by the influences method
2641 # in string context, it's the human-readable reason
2642 '""' => sub { $_[0][0] },
2643 # in boolean context, SuccessReason is 1 and FailReason is 0
2645 # negating a result gives the opposite result with the same influences
2646 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2647 # A & B = (A ? B : A) with the influences of both
2648 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2649 # A | B = (A ? A : B) with the influences of both
2650 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2654 # SuccessReason->new("human-readable reason", page => deptype, ...)
2659 return bless [$value, {@_}], $class;
2662 # influences(): return a reference to a copy of the hash
2663 # { page => dependency type } describing the pages that indirectly influenced
2664 # this result, but would not cause a dependency through ikiwiki's core
2667 # See [[todo/dependency_types]] for extensive discussion of what this means.
2669 # influences(page => deptype, ...): remove all influences, replace them
2670 # with the arguments, and return a reference to a copy of the new influences.
2674 $this->[1]={@_} if @_;
2675 my %i=%{$this->[1]};
2680 # True if this result has the same influences whichever page it matches,
2681 # For instance, whether bar matches backlink(foo) is influenced only by
2682 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2683 # which does not mention bar anywhere.
2685 # False if this result would have different influences when matching
2686 # different pages. For instance, when testing whether link(foo) matches bar,
2687 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2688 # bar's links could change the outcome; so its influences are not the same
2689 # as when testing whether link(foo) matches baz.
2691 # Static influences are one of the things that make pagespec_match_list
2692 # more efficient than repeated calls to pagespec_match.
2694 sub influences_static {
2695 return ! $_[0][1]->{""};
2698 # Change the influences of $this to be the influences of "$this & $other"
2699 # or "$this | $other".
2701 # If both $this and $other are either successful or have influences,
2702 # or this is an "or" operation, the result has all the influences from
2703 # either of the arguments. It has dynamic influences if either argument
2704 # has dynamic influences.
2706 # If this is an "and" operation, and at least one argument is a
2707 # FailReason with no influences, the result has no influences, and they
2708 # are not dynamic. For instance, link(foo) matching bar is influenced
2709 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2710 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2711 # bar, because it would be false however often you edit bar.
2713 sub merge_influences {
2718 # This "if" is odd because it needs to avoid negating $this
2719 # or $other, which would alter the objects in-place. Be careful.
2720 if (! $anded || (($this || %{$this->[1]}) &&
2721 ($other || %{$other->[1]}))) {
2722 foreach my $influence (keys %{$other->[1]}) {
2723 $this->[1]{$influence} |= $other->[1]{$influence};
2732 # Change $this so it is not considered to be influenced by $torm.
2734 sub remove_influence {
2738 delete $this->[1]{$torm};
2741 package IkiWiki::ErrorReason;
2743 our @ISA = 'IkiWiki::FailReason';
2745 package IkiWiki::PageSpec;
2751 if ($path =~ m!^\.(/|$)!) {
2753 $from=~s#/?[^/]+$## if defined $from;
2755 $path="$from/$path" if defined $from && length $from;
2759 $path = "" unless defined $path;
2768 sub match_glob ($$;@) {
2773 $glob=derel($glob, $params{location});
2775 # Instead of converting the glob to a regex every time,
2776 # cache the compiled regex to save time.
2777 my $re=$glob_cache{$glob};
2778 unless (defined $re) {
2779 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2782 if (! IkiWiki::isinternal($page) || $params{internal}) {
2783 return IkiWiki::SuccessReason->new("$glob matches $page");
2786 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2790 return IkiWiki::FailReason->new("$glob does not match $page");
2794 sub match_internal ($$;@) {
2795 return match_glob(shift, shift, @_, internal => 1)
2798 sub match_page ($$;@) {
2800 my $match=match_glob($page, shift, @_);
2802 my $source=exists $IkiWiki::pagesources{$page} ?
2803 $IkiWiki::pagesources{$page} :
2804 $IkiWiki::delpagesources{$page};
2805 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2806 if (! defined $type) {
2807 return IkiWiki::FailReason->new("$page is not a page");
2813 sub match_link ($$;@) {
2818 $link=derel($link, $params{location});
2819 my $from=exists $params{location} ? $params{location} : '';
2820 my $linktype=$params{linktype};
2822 if (defined $linktype) {
2823 $qualifier=" with type $linktype";
2826 my $links = $IkiWiki::links{$page};
2827 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2828 unless $links && @{$links};
2829 my $bestlink = IkiWiki::bestlink($from, $link);
2830 foreach my $p (@{$links}) {
2831 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2833 if (length $bestlink) {
2834 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2835 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2839 if (match_glob($p, $link, %params)) {
2840 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2842 my ($p_rel)=$p=~/^\/?(.*)/;
2844 if (match_glob($p_rel, $link, %params)) {
2845 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2849 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2852 sub match_backlink ($$;@) {
2856 if ($testpage eq '.') {
2857 $testpage = $params{'location'}
2859 my $ret=match_link($testpage, $page, @_);
2860 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2864 sub match_created_before ($$;@) {
2869 $testpage=derel($testpage, $params{location});
2871 if (exists $IkiWiki::pagectime{$testpage}) {
2872 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2873 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2876 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2880 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2884 sub match_created_after ($$;@) {
2889 $testpage=derel($testpage, $params{location});
2891 if (exists $IkiWiki::pagectime{$testpage}) {
2892 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2893 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2896 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2900 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2904 sub match_creation_day ($$;@) {
2907 if ($d !~ /^\d+$/) {
2908 return IkiWiki::ErrorReason->new("invalid day $d");
2910 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2911 return IkiWiki::SuccessReason->new('creation_day matched');
2914 return IkiWiki::FailReason->new('creation_day did not match');
2918 sub match_creation_month ($$;@) {
2921 if ($m !~ /^\d+$/) {
2922 return IkiWiki::ErrorReason->new("invalid month $m");
2924 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2925 return IkiWiki::SuccessReason->new('creation_month matched');
2928 return IkiWiki::FailReason->new('creation_month did not match');
2932 sub match_creation_year ($$;@) {
2935 if ($y !~ /^\d+$/) {
2936 return IkiWiki::ErrorReason->new("invalid year $y");
2938 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2939 return IkiWiki::SuccessReason->new('creation_year matched');
2942 return IkiWiki::FailReason->new('creation_year did not match');
2946 sub match_user ($$;@) {
2951 if (! exists $params{user}) {
2952 return IkiWiki::ErrorReason->new("no user specified");
2955 my $regexp=IkiWiki::glob2re($user);
2957 if (defined $params{user} && $params{user}=~$regexp) {
2958 return IkiWiki::SuccessReason->new("user is $user");
2960 elsif (! defined $params{user}) {
2961 return IkiWiki::FailReason->new("not logged in");
2964 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2968 sub match_admin ($$;@) {
2973 if (! exists $params{user}) {
2974 return IkiWiki::ErrorReason->new("no user specified");
2977 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2978 return IkiWiki::SuccessReason->new("user is an admin");
2980 elsif (! defined $params{user}) {
2981 return IkiWiki::FailReason->new("not logged in");
2984 return IkiWiki::FailReason->new("user is not an admin");
2988 sub match_ip ($$;@) {
2993 if (! exists $params{ip}) {
2994 return IkiWiki::ErrorReason->new("no IP specified");
2997 my $regexp=IkiWiki::glob2re(lc $ip);
2999 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3000 return IkiWiki::SuccessReason->new("IP is $ip");
3003 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3007 package IkiWiki::SortSpec;
3009 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3010 # are easily available in this namespace, for cmp functions to use them.
3017 IkiWiki::pagetitle(IkiWiki::basename($a))
3019 IkiWiki::pagetitle(IkiWiki::basename($b))
3022 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3023 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3024 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }