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 eval q{use HTML::Entities};
1574 $error = encode_entities($error);
1575 $ret="[[!$command <span class=\"error\">".
1576 gettext("Error").": $error"."</span>]]";
1580 # use void context during scan pass
1582 $hooks{preprocess}{$command}{call}->(
1585 destpage => $destpage,
1586 preview => $preprocess_preview,
1591 $preprocessing{$page}--;
1595 return "[[$prefix$command $params]]";
1600 if ($config{prefix_directives}) {
1603 \[\[(!) # directive open; 2: prefix
1604 ([-\w]+) # 3: command
1605 ( # 4: the parameters..
1606 \s+ # Must have space if parameters present
1608 (?:[-.\w]+=)? # named parameter key?
1610 """.*?""" # triple-quoted value
1612 "[^"]*?" # single-quoted value
1614 '''.*?''' # triple-single-quote
1616 <<([a-zA-Z]+)\n # 5: heredoc start
1617 (?:.*?)\n\5 # heredoc value
1619 [^"\s\]]+ # unquoted value
1621 \s* # whitespace or end
1624 *)? # 0 or more parameters
1625 \]\] # directive closed
1631 \[\[(!?) # directive open; 2: optional prefix
1632 ([-\w]+) # 3: command
1634 ( # 4: the parameters..
1636 (?:[-.\w]+=)? # named parameter key?
1638 """.*?""" # triple-quoted value
1640 "[^"]*?" # single-quoted value
1642 '''.*?''' # triple-single-quote
1644 <<([a-zA-Z]+)\n # 5: heredoc start
1645 (?:.*?)\n\5 # heredoc value
1647 [^"\s\]]+ # unquoted value
1649 \s* # whitespace or end
1652 *) # 0 or more parameters
1653 \]\] # directive closed
1657 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1666 run_hooks(filter => sub {
1667 $content=shift->(page => $page, destpage => $destpage,
1668 content => $content);
1674 sub check_canedit ($$$;$) {
1681 run_hooks(canedit => sub {
1682 return if defined $canedit;
1683 my $ret=shift->($page, $q, $session);
1688 elsif (ref $ret eq 'CODE') {
1689 $ret->() unless $nonfatal;
1692 elsif (defined $ret) {
1693 error($ret) unless $nonfatal;
1698 return defined $canedit ? $canedit : 1;
1701 sub check_content (@) {
1704 return 1 if ! exists $hooks{checkcontent}; # optimisation
1706 if (exists $pagesources{$params{page}}) {
1708 my %old=map { $_ => 1 }
1709 split("\n", readfile(srcfile($pagesources{$params{page}})));
1710 foreach my $line (split("\n", $params{content})) {
1711 push @diff, $line if ! exists $old{$line};
1713 $params{diff}=join("\n", @diff);
1717 run_hooks(checkcontent => sub {
1718 return if defined $ok;
1719 my $ret=shift->(%params);
1724 elsif (ref $ret eq 'CODE') {
1725 $ret->() unless $params{nonfatal};
1728 elsif (defined $ret) {
1729 error($ret) unless $params{nonfatal};
1735 return defined $ok ? $ok : 1;
1738 sub check_canchange (@) {
1740 my $cgi = $params{cgi};
1741 my $session = $params{session};
1742 my @changes = @{$params{changes}};
1745 foreach my $change (@changes) {
1746 # This untaint is safe because we check file_pruned and
1748 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1749 $file=possibly_foolish_untaint($file);
1750 if (! defined $file || ! length $file ||
1751 file_pruned($file)) {
1752 error(gettext("bad file name %s"), $file);
1755 my $type=pagetype($file);
1756 my $page=pagename($file) if defined $type;
1758 if ($change->{action} eq 'add') {
1762 if ($change->{action} eq 'change' ||
1763 $change->{action} eq 'add') {
1764 if (defined $page) {
1765 check_canedit($page, $cgi, $session);
1769 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1770 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1771 check_canedit($file, $cgi, $session);
1776 elsif ($change->{action} eq 'remove') {
1777 # check_canremove tests to see if the file is present
1778 # on disk. This will fail when a single commit adds a
1779 # file and then removes it again. Avoid the problem
1780 # by not testing the removal in such pairs of changes.
1781 # (The add is still tested, just to make sure that
1782 # no data is added to the repo that a web edit
1784 next if $newfiles{$file};
1786 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1787 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1788 check_canedit(defined $page ? $page : $file, $cgi, $session);
1793 error "unknown action ".$change->{action};
1796 error sprintf(gettext("you are not allowed to change %s"), $file);
1804 # Take an exclusive lock on the wiki to prevent multiple concurrent
1805 # run issues. The lock will be dropped on program exit.
1806 if (! -d $config{wikistatedir}) {
1807 mkdir($config{wikistatedir});
1809 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1810 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1811 if (! flock($wikilock, 2)) { # LOCK_EX
1812 error("failed to get lock");
1818 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1819 return close($wikilock) if $wikilock;
1825 sub commit_hook_enabled () {
1826 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1827 error("cannot write to $config{wikistatedir}/commitlock: $!");
1828 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1829 close($commitlock) || error("failed closing commitlock: $!");
1832 close($commitlock) || error("failed closing commitlock: $!");
1836 sub disable_commit_hook () {
1837 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1838 error("cannot write to $config{wikistatedir}/commitlock: $!");
1839 if (! flock($commitlock, 2)) { # LOCK_EX
1840 error("failed to get commit lock");
1845 sub enable_commit_hook () {
1846 return close($commitlock) if $commitlock;
1851 %oldrenderedfiles=%pagectime=();
1852 my $rebuild=$config{rebuild};
1854 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1855 %destsources=%renderedfiles=%pagecase=%pagestate=
1856 %depends_simple=%typedlinks=%oldtypedlinks=();
1859 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1860 if (-e "$config{wikistatedir}/index") {
1861 system("ikiwiki-transition", "indexdb", $config{srcdir});
1862 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1865 # gettime on first build
1866 $config{gettime}=1 unless defined $config{gettime};
1871 my $index=Storable::fd_retrieve($in);
1872 if (! defined $index) {
1877 if (exists $index->{version} && ! ref $index->{version}) {
1878 $pages=$index->{page};
1879 %wikistate=%{$index->{state}};
1880 # Handle plugins that got disabled by loading a new setup.
1881 if (exists $config{setupfile}) {
1882 require IkiWiki::Setup;
1883 IkiWiki::Setup::disabled_plugins(
1884 grep { ! $loaded_plugins{$_} } keys %wikistate);
1892 foreach my $src (keys %$pages) {
1893 my $d=$pages->{$src};
1895 if (exists $d->{page} && ! $rebuild) {
1899 $page=pagename($src);
1901 $pagectime{$page}=$d->{ctime};
1902 $pagesources{$page}=$src;
1904 $pagemtime{$page}=$d->{mtime};
1905 $renderedfiles{$page}=$d->{dest};
1906 if (exists $d->{links} && ref $d->{links}) {
1907 $links{$page}=$d->{links};
1908 $oldlinks{$page}=[@{$d->{links}}];
1910 if (ref $d->{depends_simple} eq 'ARRAY') {
1912 $depends_simple{$page}={
1913 map { $_ => 1 } @{$d->{depends_simple}}
1916 elsif (exists $d->{depends_simple}) {
1917 $depends_simple{$page}=$d->{depends_simple};
1919 if (exists $d->{dependslist}) {
1922 map { $_ => $DEPEND_CONTENT }
1923 @{$d->{dependslist}}
1926 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1928 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1930 elsif (exists $d->{depends}) {
1931 $depends{$page}=$d->{depends};
1933 if (exists $d->{state}) {
1934 $pagestate{$page}=$d->{state};
1936 if (exists $d->{typedlinks}) {
1937 $typedlinks{$page}=$d->{typedlinks};
1939 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1940 next unless %$links;
1941 $oldtypedlinks{$page}{$type} = {%$links};
1945 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1947 foreach my $page (keys %pagesources) {
1948 $pagecase{lc $page}=$page;
1950 foreach my $page (keys %renderedfiles) {
1951 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1953 $lastrev=$index->{lastrev};
1954 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1959 run_hooks(savestate => sub { shift->() });
1961 my @plugins=keys %loaded_plugins;
1963 if (! -d $config{wikistatedir}) {
1964 mkdir($config{wikistatedir});
1966 my $newfile="$config{wikistatedir}/indexdb.new";
1967 my $cleanup = sub { unlink($newfile) };
1968 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1971 foreach my $page (keys %pagemtime) {
1972 next unless $pagemtime{$page};
1973 my $src=$pagesources{$page};
1975 $index{page}{$src}={
1977 ctime => $pagectime{$page},
1978 mtime => $pagemtime{$page},
1979 dest => $renderedfiles{$page},
1980 links => $links{$page},
1983 if (exists $depends{$page}) {
1984 $index{page}{$src}{depends} = $depends{$page};
1987 if (exists $depends_simple{$page}) {
1988 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1991 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1992 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1995 if (exists $pagestate{$page}) {
1996 $index{page}{$src}{state}=$pagestate{$page};
2001 foreach my $id (@plugins) {
2002 $index{state}{$id}={}; # used to detect disabled plugins
2003 foreach my $key (keys %{$wikistate{$id}}) {
2004 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2008 $index{lastrev}=$lastrev;
2009 $index{underlayfiles}=\@underlayfiles;
2011 $index{version}="3";
2012 my $ret=Storable::nstore_fd(\%index, $out);
2013 return if ! defined $ret || ! $ret;
2014 close $out || error("failed saving to $newfile: $!", $cleanup);
2015 rename($newfile, "$config{wikistatedir}/indexdb") ||
2016 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2021 sub template_file ($) {
2024 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2026 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2027 $template=srcfile($pagesources{$tpage}, 1);
2031 $template=srcfile($tpage, 1);
2034 if (defined $template) {
2035 return $template, $tpage, 1 if wantarray;
2039 $name=~s:/::; # avoid path traversal
2040 foreach my $dir ($config{templatedir},
2041 "$installdir/share/ikiwiki/templates") {
2042 if (-e "$dir/$name") {
2043 $template="$dir/$name";
2047 if (defined $template) {
2048 return $template, $tpage if wantarray;
2056 sub template_depends ($$;@) {
2060 my ($filename, $tpage, $untrusted)=template_file($name);
2061 if (! defined $filename) {
2062 error(sprintf(gettext("template %s not found"), $name))
2065 if (defined $page && defined $tpage) {
2066 add_depends($page, $tpage);
2071 my $text_ref = shift;
2072 ${$text_ref} = decode_utf8(${$text_ref});
2073 run_hooks(readtemplate => sub {
2074 ${$text_ref} = shift->(
2077 content => ${$text_ref},
2078 untrusted => $untrusted,
2082 loop_context_vars => 1,
2083 die_on_bad_params => 0,
2084 parent_global_vars => 1,
2085 filename => $filename,
2087 ($untrusted ? (no_includes => 1) : ()),
2089 return @opts if wantarray;
2091 require HTML::Template;
2092 return HTML::Template->new(@opts);
2095 sub template ($;@) {
2096 template_depends(shift, undef, @_);
2099 sub templateactions ($$) {
2105 run_hooks(pageactions => sub {
2106 push @actions, map { { action => $_ } }
2107 grep { defined } shift->(page => $page);
2109 $template->param(actions => \@actions);
2111 if ($config{cgiurl} && exists $hooks{auth}) {
2112 $template->param(prefsurl => cgiurl(do => "prefs"));
2116 if ($have_actions || @actions) {
2117 $template->param(have_actions => 1);
2124 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2125 error 'hook requires type, call, and id parameters';
2128 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2130 $hooks{$param{type}}{$param{id}}=\%param;
2134 sub run_hooks ($$) {
2135 # Calls the given sub for each hook of the given type,
2136 # passing it the hook function to call.
2140 if (exists $hooks{$type}) {
2141 my (@first, @middle, @last);
2142 foreach my $id (keys %{$hooks{$type}}) {
2143 if ($hooks{$type}{$id}{first}) {
2146 elsif ($hooks{$type}{$id}{last}) {
2153 foreach my $id (@first, @middle, @last) {
2154 $sub->($hooks{$type}{$id}{call});
2162 $hooks{rcs}{rcs_update}{call}->(@_);
2165 sub rcs_prepedit ($) {
2166 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2169 sub rcs_commit (@) {
2170 $hooks{rcs}{rcs_commit}{call}->(@_);
2173 sub rcs_commit_staged (@) {
2174 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2178 $hooks{rcs}{rcs_add}{call}->(@_);
2181 sub rcs_remove ($) {
2182 $hooks{rcs}{rcs_remove}{call}->(@_);
2185 sub rcs_rename ($$) {
2186 $hooks{rcs}{rcs_rename}{call}->(@_);
2189 sub rcs_recentchanges ($) {
2190 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2193 sub rcs_diff ($;$) {
2194 $hooks{rcs}{rcs_diff}{call}->(@_);
2197 sub rcs_getctime ($) {
2198 $hooks{rcs}{rcs_getctime}{call}->(@_);
2201 sub rcs_getmtime ($) {
2202 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2205 sub rcs_receive () {
2206 $hooks{rcs}{rcs_receive}{call}->();
2209 sub add_depends ($$;$) {
2212 my $deptype=shift || $DEPEND_CONTENT;
2214 # Is the pagespec a simple page name?
2215 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2216 $pagespec !~ /[\s*?()!]/) {
2217 $depends_simple{$page}{lc $pagespec} |= $deptype;
2221 # Add explicit dependencies for influences.
2222 my $sub=pagespec_translate($pagespec);
2223 return unless defined $sub;
2224 foreach my $p (keys %pagesources) {
2225 my $r=$sub->($p, location => $page);
2226 my $i=$r->influences;
2227 my $static=$r->influences_static;
2228 foreach my $k (keys %$i) {
2229 next unless $r || $static || $k eq $page;
2230 $depends_simple{$page}{lc $k} |= $i->{$k};
2235 $depends{$page}{$pagespec} |= $deptype;
2241 foreach my $type (@_) {
2242 if ($type eq 'presence') {
2243 $deptype |= $DEPEND_PRESENCE;
2245 elsif ($type eq 'links') {
2246 $deptype |= $DEPEND_LINKS;
2248 elsif ($type eq 'content') {
2249 $deptype |= $DEPEND_CONTENT;
2255 my $file_prune_regexp;
2256 sub file_pruned ($) {
2259 if (defined $config{include} && length $config{include}) {
2260 return 0 if $file =~ m/$config{include}/;
2263 if (! defined $file_prune_regexp) {
2264 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2265 $file_prune_regexp=qr/$file_prune_regexp/;
2267 return $file =~ m/$file_prune_regexp/;
2270 sub define_gettext () {
2271 # If translation is needed, redefine the gettext function to do it.
2272 # Otherwise, it becomes a quick no-op.
2275 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2276 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2277 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2279 $gettext_obj=eval q{
2280 use Locale::gettext q{textdomain};
2281 Locale::gettext->domain('ikiwiki')
2286 no warnings 'redefine';
2288 $getobj->() if $getobj;
2290 $gettext_obj->get(shift);
2297 $getobj->() if $getobj;
2299 $gettext_obj->nget(@_);
2302 return ($_[2] == 1 ? $_[0] : $_[1])
2320 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2324 # Injects a new function into the symbol table to replace an
2325 # exported function.
2328 # This is deep ugly perl foo, beware.
2331 if (! defined $params{parent}) {
2332 $params{parent}='::';
2333 $params{old}=\&{$params{name}};
2334 $params{name}=~s/.*:://;
2336 my $parent=$params{parent};
2337 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2338 $ns = $params{parent} . $ns;
2339 inject(%params, parent => $ns) unless $ns eq '::main::';
2340 *{$ns . $params{name}} = $params{call}
2341 if exists ${$ns}{$params{name}} &&
2342 \&{${$ns}{$params{name}}} == $params{old};
2348 sub add_link ($$;$) {
2353 push @{$links{$page}}, $link
2354 unless grep { $_ eq $link } @{$links{$page}};
2356 if (defined $type) {
2357 $typedlinks{$page}{$type}{$link} = 1;
2361 sub add_autofile ($$$) {
2364 my $generator=shift;
2366 $autofiles{$file}{plugin}=$plugin;
2367 $autofiles{$file}{generator}=$generator;
2371 return LWP::UserAgent->new(
2372 cookie_jar => $config{cookiejar},
2373 env_proxy => 1, # respect proxy env vars
2374 agent => $config{useragent},
2378 sub sortspec_translate ($$) {
2380 my $reverse = shift;
2386 (-?) # group 1: perhaps negated
2389 \w+\([^\)]*\) # command(params)
2391 [^\s]+ # or anything else
2399 if ($word =~ m/^(\w+)\((.*)\)$/) {
2400 # command with parameters
2404 elsif ($word !~ m/^\w+$/) {
2405 error(sprintf(gettext("invalid sort type %s"), $word));
2416 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2417 if (defined $params) {
2418 push @data, $params;
2419 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2422 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2426 error(sprintf(gettext("unknown sort type %s"), $word));
2430 if (! length $code) {
2431 # undefined sorting method... sort arbitrarily
2440 return eval 'sub { '.$code.' }';
2443 sub pagespec_translate ($) {
2446 # Convert spec to perl code.
2450 \s* # ignore whitespace
2451 ( # 1: match a single word
2458 \w+\([^\)]*\) # command(params)
2460 [^\s()]+ # any other text
2462 \s* # ignore whitespace
2465 if (lc $word eq 'and') {
2468 elsif (lc $word eq 'or') {
2471 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2474 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2475 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2477 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2480 push @data, qq{unknown function in pagespec "$word"};
2481 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2486 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2490 if (! length $code) {
2491 $code="IkiWiki::FailReason->new('empty pagespec')";
2495 return eval 'sub { my $page=shift; '.$code.' }';
2498 sub pagespec_match ($$;@) {
2503 # Backwards compatability with old calling convention.
2505 unshift @params, 'location';
2508 my $sub=pagespec_translate($spec);
2509 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2511 return $sub->($page, @params);
2514 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2516 # Not exported yet, but could be in future if it is generally useful.
2517 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2518 # which is "more internal".
2519 sub sort_pages ($$;@) {
2523 $sort = sortspec_translate($sort, $params{reverse});
2524 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2527 sub pagespec_match_list ($$;@) {
2532 # Backwards compatability with old calling convention.
2534 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2535 $params{list}=$page;
2536 $page=$params{location}; # ugh!
2539 my $sub=pagespec_translate($pagespec);
2540 error "syntax error in pagespec \"$pagespec\""
2542 my $sort=sortspec_translate($params{sort}, $params{reverse})
2543 if defined $params{sort};
2546 if (exists $params{list}) {
2547 @candidates=exists $params{filter}
2548 ? grep { ! $params{filter}->($_) } @{$params{list}}
2552 @candidates=exists $params{filter}
2553 ? grep { ! $params{filter}->($_) } keys %pagesources
2554 : keys %pagesources;
2557 # clear params, remainder is passed to pagespec
2558 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2559 my $num=$params{num};
2560 delete @params{qw{num deptype reverse sort filter list}};
2562 # when only the top matches will be returned, it's efficient to
2563 # sort before matching to pagespec,
2564 if (defined $num && defined $sort) {
2565 @candidates=IkiWiki::SortSpec::sort_pages(
2566 $sort, @candidates);
2572 my $accum=IkiWiki::SuccessReason->new();
2573 foreach my $p (@candidates) {
2574 my $r=$sub->($p, %params, location => $page);
2575 error(sprintf(gettext("cannot match pages: %s"), $r))
2576 if $r->isa("IkiWiki::ErrorReason");
2577 unless ($r || $r->influences_static) {
2578 $r->remove_influence($p);
2583 last if defined $num && ++$count == $num;
2587 # Add simple dependencies for accumulated influences.
2588 my $i=$accum->influences;
2589 foreach my $k (keys %$i) {
2590 $depends_simple{$page}{lc $k} |= $i->{$k};
2593 # when all matches will be returned, it's efficient to
2594 # sort after matching
2595 if (! defined $num && defined $sort) {
2596 return IkiWiki::SortSpec::sort_pages(
2604 sub pagespec_valid ($) {
2607 return defined pagespec_translate($spec);
2611 my $re=quotemeta(shift);
2617 package IkiWiki::FailReason;
2620 '""' => sub { $_[0][0] },
2622 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2623 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2624 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2628 our @ISA = 'IkiWiki::SuccessReason';
2630 package IkiWiki::SuccessReason;
2632 # A blessed array-ref:
2634 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2636 # - if absent or false, the influences of this evaluation are "static",
2637 # see the influences_static method
2638 # - if true, they are dynamic (not static)
2639 # [1]{any other key}:
2640 # the dependency types of influences, as returned by the influences method
2643 # in string context, it's the human-readable reason
2644 '""' => sub { $_[0][0] },
2645 # in boolean context, SuccessReason is 1 and FailReason is 0
2647 # negating a result gives the opposite result with the same influences
2648 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2649 # A & B = (A ? B : A) with the influences of both
2650 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2651 # A | B = (A ? A : B) with the influences of both
2652 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2656 # SuccessReason->new("human-readable reason", page => deptype, ...)
2661 return bless [$value, {@_}], $class;
2664 # influences(): return a reference to a copy of the hash
2665 # { page => dependency type } describing the pages that indirectly influenced
2666 # this result, but would not cause a dependency through ikiwiki's core
2669 # See [[todo/dependency_types]] for extensive discussion of what this means.
2671 # influences(page => deptype, ...): remove all influences, replace them
2672 # with the arguments, and return a reference to a copy of the new influences.
2676 $this->[1]={@_} if @_;
2677 my %i=%{$this->[1]};
2682 # True if this result has the same influences whichever page it matches,
2683 # For instance, whether bar matches backlink(foo) is influenced only by
2684 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2685 # which does not mention bar anywhere.
2687 # False if this result would have different influences when matching
2688 # different pages. For instance, when testing whether link(foo) matches bar,
2689 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2690 # bar's links could change the outcome; so its influences are not the same
2691 # as when testing whether link(foo) matches baz.
2693 # Static influences are one of the things that make pagespec_match_list
2694 # more efficient than repeated calls to pagespec_match.
2696 sub influences_static {
2697 return ! $_[0][1]->{""};
2700 # Change the influences of $this to be the influences of "$this & $other"
2701 # or "$this | $other".
2703 # If both $this and $other are either successful or have influences,
2704 # or this is an "or" operation, the result has all the influences from
2705 # either of the arguments. It has dynamic influences if either argument
2706 # has dynamic influences.
2708 # If this is an "and" operation, and at least one argument is a
2709 # FailReason with no influences, the result has no influences, and they
2710 # are not dynamic. For instance, link(foo) matching bar is influenced
2711 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2712 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2713 # bar, because it would be false however often you edit bar.
2715 sub merge_influences {
2720 # This "if" is odd because it needs to avoid negating $this
2721 # or $other, which would alter the objects in-place. Be careful.
2722 if (! $anded || (($this || %{$this->[1]}) &&
2723 ($other || %{$other->[1]}))) {
2724 foreach my $influence (keys %{$other->[1]}) {
2725 $this->[1]{$influence} |= $other->[1]{$influence};
2734 # Change $this so it is not considered to be influenced by $torm.
2736 sub remove_influence {
2740 delete $this->[1]{$torm};
2743 package IkiWiki::ErrorReason;
2745 our @ISA = 'IkiWiki::FailReason';
2747 package IkiWiki::PageSpec;
2753 if ($path =~ m!^\.(/|$)!) {
2755 $from=~s#/?[^/]+$## if defined $from;
2757 $path="$from/$path" if defined $from && length $from;
2761 $path = "" unless defined $path;
2770 sub match_glob ($$;@) {
2775 $glob=derel($glob, $params{location});
2777 # Instead of converting the glob to a regex every time,
2778 # cache the compiled regex to save time.
2779 my $re=$glob_cache{$glob};
2780 unless (defined $re) {
2781 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2784 if (! IkiWiki::isinternal($page) || $params{internal}) {
2785 return IkiWiki::SuccessReason->new("$glob matches $page");
2788 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2792 return IkiWiki::FailReason->new("$glob does not match $page");
2796 sub match_internal ($$;@) {
2797 return match_glob(shift, shift, @_, internal => 1)
2800 sub match_page ($$;@) {
2802 my $match=match_glob($page, shift, @_);
2804 my $source=exists $IkiWiki::pagesources{$page} ?
2805 $IkiWiki::pagesources{$page} :
2806 $IkiWiki::delpagesources{$page};
2807 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2808 if (! defined $type) {
2809 return IkiWiki::FailReason->new("$page is not a page");
2815 sub match_link ($$;@) {
2820 $link=derel($link, $params{location});
2821 my $from=exists $params{location} ? $params{location} : '';
2822 my $linktype=$params{linktype};
2824 if (defined $linktype) {
2825 $qualifier=" with type $linktype";
2828 my $links = $IkiWiki::links{$page};
2829 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2830 unless $links && @{$links};
2831 my $bestlink = IkiWiki::bestlink($from, $link);
2832 foreach my $p (@{$links}) {
2833 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2835 if (length $bestlink) {
2836 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2837 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2841 if (match_glob($p, $link, %params)) {
2842 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2844 my ($p_rel)=$p=~/^\/?(.*)/;
2846 if (match_glob($p_rel, $link, %params)) {
2847 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2851 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2854 sub match_backlink ($$;@) {
2858 if ($testpage eq '.') {
2859 $testpage = $params{'location'}
2861 my $ret=match_link($testpage, $page, @_);
2862 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2866 sub match_created_before ($$;@) {
2871 $testpage=derel($testpage, $params{location});
2873 if (exists $IkiWiki::pagectime{$testpage}) {
2874 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2875 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2878 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2882 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2886 sub match_created_after ($$;@) {
2891 $testpage=derel($testpage, $params{location});
2893 if (exists $IkiWiki::pagectime{$testpage}) {
2894 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2895 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2898 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2902 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2906 sub match_creation_day ($$;@) {
2909 if ($d !~ /^\d+$/) {
2910 return IkiWiki::ErrorReason->new("invalid day $d");
2912 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2913 return IkiWiki::SuccessReason->new('creation_day matched');
2916 return IkiWiki::FailReason->new('creation_day did not match');
2920 sub match_creation_month ($$;@) {
2923 if ($m !~ /^\d+$/) {
2924 return IkiWiki::ErrorReason->new("invalid month $m");
2926 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2927 return IkiWiki::SuccessReason->new('creation_month matched');
2930 return IkiWiki::FailReason->new('creation_month did not match');
2934 sub match_creation_year ($$;@) {
2937 if ($y !~ /^\d+$/) {
2938 return IkiWiki::ErrorReason->new("invalid year $y");
2940 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2941 return IkiWiki::SuccessReason->new('creation_year matched');
2944 return IkiWiki::FailReason->new('creation_year did not match');
2948 sub match_user ($$;@) {
2953 if (! exists $params{user}) {
2954 return IkiWiki::ErrorReason->new("no user specified");
2957 my $regexp=IkiWiki::glob2re($user);
2959 if (defined $params{user} && $params{user}=~$regexp) {
2960 return IkiWiki::SuccessReason->new("user is $user");
2962 elsif (! defined $params{user}) {
2963 return IkiWiki::FailReason->new("not logged in");
2966 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2970 sub match_admin ($$;@) {
2975 if (! exists $params{user}) {
2976 return IkiWiki::ErrorReason->new("no user specified");
2979 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2980 return IkiWiki::SuccessReason->new("user is an admin");
2982 elsif (! defined $params{user}) {
2983 return IkiWiki::FailReason->new("not logged in");
2986 return IkiWiki::FailReason->new("user is not an admin");
2990 sub match_ip ($$;@) {
2995 if (! exists $params{ip}) {
2996 return IkiWiki::ErrorReason->new("no IP specified");
2999 my $regexp=IkiWiki::glob2re(lc $ip);
3001 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3002 return IkiWiki::SuccessReason->new("IP is $ip");
3005 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3009 package IkiWiki::SortSpec;
3011 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3012 # are easily available in this namespace, for cmp functions to use them.
3019 IkiWiki::pagetitle(IkiWiki::basename($a))
3021 IkiWiki::pagetitle(IkiWiki::basename($b))
3024 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3025 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3026 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }