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 directorys. Can be either a string (for backward compatibility) or a list of strings.",
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",
556 if (! ref $config{libdir}) {
557 if (length $config{libdir}) {
558 $libdirs = [$config{libdir}];
563 $libdirs = $config{libdir};
568 sub defaultconfig () {
571 foreach my $key (keys %s) {
572 push @ret, $key, $s{$key}->{default};
577 # URL to top of wiki as a path starting with /, valid from any wiki page or
578 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
580 # URL to CGI script, similar to $local_url
584 # locale stuff; avoid LC_ALL since it overrides everything
585 if (defined $ENV{LC_ALL}) {
586 $ENV{LANG} = $ENV{LC_ALL};
589 if (defined $config{locale}) {
590 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
591 $ENV{LANG}=$config{locale};
596 if (! defined $config{wiki_file_regexp}) {
597 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
600 if (ref $config{ENV} eq 'HASH') {
601 foreach my $val (keys %{$config{ENV}}) {
602 $ENV{$val}=$config{ENV}{$val};
605 if (defined $config{timezone} && length $config{timezone}) {
606 $ENV{TZ}=$config{timezone};
609 $config{timezone}=$ENV{TZ};
612 if ($config{w3mmode}) {
613 eval q{use Cwd q{abs_path}};
615 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
616 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
617 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
618 unless $config{cgiurl} =~ m!file:///!;
619 $config{url}="file://".$config{destdir};
622 if ($config{cgi} && ! length $config{url}) {
623 error(gettext("Must specify url to wiki with --url when using --cgi"));
626 if (defined $config{url} && length $config{url}) {
628 my $baseurl = URI->new($config{url});
630 $local_url = $baseurl->path . "/";
631 $local_cgiurl = undef;
633 if (length $config{cgiurl}) {
634 my $cgiurl = URI->new($config{cgiurl});
636 $local_cgiurl = $cgiurl->path;
638 if ($cgiurl->scheme eq 'https' &&
639 $baseurl->scheme eq 'http') {
640 # We assume that the same content is available
641 # over both http and https, because if it
642 # wasn't, accessing the static content
643 # from the CGI would be mixed-content,
644 # which would be a security flaw.
646 if ($cgiurl->authority ne $baseurl->authority) {
647 # use protocol-relative URL for
649 $local_url = "$config{url}/";
650 $local_url =~ s{^http://}{//};
652 # else use host-relative URL for static content
654 # either way, CGI needs to be absolute
655 $local_cgiurl = $config{cgiurl};
657 elsif ($cgiurl->scheme ne $baseurl->scheme) {
658 # too far apart, fall back to absolute URLs
659 $local_url = "$config{url}/";
660 $local_cgiurl = $config{cgiurl};
662 elsif ($cgiurl->authority ne $baseurl->authority) {
663 # slightly too far apart, fall back to
664 # protocol-relative URLs
665 $local_url = "$config{url}/";
666 $local_url =~ s{^https?://}{//};
667 $local_cgiurl = $config{cgiurl};
668 $local_cgiurl =~ s{^https?://}{//};
670 # else keep host-relative URLs
673 $local_url =~ s{//$}{/};
676 $local_cgiurl = $config{cgiurl};
679 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
680 unless exists $config{wikistatedir} && defined $config{wikistatedir};
682 if (defined $config{umask}) {
683 my $u = possibly_foolish_untaint($config{umask});
685 if ($u =~ m/^\d+$/) {
688 elsif ($u eq 'private') {
691 elsif ($u eq 'group') {
694 elsif ($u eq 'public') {
698 error(sprintf(gettext("unsupported umask setting %s"), $u));
702 run_hooks(checkconfig => sub { shift->() });
710 foreach my $dir (@INC, getlibdirs()) {
711 next unless defined $dir && length $dir;
712 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
713 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
717 foreach my $dir (getlibdirs(), "$installdir/lib/ikiwiki") {
718 next unless defined $dir && length $dir;
719 foreach my $file (glob("$dir/plugins/*")) {
720 $ret{basename($file)}=1 if -x $file;
728 if (defined $config{libdir} && length $config{libdir}) {
729 foreach my $dir (getlibdirs()) {
730 unshift @INC, possibly_foolish_untaint($dir);
734 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
739 if (exists $hooks{rcs}) {
740 error(gettext("cannot use multiple rcs plugins"));
742 loadplugin($config{rcs});
744 if (! exists $hooks{rcs}) {
748 run_hooks(getopt => sub { shift->() });
749 if (grep /^-/, @ARGV) {
750 print STDERR "Unknown option (or missing parameter): $_\n"
751 foreach grep /^-/, @ARGV;
758 sub loadplugin ($;$) {
762 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
764 foreach my $possiblytainteddir (getlibdirs(), "$installdir/lib/ikiwiki") {
765 my $dir = defined $possiblytainteddir ? possibly_foolish_untaint($possiblytainteddir) : undef;
766 if (defined $dir && -x "$dir/plugins/$plugin") {
767 eval { require IkiWiki::Plugin::external };
770 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
772 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
773 $loaded_plugins{$plugin}=1;
778 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
781 error("Failed to load plugin $mod: $@");
783 $loaded_plugins{$plugin}=1;
790 log_message('err' => $message) if $config{syslog};
791 if (defined $cleaner) {
798 return unless $config{verbose};
799 return log_message(debug => @_);
804 sub log_message ($$) {
807 if ($config{syslog}) {
810 Sys::Syslog::setlogsock('unix');
811 Sys::Syslog::openlog('ikiwiki', '', 'user');
815 # keep a copy to avoid editing the original config repeatedly
816 my $wikiname = $config{wikiname};
817 utf8::encode($wikiname);
818 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
821 print STDERR "failed to syslog: $@" unless $log_failed;
827 elsif (! $config{cgi}) {
831 return print STDERR "@_\n";
835 sub possibly_foolish_untaint ($) {
837 my ($untainted)=$tainted=~/(.*)/s;
857 return exists $pagesources{$page} &&
858 $pagesources{$page} =~ /\._([^.]+)$/;
864 if ($file =~ /\.([^.]+)$/) {
865 return $1 if exists $hooks{htmlize}{$1};
867 my $base=basename($file);
868 if (exists $hooks{htmlize}{$base} &&
869 $hooks{htmlize}{$base}{noextension}) {
880 if (exists $pagename_cache{$file}) {
881 return $pagename_cache{$file};
884 my $type=pagetype($file);
886 $page=~s/\Q.$type\E*$//
887 if defined $type && !$hooks{htmlize}{$type}{keepextension}
888 && !$hooks{htmlize}{$type}{noextension};
889 if ($config{indexpages} && $page=~/(.*)\/index$/) {
893 $pagename_cache{$file} = $page;
897 sub newpagefile ($$) {
901 if (! $config{indexpages} || $page eq 'index') {
902 return $page.".".$type;
905 return $page."/index.".$type;
909 sub targetpage ($$;$) {
914 if (defined $filename) {
915 return $page."/".$filename.".".$ext;
917 elsif (! $config{usedirs} || $page eq 'index') {
918 return $page.".".$ext;
921 return $page."/index.".$ext;
928 return targetpage($page, $config{htmlext});
935 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
936 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
937 return "$dir/$file", stat(_) if -e "$dir/$file";
939 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
944 return (srcfile_stat(@_))[0];
947 sub add_literal_underlay ($) {
950 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
951 unshift @{$config{underlaydirs}}, $dir;
955 sub add_underlay ($) {
959 $dir="$config{underlaydirbase}/$dir";
962 add_literal_underlay($dir);
963 # why does it return 1? we just don't know
967 sub readfile ($;$$) {
973 error("cannot read a symlink ($file)");
977 open (my $in, "<", $file) || error("failed to read $file: $!");
978 binmode($in) if ($binary);
979 return \*$in if $wantfd;
981 # check for invalid utf-8, and toss it back to avoid crashes
982 if (! utf8::valid($ret)) {
983 $ret=encode_utf8($ret);
985 close $in || error("failed to read $file: $!");
989 sub prep_writefile ($$) {
994 while (length $test) {
995 if (-l "$destdir/$test") {
996 error("cannot write to a symlink ($test)");
998 if (-f _ && $test ne $file) {
999 # Remove conflicting file.
1000 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1001 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1003 unlink("$destdir/$test");
1009 $test=dirname($test);
1012 my $dir=dirname("$destdir/$file");
1015 foreach my $s (split(m!/+!, $dir)) {
1018 mkdir($d) || error("failed to create directory $d: $!");
1026 sub writefile ($$$;$$) {
1027 my $file=shift; # can include subdirs
1028 my $destdir=shift; # directory to put file in
1033 prep_writefile($file, $destdir);
1035 my $newfile="$destdir/$file.ikiwiki-new";
1037 error("cannot write to a symlink ($newfile)");
1040 my $cleanup = sub { unlink($newfile) };
1041 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1042 binmode($out) if ($binary);
1044 $writer->(\*$out, $cleanup);
1047 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1049 close $out || error("failed saving $newfile: $!", $cleanup);
1050 rename($newfile, "$destdir/$file") ||
1051 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1057 sub will_render ($$;$) {
1062 # Important security check for independently created files.
1063 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1064 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1065 my $from_other_page=0;
1066 # Expensive, but rarely runs.
1067 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1070 dirname($_) eq $dest
1071 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1077 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1078 unless $from_other_page;
1081 # If $dest exists as a directory, remove conflicting files in it
1082 # rendered from other pages.
1084 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1085 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1086 if (dirname($f) eq $dest) {
1087 unlink("$config{destdir}/$f");
1088 rmdir(dirname("$config{destdir}/$f"));
1094 if (! $clear || $cleared{$page}) {
1095 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1098 foreach my $old (@{$renderedfiles{$page}}) {
1099 delete $destsources{$old};
1101 $renderedfiles{$page}=[$dest];
1104 $destsources{$dest}=$page;
1114 if ($link=~s/^\/+//) {
1122 $l.="/" if length $l;
1125 if (exists $pagesources{$l}) {
1128 elsif (exists $pagecase{lc $l}) {
1129 return $pagecase{lc $l};
1131 } while $cwd=~s{/?[^/]+$}{};
1133 if (length $config{userdir}) {
1134 my $l = "$config{userdir}/".lc($link);
1135 if (exists $pagesources{$l}) {
1138 elsif (exists $pagecase{lc $l}) {
1139 return $pagecase{lc $l};
1143 #print STDERR "warning: page $page, broken link: $link\n";
1147 sub isinlinableimage ($) {
1150 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1153 sub pagetitle ($;$) {
1155 my $unescaped=shift;
1158 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1161 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1169 # support use w/o %config set
1170 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1171 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1177 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1178 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1185 my $cgiurl=$local_cgiurl;
1187 if (exists $params{cgiurl}) {
1188 $cgiurl=$params{cgiurl};
1189 delete $params{cgiurl};
1197 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1200 sub cgiurl_abs (@) {
1202 URI->new_abs(cgiurl(@_), $config{cgiurl});
1208 return $local_url if ! defined $page;
1210 $page=htmlpage($page);
1212 $page=~s/[^\/]+\//..\//g;
1220 return $url unless defined $urlbase && length $urlbase;
1223 URI->new_abs($url, $urlbase)->as_string;
1227 # Work around very innefficient behavior in File::Spec if abs2rel
1228 # is passed two relative paths. It's much faster if paths are
1229 # absolute! (Debian bug #376658; fixed in debian unstable now)
1234 my $ret=File::Spec->abs2rel($path, $base);
1235 $ret=~s/^// if defined $ret;
1239 sub displaytime ($;$$) {
1240 # Plugins can override this function to mark up the time to
1242 my $time=formattime($_[0], $_[1]);
1243 if ($config{html5}) {
1244 return '<time datetime="'.date_3339($_[0]).'"'.
1245 ($_[2] ? ' pubdate="pubdate"' : '').
1246 '>'.$time.'</time>';
1249 return '<span class="date">'.$time.'</span>';
1253 sub formattime ($;$) {
1254 # Plugins can override this function to format the time.
1257 if (! defined $format) {
1258 $format=$config{timeformat};
1261 return strftime_utf8($format, localtime($time));
1264 my $strftime_encoding;
1266 # strftime doesn't know about encodings, so make sure
1267 # its output is properly treated as utf8.
1268 # Note that this does not handle utf-8 in the format string.
1269 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1270 unless defined $strftime_encoding;
1272 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1273 : POSIX::strftime(@_);
1279 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1280 POSIX::setlocale(&POSIX::LC_TIME, "C");
1281 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1282 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1286 sub beautify_urlpath ($) {
1289 # Ensure url is not an empty link, and if necessary,
1290 # add ./ to avoid colon confusion.
1291 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1295 if ($config{usedirs}) {
1296 $url =~ s!/index.$config{htmlext}$!/!;
1311 if (! $destsources{$to}) {
1316 return $config{url}.beautify_urlpath("/".$to);
1319 if (! defined $from) {
1320 my $u = $local_url || '';
1322 return $u.beautify_urlpath("/".$to);
1325 my $link = abs2rel($to, dirname(htmlpage($from)));
1327 return beautify_urlpath($link);
1330 sub isselflink ($$) {
1331 # Plugins can override this function to support special types
1336 return $page eq $link;
1339 sub htmllink ($$$;@) {
1340 my $lpage=shift; # the page doing the linking
1341 my $page=shift; # the page that will contain the link (different for inline)
1348 if (! $opts{forcesubpage}) {
1349 $bestlink=bestlink($lpage, $link);
1352 $bestlink="$lpage/".lc($link);
1356 if (defined $opts{linktext}) {
1357 $linktext=$opts{linktext};
1360 $linktext=pagetitle(basename($link));
1363 return "<span class=\"selflink\">$linktext</span>"
1364 if length $bestlink && isselflink($page, $bestlink) &&
1365 ! defined $opts{anchor};
1367 if (! $destsources{$bestlink}) {
1368 $bestlink=htmlpage($bestlink);
1370 if (! $destsources{$bestlink}) {
1372 if (length $config{cgiurl}) {
1373 $cgilink = "<a href=\"".
1378 )."\" rel=\"nofollow\">?</a>";
1380 return "<span class=\"createlink\">$cgilink$linktext</span>"
1384 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1385 $bestlink=beautify_urlpath($bestlink);
1387 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1388 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1391 if (defined $opts{anchor}) {
1392 $bestlink.="#".$opts{anchor};
1396 foreach my $attr (qw{rel class title}) {
1397 if (defined $opts{$attr}) {
1398 push @attrs, " $attr=\"$opts{$attr}\"";
1402 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1407 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1410 sub openiduser ($) {
1413 if (defined $user && $user =~ m!^https?://! &&
1414 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1417 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1418 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1421 # backcompat with old version
1422 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1423 $display=$oid->display;
1426 # Convert "user.somehost.com" to "user [somehost.com]"
1427 # (also "user.somehost.co.uk")
1428 if ($display !~ /\[/) {
1429 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1431 # Convert "http://somehost.com/user" to "user [somehost.com]".
1432 # (also "https://somehost.com/user/")
1433 if ($display !~ /\[/) {
1434 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1436 $display=~s!^https?://!!; # make sure this is removed
1437 eval q{use CGI 'escapeHTML'};
1439 return escapeHTML($display);
1444 sub htmlize ($$$$) {
1450 my $oneline = $content !~ /\n/;
1452 if (exists $hooks{htmlize}{$type}) {
1453 $content=$hooks{htmlize}{$type}{call}->(
1455 content => $content,
1459 error("htmlization of $type not supported");
1462 run_hooks(sanitize => sub {
1465 destpage => $destpage,
1466 content => $content,
1471 # hack to get rid of enclosing junk added by markdown
1472 # and other htmlizers/sanitizers
1473 $content=~s/^<p>//i;
1474 $content=~s/<\/p>\n*$//i;
1485 run_hooks(linkify => sub {
1488 destpage => $destpage,
1489 content => $content,
1497 our $preprocess_preview=0;
1498 sub preprocess ($$$;$$) {
1499 my $page=shift; # the page the data comes from
1500 my $destpage=shift; # the page the data will appear in (different for inline)
1505 # Using local because it needs to be set within any nested calls
1507 local $preprocess_preview=$preview if defined $preview;
1514 $params="" if ! defined $params;
1516 if (length $escape) {
1517 return "[[$prefix$command $params]]";
1519 elsif (exists $hooks{preprocess}{$command}) {
1520 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1521 # Note: preserve order of params, some plugins may
1522 # consider it significant.
1524 while ($params =~ m{
1525 (?:([-.\w]+)=)? # 1: named parameter key?
1527 """(.*?)""" # 2: triple-quoted value
1529 "([^"]*?)" # 3: single-quoted value
1531 '''(.*?)''' # 4: triple-single-quote
1533 <<([a-zA-Z]+)\n # 5: heredoc start
1534 (.*?)\n\5 # 6: heredoc value
1536 (\S+) # 7: unquoted value
1538 (?:\s+|$) # delimiter to next param
1548 elsif (defined $3) {
1551 elsif (defined $4) {
1554 elsif (defined $7) {
1557 elsif (defined $6) {
1562 push @params, $key, $val;
1565 push @params, $val, '';
1568 if ($preprocessing{$page}++ > 8) {
1569 # Avoid loops of preprocessed pages preprocessing
1570 # other pages that preprocess them, etc.
1571 return "[[!$command <span class=\"error\">".
1572 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1573 $page, $preprocessing{$page}).
1579 $hooks{preprocess}{$command}{call}->(
1582 destpage => $destpage,
1583 preview => $preprocess_preview,
1589 $ret="[[!$command <span class=\"error\">".
1590 gettext("Error").": $error"."</span>]]";
1594 # use void context during scan pass
1596 $hooks{preprocess}{$command}{call}->(
1599 destpage => $destpage,
1600 preview => $preprocess_preview,
1605 $preprocessing{$page}--;
1609 return "[[$prefix$command $params]]";
1614 if ($config{prefix_directives}) {
1617 \[\[(!) # directive open; 2: prefix
1618 ([-\w]+) # 3: command
1619 ( # 4: the parameters..
1620 \s+ # Must have space if parameters present
1622 (?:[-.\w]+=)? # named parameter key?
1624 """.*?""" # triple-quoted value
1626 "[^"]*?" # single-quoted value
1628 '''.*?''' # triple-single-quote
1630 <<([a-zA-Z]+)\n # 5: heredoc start
1631 (?:.*?)\n\5 # heredoc value
1633 [^"\s\]]+ # unquoted value
1635 \s* # whitespace or end
1638 *)? # 0 or more parameters
1639 \]\] # directive closed
1645 \[\[(!?) # directive open; 2: optional prefix
1646 ([-\w]+) # 3: command
1648 ( # 4: the parameters..
1650 (?:[-.\w]+=)? # named parameter key?
1652 """.*?""" # triple-quoted value
1654 "[^"]*?" # single-quoted value
1656 '''.*?''' # triple-single-quote
1658 <<([a-zA-Z]+)\n # 5: heredoc start
1659 (?:.*?)\n\5 # heredoc value
1661 [^"\s\]]+ # unquoted value
1663 \s* # whitespace or end
1666 *) # 0 or more parameters
1667 \]\] # directive closed
1671 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1680 run_hooks(filter => sub {
1681 $content=shift->(page => $page, destpage => $destpage,
1682 content => $content);
1688 sub check_canedit ($$$;$) {
1695 run_hooks(canedit => sub {
1696 return if defined $canedit;
1697 my $ret=shift->($page, $q, $session);
1702 elsif (ref $ret eq 'CODE') {
1703 $ret->() unless $nonfatal;
1706 elsif (defined $ret) {
1707 error($ret) unless $nonfatal;
1712 return defined $canedit ? $canedit : 1;
1715 sub check_content (@) {
1718 return 1 if ! exists $hooks{checkcontent}; # optimisation
1720 if (exists $pagesources{$params{page}}) {
1722 my %old=map { $_ => 1 }
1723 split("\n", readfile(srcfile($pagesources{$params{page}})));
1724 foreach my $line (split("\n", $params{content})) {
1725 push @diff, $line if ! exists $old{$line};
1727 $params{diff}=join("\n", @diff);
1731 run_hooks(checkcontent => sub {
1732 return if defined $ok;
1733 my $ret=shift->(%params);
1738 elsif (ref $ret eq 'CODE') {
1739 $ret->() unless $params{nonfatal};
1742 elsif (defined $ret) {
1743 error($ret) unless $params{nonfatal};
1749 return defined $ok ? $ok : 1;
1752 sub check_canchange (@) {
1754 my $cgi = $params{cgi};
1755 my $session = $params{session};
1756 my @changes = @{$params{changes}};
1759 foreach my $change (@changes) {
1760 # This untaint is safe because we check file_pruned and
1762 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1763 $file=possibly_foolish_untaint($file);
1764 if (! defined $file || ! length $file ||
1765 file_pruned($file)) {
1766 error(gettext("bad file name %s"), $file);
1769 my $type=pagetype($file);
1770 my $page=pagename($file) if defined $type;
1772 if ($change->{action} eq 'add') {
1776 if ($change->{action} eq 'change' ||
1777 $change->{action} eq 'add') {
1778 if (defined $page) {
1779 check_canedit($page, $cgi, $session);
1783 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1784 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1785 check_canedit($file, $cgi, $session);
1790 elsif ($change->{action} eq 'remove') {
1791 # check_canremove tests to see if the file is present
1792 # on disk. This will fail when a single commit adds a
1793 # file and then removes it again. Avoid the problem
1794 # by not testing the removal in such pairs of changes.
1795 # (The add is still tested, just to make sure that
1796 # no data is added to the repo that a web edit
1798 next if $newfiles{$file};
1800 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1801 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1802 check_canedit(defined $page ? $page : $file, $cgi, $session);
1807 error "unknown action ".$change->{action};
1810 error sprintf(gettext("you are not allowed to change %s"), $file);
1818 # Take an exclusive lock on the wiki to prevent multiple concurrent
1819 # run issues. The lock will be dropped on program exit.
1820 if (! -d $config{wikistatedir}) {
1821 mkdir($config{wikistatedir});
1823 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1824 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1825 if (! flock($wikilock, 2)) { # LOCK_EX
1826 error("failed to get lock");
1832 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1833 return close($wikilock) if $wikilock;
1839 sub commit_hook_enabled () {
1840 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1841 error("cannot write to $config{wikistatedir}/commitlock: $!");
1842 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1843 close($commitlock) || error("failed closing commitlock: $!");
1846 close($commitlock) || error("failed closing commitlock: $!");
1850 sub disable_commit_hook () {
1851 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1852 error("cannot write to $config{wikistatedir}/commitlock: $!");
1853 if (! flock($commitlock, 2)) { # LOCK_EX
1854 error("failed to get commit lock");
1859 sub enable_commit_hook () {
1860 return close($commitlock) if $commitlock;
1865 %oldrenderedfiles=%pagectime=();
1866 my $rebuild=$config{rebuild};
1868 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1869 %destsources=%renderedfiles=%pagecase=%pagestate=
1870 %depends_simple=%typedlinks=%oldtypedlinks=();
1873 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1874 if (-e "$config{wikistatedir}/index") {
1875 system("ikiwiki-transition", "indexdb", $config{srcdir});
1876 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1879 # gettime on first build
1880 $config{gettime}=1 unless defined $config{gettime};
1885 my $index=Storable::fd_retrieve($in);
1886 if (! defined $index) {
1891 if (exists $index->{version} && ! ref $index->{version}) {
1892 $pages=$index->{page};
1893 %wikistate=%{$index->{state}};
1894 # Handle plugins that got disabled by loading a new setup.
1895 if (exists $config{setupfile}) {
1896 require IkiWiki::Setup;
1897 IkiWiki::Setup::disabled_plugins(
1898 grep { ! $loaded_plugins{$_} } keys %wikistate);
1906 foreach my $src (keys %$pages) {
1907 my $d=$pages->{$src};
1909 if (exists $d->{page} && ! $rebuild) {
1913 $page=pagename($src);
1915 $pagectime{$page}=$d->{ctime};
1916 $pagesources{$page}=$src;
1918 $pagemtime{$page}=$d->{mtime};
1919 $renderedfiles{$page}=$d->{dest};
1920 if (exists $d->{links} && ref $d->{links}) {
1921 $links{$page}=$d->{links};
1922 $oldlinks{$page}=[@{$d->{links}}];
1924 if (ref $d->{depends_simple} eq 'ARRAY') {
1926 $depends_simple{$page}={
1927 map { $_ => 1 } @{$d->{depends_simple}}
1930 elsif (exists $d->{depends_simple}) {
1931 $depends_simple{$page}=$d->{depends_simple};
1933 if (exists $d->{dependslist}) {
1936 map { $_ => $DEPEND_CONTENT }
1937 @{$d->{dependslist}}
1940 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1942 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1944 elsif (exists $d->{depends}) {
1945 $depends{$page}=$d->{depends};
1947 if (exists $d->{state}) {
1948 $pagestate{$page}=$d->{state};
1950 if (exists $d->{typedlinks}) {
1951 $typedlinks{$page}=$d->{typedlinks};
1953 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1954 next unless %$links;
1955 $oldtypedlinks{$page}{$type} = {%$links};
1959 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1961 foreach my $page (keys %pagesources) {
1962 $pagecase{lc $page}=$page;
1964 foreach my $page (keys %renderedfiles) {
1965 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1967 $lastrev=$index->{lastrev};
1968 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1973 run_hooks(savestate => sub { shift->() });
1975 my @plugins=keys %loaded_plugins;
1977 if (! -d $config{wikistatedir}) {
1978 mkdir($config{wikistatedir});
1980 my $newfile="$config{wikistatedir}/indexdb.new";
1981 my $cleanup = sub { unlink($newfile) };
1982 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1985 foreach my $page (keys %pagemtime) {
1986 next unless $pagemtime{$page};
1987 my $src=$pagesources{$page};
1989 $index{page}{$src}={
1991 ctime => $pagectime{$page},
1992 mtime => $pagemtime{$page},
1993 dest => $renderedfiles{$page},
1994 links => $links{$page},
1997 if (exists $depends{$page}) {
1998 $index{page}{$src}{depends} = $depends{$page};
2001 if (exists $depends_simple{$page}) {
2002 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2005 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2006 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2009 if (exists $pagestate{$page}) {
2010 $index{page}{$src}{state}=$pagestate{$page};
2015 foreach my $id (@plugins) {
2016 $index{state}{$id}={}; # used to detect disabled plugins
2017 foreach my $key (keys %{$wikistate{$id}}) {
2018 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2022 $index{lastrev}=$lastrev;
2023 $index{underlayfiles}=\@underlayfiles;
2025 $index{version}="3";
2026 my $ret=Storable::nstore_fd(\%index, $out);
2027 return if ! defined $ret || ! $ret;
2028 close $out || error("failed saving to $newfile: $!", $cleanup);
2029 rename($newfile, "$config{wikistatedir}/indexdb") ||
2030 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2035 sub template_file ($) {
2038 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2040 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2041 $template=srcfile($pagesources{$tpage}, 1);
2045 $template=srcfile($tpage, 1);
2048 if (defined $template) {
2049 return $template, $tpage, 1 if wantarray;
2053 $name=~s:/::; # avoid path traversal
2054 foreach my $dir ($config{templatedir},
2055 "$installdir/share/ikiwiki/templates") {
2056 if (-e "$dir/$name") {
2057 $template="$dir/$name";
2061 if (defined $template) {
2062 return $template, $tpage if wantarray;
2070 sub template_depends ($$;@) {
2074 my ($filename, $tpage, $untrusted)=template_file($name);
2075 if (! defined $filename) {
2076 error(sprintf(gettext("template %s not found"), $name))
2079 if (defined $page && defined $tpage) {
2080 add_depends($page, $tpage);
2085 my $text_ref = shift;
2086 ${$text_ref} = decode_utf8(${$text_ref});
2087 run_hooks(readtemplate => sub {
2088 ${$text_ref} = shift->(
2091 content => ${$text_ref},
2092 untrusted => $untrusted,
2096 loop_context_vars => 1,
2097 die_on_bad_params => 0,
2098 parent_global_vars => 1,
2099 filename => $filename,
2101 ($untrusted ? (no_includes => 1) : ()),
2103 return @opts if wantarray;
2105 require HTML::Template;
2106 return HTML::Template->new(@opts);
2109 sub template ($;@) {
2110 template_depends(shift, undef, @_);
2113 sub templateactions ($$) {
2119 run_hooks(pageactions => sub {
2120 push @actions, map { { action => $_ } }
2121 grep { defined } shift->(page => $page);
2123 $template->param(actions => \@actions);
2125 if ($config{cgiurl} && exists $hooks{auth}) {
2126 $template->param(prefsurl => cgiurl(do => "prefs"));
2130 if ($have_actions || @actions) {
2131 $template->param(have_actions => 1);
2138 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2139 error 'hook requires type, call, and id parameters';
2142 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2144 $hooks{$param{type}}{$param{id}}=\%param;
2148 sub run_hooks ($$) {
2149 # Calls the given sub for each hook of the given type,
2150 # passing it the hook function to call.
2154 if (exists $hooks{$type}) {
2155 my (@first, @middle, @last);
2156 foreach my $id (keys %{$hooks{$type}}) {
2157 if ($hooks{$type}{$id}{first}) {
2160 elsif ($hooks{$type}{$id}{last}) {
2167 foreach my $id (@first, @middle, @last) {
2168 $sub->($hooks{$type}{$id}{call});
2176 $hooks{rcs}{rcs_update}{call}->(@_);
2179 sub rcs_prepedit ($) {
2180 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2183 sub rcs_commit (@) {
2184 $hooks{rcs}{rcs_commit}{call}->(@_);
2187 sub rcs_commit_staged (@) {
2188 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2192 $hooks{rcs}{rcs_add}{call}->(@_);
2195 sub rcs_remove ($) {
2196 $hooks{rcs}{rcs_remove}{call}->(@_);
2199 sub rcs_rename ($$) {
2200 $hooks{rcs}{rcs_rename}{call}->(@_);
2203 sub rcs_recentchanges ($) {
2204 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2207 sub rcs_diff ($;$) {
2208 $hooks{rcs}{rcs_diff}{call}->(@_);
2211 sub rcs_getctime ($) {
2212 $hooks{rcs}{rcs_getctime}{call}->(@_);
2215 sub rcs_getmtime ($) {
2216 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2219 sub rcs_receive () {
2220 $hooks{rcs}{rcs_receive}{call}->();
2223 sub add_depends ($$;$) {
2226 my $deptype=shift || $DEPEND_CONTENT;
2228 # Is the pagespec a simple page name?
2229 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2230 $pagespec !~ /[\s*?()!]/) {
2231 $depends_simple{$page}{lc $pagespec} |= $deptype;
2235 # Add explicit dependencies for influences.
2236 my $sub=pagespec_translate($pagespec);
2237 return unless defined $sub;
2238 foreach my $p (keys %pagesources) {
2239 my $r=$sub->($p, location => $page);
2240 my $i=$r->influences;
2241 my $static=$r->influences_static;
2242 foreach my $k (keys %$i) {
2243 next unless $r || $static || $k eq $page;
2244 $depends_simple{$page}{lc $k} |= $i->{$k};
2249 $depends{$page}{$pagespec} |= $deptype;
2255 foreach my $type (@_) {
2256 if ($type eq 'presence') {
2257 $deptype |= $DEPEND_PRESENCE;
2259 elsif ($type eq 'links') {
2260 $deptype |= $DEPEND_LINKS;
2262 elsif ($type eq 'content') {
2263 $deptype |= $DEPEND_CONTENT;
2269 my $file_prune_regexp;
2270 sub file_pruned ($) {
2273 if (defined $config{include} && length $config{include}) {
2274 return 0 if $file =~ m/$config{include}/;
2277 if (! defined $file_prune_regexp) {
2278 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2279 $file_prune_regexp=qr/$file_prune_regexp/;
2281 return $file =~ m/$file_prune_regexp/;
2284 sub define_gettext () {
2285 # If translation is needed, redefine the gettext function to do it.
2286 # Otherwise, it becomes a quick no-op.
2289 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2290 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2291 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2293 $gettext_obj=eval q{
2294 use Locale::gettext q{textdomain};
2295 Locale::gettext->domain('ikiwiki')
2300 no warnings 'redefine';
2302 $getobj->() if $getobj;
2304 $gettext_obj->get(shift);
2311 $getobj->() if $getobj;
2313 $gettext_obj->nget(@_);
2316 return ($_[2] == 1 ? $_[0] : $_[1])
2334 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2338 # Injects a new function into the symbol table to replace an
2339 # exported function.
2342 # This is deep ugly perl foo, beware.
2345 if (! defined $params{parent}) {
2346 $params{parent}='::';
2347 $params{old}=\&{$params{name}};
2348 $params{name}=~s/.*:://;
2350 my $parent=$params{parent};
2351 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2352 $ns = $params{parent} . $ns;
2353 inject(%params, parent => $ns) unless $ns eq '::main::';
2354 *{$ns . $params{name}} = $params{call}
2355 if exists ${$ns}{$params{name}} &&
2356 \&{${$ns}{$params{name}}} == $params{old};
2362 sub add_link ($$;$) {
2367 push @{$links{$page}}, $link
2368 unless grep { $_ eq $link } @{$links{$page}};
2370 if (defined $type) {
2371 $typedlinks{$page}{$type}{$link} = 1;
2375 sub add_autofile ($$$) {
2378 my $generator=shift;
2380 $autofiles{$file}{plugin}=$plugin;
2381 $autofiles{$file}{generator}=$generator;
2385 return LWP::UserAgent->new(
2386 cookie_jar => $config{cookiejar},
2387 env_proxy => 1, # respect proxy env vars
2388 agent => $config{useragent},
2392 sub sortspec_translate ($$) {
2394 my $reverse = shift;
2400 (-?) # group 1: perhaps negated
2403 \w+\([^\)]*\) # command(params)
2405 [^\s]+ # or anything else
2413 if ($word =~ m/^(\w+)\((.*)\)$/) {
2414 # command with parameters
2418 elsif ($word !~ m/^\w+$/) {
2419 error(sprintf(gettext("invalid sort type %s"), $word));
2430 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2431 if (defined $params) {
2432 push @data, $params;
2433 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2436 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2440 error(sprintf(gettext("unknown sort type %s"), $word));
2444 if (! length $code) {
2445 # undefined sorting method... sort arbitrarily
2454 return eval 'sub { '.$code.' }';
2457 sub pagespec_translate ($) {
2460 # Convert spec to perl code.
2464 \s* # ignore whitespace
2465 ( # 1: match a single word
2472 \w+\([^\)]*\) # command(params)
2474 [^\s()]+ # any other text
2476 \s* # ignore whitespace
2479 if (lc $word eq 'and') {
2482 elsif (lc $word eq 'or') {
2485 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2488 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2489 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2491 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2494 push @data, qq{unknown function in pagespec "$word"};
2495 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2500 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2504 if (! length $code) {
2505 $code="IkiWiki::FailReason->new('empty pagespec')";
2509 return eval 'sub { my $page=shift; '.$code.' }';
2512 sub pagespec_match ($$;@) {
2517 # Backwards compatability with old calling convention.
2519 unshift @params, 'location';
2522 my $sub=pagespec_translate($spec);
2523 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2525 return $sub->($page, @params);
2528 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2530 # Not exported yet, but could be in future if it is generally useful.
2531 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2532 # which is "more internal".
2533 sub sort_pages ($$;@) {
2537 $sort = sortspec_translate($sort, $params{reverse});
2538 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2541 sub pagespec_match_list ($$;@) {
2546 # Backwards compatability with old calling convention.
2548 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2549 $params{list}=$page;
2550 $page=$params{location}; # ugh!
2553 my $sub=pagespec_translate($pagespec);
2554 error "syntax error in pagespec \"$pagespec\""
2556 my $sort=sortspec_translate($params{sort}, $params{reverse})
2557 if defined $params{sort};
2560 if (exists $params{list}) {
2561 @candidates=exists $params{filter}
2562 ? grep { ! $params{filter}->($_) } @{$params{list}}
2566 @candidates=exists $params{filter}
2567 ? grep { ! $params{filter}->($_) } keys %pagesources
2568 : keys %pagesources;
2571 # clear params, remainder is passed to pagespec
2572 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2573 my $num=$params{num};
2574 delete @params{qw{num deptype reverse sort filter list}};
2576 # when only the top matches will be returned, it's efficient to
2577 # sort before matching to pagespec,
2578 if (defined $num && defined $sort) {
2579 @candidates=IkiWiki::SortSpec::sort_pages(
2580 $sort, @candidates);
2586 my $accum=IkiWiki::SuccessReason->new();
2587 foreach my $p (@candidates) {
2588 my $r=$sub->($p, %params, location => $page);
2589 error(sprintf(gettext("cannot match pages: %s"), $r))
2590 if $r->isa("IkiWiki::ErrorReason");
2591 unless ($r || $r->influences_static) {
2592 $r->remove_influence($p);
2597 last if defined $num && ++$count == $num;
2601 # Add simple dependencies for accumulated influences.
2602 my $i=$accum->influences;
2603 foreach my $k (keys %$i) {
2604 $depends_simple{$page}{lc $k} |= $i->{$k};
2607 # when all matches will be returned, it's efficient to
2608 # sort after matching
2609 if (! defined $num && defined $sort) {
2610 return IkiWiki::SortSpec::sort_pages(
2618 sub pagespec_valid ($) {
2621 return defined pagespec_translate($spec);
2625 my $re=quotemeta(shift);
2631 package IkiWiki::FailReason;
2634 '""' => sub { $_[0][0] },
2636 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2637 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2638 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2642 our @ISA = 'IkiWiki::SuccessReason';
2644 package IkiWiki::SuccessReason;
2646 # A blessed array-ref:
2648 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2650 # - if absent or false, the influences of this evaluation are "static",
2651 # see the influences_static method
2652 # - if true, they are dynamic (not static)
2653 # [1]{any other key}:
2654 # the dependency types of influences, as returned by the influences method
2657 # in string context, it's the human-readable reason
2658 '""' => sub { $_[0][0] },
2659 # in boolean context, SuccessReason is 1 and FailReason is 0
2661 # negating a result gives the opposite result with the same influences
2662 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2663 # A & B = (A ? B : A) with the influences of both
2664 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2665 # A | B = (A ? A : B) with the influences of both
2666 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2670 # SuccessReason->new("human-readable reason", page => deptype, ...)
2675 return bless [$value, {@_}], $class;
2678 # influences(): return a reference to a copy of the hash
2679 # { page => dependency type } describing the pages that indirectly influenced
2680 # this result, but would not cause a dependency through ikiwiki's core
2683 # See [[todo/dependency_types]] for extensive discussion of what this means.
2685 # influences(page => deptype, ...): remove all influences, replace them
2686 # with the arguments, and return a reference to a copy of the new influences.
2690 $this->[1]={@_} if @_;
2691 my %i=%{$this->[1]};
2696 # True if this result has the same influences whichever page it matches,
2697 # For instance, whether bar matches backlink(foo) is influenced only by
2698 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2699 # which does not mention bar anywhere.
2701 # False if this result would have different influences when matching
2702 # different pages. For instance, when testing whether link(foo) matches bar,
2703 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2704 # bar's links could change the outcome; so its influences are not the same
2705 # as when testing whether link(foo) matches baz.
2707 # Static influences are one of the things that make pagespec_match_list
2708 # more efficient than repeated calls to pagespec_match.
2710 sub influences_static {
2711 return ! $_[0][1]->{""};
2714 # Change the influences of $this to be the influences of "$this & $other"
2715 # or "$this | $other".
2717 # If both $this and $other are either successful or have influences,
2718 # or this is an "or" operation, the result has all the influences from
2719 # either of the arguments. It has dynamic influences if either argument
2720 # has dynamic influences.
2722 # If this is an "and" operation, and at least one argument is a
2723 # FailReason with no influences, the result has no influences, and they
2724 # are not dynamic. For instance, link(foo) matching bar is influenced
2725 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2726 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2727 # bar, because it would be false however often you edit bar.
2729 sub merge_influences {
2734 # This "if" is odd because it needs to avoid negating $this
2735 # or $other, which would alter the objects in-place. Be careful.
2736 if (! $anded || (($this || %{$this->[1]}) &&
2737 ($other || %{$other->[1]}))) {
2738 foreach my $influence (keys %{$other->[1]}) {
2739 $this->[1]{$influence} |= $other->[1]{$influence};
2748 # Change $this so it is not considered to be influenced by $torm.
2750 sub remove_influence {
2754 delete $this->[1]{$torm};
2757 package IkiWiki::ErrorReason;
2759 our @ISA = 'IkiWiki::FailReason';
2761 package IkiWiki::PageSpec;
2767 if ($path =~ m!^\.(/|$)!) {
2769 $from=~s#/?[^/]+$## if defined $from;
2771 $path="$from/$path" if defined $from && length $from;
2775 $path = "" unless defined $path;
2784 sub match_glob ($$;@) {
2789 $glob=derel($glob, $params{location});
2791 # Instead of converting the glob to a regex every time,
2792 # cache the compiled regex to save time.
2793 my $re=$glob_cache{$glob};
2794 unless (defined $re) {
2795 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2798 if (! IkiWiki::isinternal($page) || $params{internal}) {
2799 return IkiWiki::SuccessReason->new("$glob matches $page");
2802 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2806 return IkiWiki::FailReason->new("$glob does not match $page");
2810 sub match_internal ($$;@) {
2811 return match_glob(shift, shift, @_, internal => 1)
2814 sub match_page ($$;@) {
2816 my $match=match_glob($page, shift, @_);
2818 my $source=exists $IkiWiki::pagesources{$page} ?
2819 $IkiWiki::pagesources{$page} :
2820 $IkiWiki::delpagesources{$page};
2821 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2822 if (! defined $type) {
2823 return IkiWiki::FailReason->new("$page is not a page");
2829 sub match_link ($$;@) {
2834 $link=derel($link, $params{location});
2835 my $from=exists $params{location} ? $params{location} : '';
2836 my $linktype=$params{linktype};
2838 if (defined $linktype) {
2839 $qualifier=" with type $linktype";
2842 my $links = $IkiWiki::links{$page};
2843 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2844 unless $links && @{$links};
2845 my $bestlink = IkiWiki::bestlink($from, $link);
2846 foreach my $p (@{$links}) {
2847 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2849 if (length $bestlink) {
2850 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2851 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2855 if (match_glob($p, $link, %params)) {
2856 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2858 my ($p_rel)=$p=~/^\/?(.*)/;
2860 if (match_glob($p_rel, $link, %params)) {
2861 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2865 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2868 sub match_backlink ($$;@) {
2872 if ($testpage eq '.') {
2873 $testpage = $params{'location'}
2875 my $ret=match_link($testpage, $page, @_);
2876 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2880 sub match_created_before ($$;@) {
2885 $testpage=derel($testpage, $params{location});
2887 if (exists $IkiWiki::pagectime{$testpage}) {
2888 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2889 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2892 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2896 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2900 sub match_created_after ($$;@) {
2905 $testpage=derel($testpage, $params{location});
2907 if (exists $IkiWiki::pagectime{$testpage}) {
2908 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2909 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2912 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2916 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2920 sub match_creation_day ($$;@) {
2923 if ($d !~ /^\d+$/) {
2924 return IkiWiki::ErrorReason->new("invalid day $d");
2926 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2927 return IkiWiki::SuccessReason->new('creation_day matched');
2930 return IkiWiki::FailReason->new('creation_day did not match');
2934 sub match_creation_month ($$;@) {
2937 if ($m !~ /^\d+$/) {
2938 return IkiWiki::ErrorReason->new("invalid month $m");
2940 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2941 return IkiWiki::SuccessReason->new('creation_month matched');
2944 return IkiWiki::FailReason->new('creation_month did not match');
2948 sub match_creation_year ($$;@) {
2951 if ($y !~ /^\d+$/) {
2952 return IkiWiki::ErrorReason->new("invalid year $y");
2954 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2955 return IkiWiki::SuccessReason->new('creation_year matched');
2958 return IkiWiki::FailReason->new('creation_year did not match');
2962 sub match_user ($$;@) {
2967 if (! exists $params{user}) {
2968 return IkiWiki::ErrorReason->new("no user specified");
2971 my $regexp=IkiWiki::glob2re($user);
2973 if (defined $params{user} && $params{user}=~$regexp) {
2974 return IkiWiki::SuccessReason->new("user is $user");
2976 elsif (! defined $params{user}) {
2977 return IkiWiki::FailReason->new("not logged in");
2980 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2984 sub match_admin ($$;@) {
2989 if (! exists $params{user}) {
2990 return IkiWiki::ErrorReason->new("no user specified");
2993 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2994 return IkiWiki::SuccessReason->new("user is an admin");
2996 elsif (! defined $params{user}) {
2997 return IkiWiki::FailReason->new("not logged in");
3000 return IkiWiki::FailReason->new("user is not an admin");
3004 sub match_ip ($$;@) {
3009 if (! exists $params{ip}) {
3010 return IkiWiki::ErrorReason->new("no IP specified");
3013 my $regexp=IkiWiki::glob2re(lc $ip);
3015 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3016 return IkiWiki::SuccessReason->new("IP is $ip");
3019 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3023 package IkiWiki::SortSpec;
3025 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3026 # are easily available in this namespace, for cmp functions to use them.
3033 IkiWiki::pagetitle(IkiWiki::basename($a))
3035 IkiWiki::pagetitle(IkiWiki::basename($b))
3038 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3039 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3040 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }