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",
555 if (! ref $config{libdir}) {
556 if (length $config{libdir}) {
557 return [$config{libdir}];
562 return $config{libdir};
565 sub defaultconfig () {
568 foreach my $key (keys %s) {
569 push @ret, $key, $s{$key}->{default};
574 # URL to top of wiki as a path starting with /, valid from any wiki page or
575 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
577 # URL to CGI script, similar to $local_url
581 # locale stuff; avoid LC_ALL since it overrides everything
582 if (defined $ENV{LC_ALL}) {
583 $ENV{LANG} = $ENV{LC_ALL};
586 if (defined $config{locale}) {
587 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
588 $ENV{LANG}=$config{locale};
593 if (! defined $config{wiki_file_regexp}) {
594 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
597 if (ref $config{ENV} eq 'HASH') {
598 foreach my $val (keys %{$config{ENV}}) {
599 $ENV{$val}=$config{ENV}{$val};
602 if (defined $config{timezone} && length $config{timezone}) {
603 $ENV{TZ}=$config{timezone};
606 $config{timezone}=$ENV{TZ};
609 if ($config{w3mmode}) {
610 eval q{use Cwd q{abs_path}};
612 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
613 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
614 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
615 unless $config{cgiurl} =~ m!file:///!;
616 $config{url}="file://".$config{destdir};
619 if ($config{cgi} && ! length $config{url}) {
620 error(gettext("Must specify url to wiki with --url when using --cgi"));
623 if (defined $config{url} && length $config{url}) {
625 my $baseurl = URI->new($config{url});
627 $local_url = $baseurl->path . "/";
628 $local_cgiurl = undef;
630 if (length $config{cgiurl}) {
631 my $cgiurl = URI->new($config{cgiurl});
633 $local_cgiurl = $cgiurl->path;
635 if ($cgiurl->scheme eq 'https' &&
636 $baseurl->scheme eq 'http') {
637 # We assume that the same content is available
638 # over both http and https, because if it
639 # wasn't, accessing the static content
640 # from the CGI would be mixed-content,
641 # which would be a security flaw.
643 if ($cgiurl->authority ne $baseurl->authority) {
644 # use protocol-relative URL for
646 $local_url = "$config{url}/";
647 $local_url =~ s{^http://}{//};
649 # else use host-relative URL for static content
651 # either way, CGI needs to be absolute
652 $local_cgiurl = $config{cgiurl};
654 elsif ($cgiurl->scheme ne $baseurl->scheme) {
655 # too far apart, fall back to absolute URLs
656 $local_url = "$config{url}/";
657 $local_cgiurl = $config{cgiurl};
659 elsif ($cgiurl->authority ne $baseurl->authority) {
660 # slightly too far apart, fall back to
661 # protocol-relative URLs
662 $local_url = "$config{url}/";
663 $local_url =~ s{^https?://}{//};
664 $local_cgiurl = $config{cgiurl};
665 $local_cgiurl =~ s{^https?://}{//};
667 # else keep host-relative URLs
670 $local_url =~ s{//$}{/};
673 $local_cgiurl = $config{cgiurl};
676 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
677 unless exists $config{wikistatedir} && defined $config{wikistatedir};
679 if (defined $config{umask}) {
680 my $u = possibly_foolish_untaint($config{umask});
682 if ($u =~ m/^\d+$/) {
685 elsif ($u eq 'private') {
688 elsif ($u eq 'group') {
691 elsif ($u eq 'public') {
695 error(sprintf(gettext("unsupported umask setting %s"), $u));
699 run_hooks(checkconfig => sub { shift->() });
707 foreach my $dir (@INC, @{getlibdirs()}) {
708 next unless defined $dir && length $dir;
709 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
710 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
714 foreach my $dir (@{getlibdirs()}, "$installdir/lib/ikiwiki") {
715 next unless defined $dir && length $dir;
716 foreach my $file (glob("$dir/plugins/*")) {
717 $ret{basename($file)}=1 if -x $file;
725 if (defined $config{libdir} && length $config{libdir}) {
726 foreach my $dir (@{getlibdirs()}) {
727 unshift @INC, possibly_foolish_untaint($dir);
731 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
736 if (exists $hooks{rcs}) {
737 error(gettext("cannot use multiple rcs plugins"));
739 loadplugin($config{rcs});
741 if (! exists $hooks{rcs}) {
745 run_hooks(getopt => sub { shift->() });
746 if (grep /^-/, @ARGV) {
747 print STDERR "Unknown option (or missing parameter): $_\n"
748 foreach grep /^-/, @ARGV;
755 sub loadplugin ($;$) {
759 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
761 foreach my $possiblytainteddir (@{getlibdirs()}, "$installdir/lib/ikiwiki") {
762 my $dir = defined $possiblytainteddir ? possibly_foolish_untaint($possiblytainteddir) : undef;
763 if (defined $dir && -x "$dir/plugins/$plugin") {
764 eval { require IkiWiki::Plugin::external };
767 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
769 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
770 $loaded_plugins{$plugin}=1;
775 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
778 error("Failed to load plugin $mod: $@");
780 $loaded_plugins{$plugin}=1;
787 log_message('err' => $message) if $config{syslog};
788 if (defined $cleaner) {
795 return unless $config{verbose};
796 return log_message(debug => @_);
801 sub log_message ($$) {
804 if ($config{syslog}) {
807 Sys::Syslog::setlogsock('unix');
808 Sys::Syslog::openlog('ikiwiki', '', 'user');
812 # keep a copy to avoid editing the original config repeatedly
813 my $wikiname = $config{wikiname};
814 utf8::encode($wikiname);
815 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
818 print STDERR "failed to syslog: $@" unless $log_failed;
824 elsif (! $config{cgi}) {
828 return print STDERR "@_\n";
832 sub possibly_foolish_untaint ($) {
834 my ($untainted)=$tainted=~/(.*)/s;
854 return exists $pagesources{$page} &&
855 $pagesources{$page} =~ /\._([^.]+)$/;
861 if ($file =~ /\.([^.]+)$/) {
862 return $1 if exists $hooks{htmlize}{$1};
864 my $base=basename($file);
865 if (exists $hooks{htmlize}{$base} &&
866 $hooks{htmlize}{$base}{noextension}) {
877 if (exists $pagename_cache{$file}) {
878 return $pagename_cache{$file};
881 my $type=pagetype($file);
883 $page=~s/\Q.$type\E*$//
884 if defined $type && !$hooks{htmlize}{$type}{keepextension}
885 && !$hooks{htmlize}{$type}{noextension};
886 if ($config{indexpages} && $page=~/(.*)\/index$/) {
890 $pagename_cache{$file} = $page;
894 sub newpagefile ($$) {
898 if (! $config{indexpages} || $page eq 'index') {
899 return $page.".".$type;
902 return $page."/index.".$type;
906 sub targetpage ($$;$) {
911 if (defined $filename) {
912 return $page."/".$filename.".".$ext;
914 elsif (! $config{usedirs} || $page eq 'index') {
915 return $page.".".$ext;
918 return $page."/index.".$ext;
925 return targetpage($page, $config{htmlext});
932 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
933 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
934 return "$dir/$file", stat(_) if -e "$dir/$file";
936 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
941 return (srcfile_stat(@_))[0];
944 sub add_literal_underlay ($) {
947 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
948 unshift @{$config{underlaydirs}}, $dir;
952 sub add_underlay ($) {
956 $dir="$config{underlaydirbase}/$dir";
959 add_literal_underlay($dir);
960 # why does it return 1? we just don't know
964 sub readfile ($;$$) {
970 error("cannot read a symlink ($file)");
974 open (my $in, "<", $file) || error("failed to read $file: $!");
975 binmode($in) if ($binary);
976 return \*$in if $wantfd;
978 # check for invalid utf-8, and toss it back to avoid crashes
979 if (! utf8::valid($ret)) {
980 $ret=encode_utf8($ret);
982 close $in || error("failed to read $file: $!");
986 sub prep_writefile ($$) {
991 while (length $test) {
992 if (-l "$destdir/$test") {
993 error("cannot write to a symlink ($test)");
995 if (-f _ && $test ne $file) {
996 # Remove conflicting file.
997 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
998 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1000 unlink("$destdir/$test");
1006 $test=dirname($test);
1009 my $dir=dirname("$destdir/$file");
1012 foreach my $s (split(m!/+!, $dir)) {
1015 mkdir($d) || error("failed to create directory $d: $!");
1023 sub writefile ($$$;$$) {
1024 my $file=shift; # can include subdirs
1025 my $destdir=shift; # directory to put file in
1030 prep_writefile($file, $destdir);
1032 my $newfile="$destdir/$file.ikiwiki-new";
1034 error("cannot write to a symlink ($newfile)");
1037 my $cleanup = sub { unlink($newfile) };
1038 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1039 binmode($out) if ($binary);
1041 $writer->(\*$out, $cleanup);
1044 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1046 close $out || error("failed saving $newfile: $!", $cleanup);
1047 rename($newfile, "$destdir/$file") ||
1048 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1054 sub will_render ($$;$) {
1059 # Important security check for independently created files.
1060 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1061 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1062 my $from_other_page=0;
1063 # Expensive, but rarely runs.
1064 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1067 dirname($_) eq $dest
1068 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1074 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1075 unless $from_other_page;
1078 # If $dest exists as a directory, remove conflicting files in it
1079 # rendered from other pages.
1081 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1082 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1083 if (dirname($f) eq $dest) {
1084 unlink("$config{destdir}/$f");
1085 rmdir(dirname("$config{destdir}/$f"));
1091 if (! $clear || $cleared{$page}) {
1092 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1095 foreach my $old (@{$renderedfiles{$page}}) {
1096 delete $destsources{$old};
1098 $renderedfiles{$page}=[$dest];
1101 $destsources{$dest}=$page;
1111 if ($link=~s/^\/+//) {
1119 $l.="/" if length $l;
1122 if (exists $pagesources{$l}) {
1125 elsif (exists $pagecase{lc $l}) {
1126 return $pagecase{lc $l};
1128 } while $cwd=~s{/?[^/]+$}{};
1130 if (length $config{userdir}) {
1131 my $l = "$config{userdir}/".lc($link);
1132 if (exists $pagesources{$l}) {
1135 elsif (exists $pagecase{lc $l}) {
1136 return $pagecase{lc $l};
1140 #print STDERR "warning: page $page, broken link: $link\n";
1144 sub isinlinableimage ($) {
1147 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1150 sub pagetitle ($;$) {
1152 my $unescaped=shift;
1155 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1158 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1166 # support use w/o %config set
1167 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1168 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1174 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1175 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1182 my $cgiurl=$local_cgiurl;
1184 if (exists $params{cgiurl}) {
1185 $cgiurl=$params{cgiurl};
1186 delete $params{cgiurl};
1194 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1197 sub cgiurl_abs (@) {
1199 URI->new_abs(cgiurl(@_), $config{cgiurl});
1205 return $local_url if ! defined $page;
1207 $page=htmlpage($page);
1209 $page=~s/[^\/]+\//..\//g;
1217 return $url unless defined $urlbase && length $urlbase;
1220 URI->new_abs($url, $urlbase)->as_string;
1224 # Work around very innefficient behavior in File::Spec if abs2rel
1225 # is passed two relative paths. It's much faster if paths are
1226 # absolute! (Debian bug #376658; fixed in debian unstable now)
1231 my $ret=File::Spec->abs2rel($path, $base);
1232 $ret=~s/^// if defined $ret;
1236 sub displaytime ($;$$) {
1237 # Plugins can override this function to mark up the time to
1239 my $time=formattime($_[0], $_[1]);
1240 if ($config{html5}) {
1241 return '<time datetime="'.date_3339($_[0]).'"'.
1242 ($_[2] ? ' pubdate="pubdate"' : '').
1243 '>'.$time.'</time>';
1246 return '<span class="date">'.$time.'</span>';
1250 sub formattime ($;$) {
1251 # Plugins can override this function to format the time.
1254 if (! defined $format) {
1255 $format=$config{timeformat};
1258 return strftime_utf8($format, localtime($time));
1261 my $strftime_encoding;
1263 # strftime doesn't know about encodings, so make sure
1264 # its output is properly treated as utf8.
1265 # Note that this does not handle utf-8 in the format string.
1266 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1267 unless defined $strftime_encoding;
1269 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1270 : POSIX::strftime(@_);
1276 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1277 POSIX::setlocale(&POSIX::LC_TIME, "C");
1278 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1279 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1283 sub beautify_urlpath ($) {
1286 # Ensure url is not an empty link, and if necessary,
1287 # add ./ to avoid colon confusion.
1288 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1292 if ($config{usedirs}) {
1293 $url =~ s!/index.$config{htmlext}$!/!;
1308 if (! $destsources{$to}) {
1313 return $config{url}.beautify_urlpath("/".$to);
1316 if (! defined $from) {
1317 my $u = $local_url || '';
1319 return $u.beautify_urlpath("/".$to);
1322 my $link = abs2rel($to, dirname(htmlpage($from)));
1324 return beautify_urlpath($link);
1327 sub isselflink ($$) {
1328 # Plugins can override this function to support special types
1333 return $page eq $link;
1336 sub htmllink ($$$;@) {
1337 my $lpage=shift; # the page doing the linking
1338 my $page=shift; # the page that will contain the link (different for inline)
1345 if (! $opts{forcesubpage}) {
1346 $bestlink=bestlink($lpage, $link);
1349 $bestlink="$lpage/".lc($link);
1353 if (defined $opts{linktext}) {
1354 $linktext=$opts{linktext};
1357 $linktext=pagetitle(basename($link));
1360 return "<span class=\"selflink\">$linktext</span>"
1361 if length $bestlink && isselflink($page, $bestlink) &&
1362 ! defined $opts{anchor};
1364 if (! $destsources{$bestlink}) {
1365 $bestlink=htmlpage($bestlink);
1367 if (! $destsources{$bestlink}) {
1369 if (length $config{cgiurl}) {
1370 $cgilink = "<a href=\"".
1375 )."\" rel=\"nofollow\">?</a>";
1377 return "<span class=\"createlink\">$cgilink$linktext</span>"
1381 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1382 $bestlink=beautify_urlpath($bestlink);
1384 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1385 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1388 if (defined $opts{anchor}) {
1389 $bestlink.="#".$opts{anchor};
1393 foreach my $attr (qw{rel class title}) {
1394 if (defined $opts{$attr}) {
1395 push @attrs, " $attr=\"$opts{$attr}\"";
1399 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1404 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1407 sub openiduser ($) {
1410 if (defined $user && $user =~ m!^https?://! &&
1411 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1414 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1415 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1418 # backcompat with old version
1419 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1420 $display=$oid->display;
1423 # Convert "user.somehost.com" to "user [somehost.com]"
1424 # (also "user.somehost.co.uk")
1425 if ($display !~ /\[/) {
1426 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1428 # Convert "http://somehost.com/user" to "user [somehost.com]".
1429 # (also "https://somehost.com/user/")
1430 if ($display !~ /\[/) {
1431 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1433 $display=~s!^https?://!!; # make sure this is removed
1434 eval q{use CGI 'escapeHTML'};
1436 return escapeHTML($display);
1441 sub htmlize ($$$$) {
1447 my $oneline = $content !~ /\n/;
1449 if (exists $hooks{htmlize}{$type}) {
1450 $content=$hooks{htmlize}{$type}{call}->(
1452 content => $content,
1456 error("htmlization of $type not supported");
1459 run_hooks(sanitize => sub {
1462 destpage => $destpage,
1463 content => $content,
1468 # hack to get rid of enclosing junk added by markdown
1469 # and other htmlizers/sanitizers
1470 $content=~s/^<p>//i;
1471 $content=~s/<\/p>\n*$//i;
1482 run_hooks(linkify => sub {
1485 destpage => $destpage,
1486 content => $content,
1494 our $preprocess_preview=0;
1495 sub preprocess ($$$;$$) {
1496 my $page=shift; # the page the data comes from
1497 my $destpage=shift; # the page the data will appear in (different for inline)
1502 # Using local because it needs to be set within any nested calls
1504 local $preprocess_preview=$preview if defined $preview;
1511 $params="" if ! defined $params;
1513 if (length $escape) {
1514 return "[[$prefix$command $params]]";
1516 elsif (exists $hooks{preprocess}{$command}) {
1517 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1518 # Note: preserve order of params, some plugins may
1519 # consider it significant.
1521 while ($params =~ m{
1522 (?:([-.\w]+)=)? # 1: named parameter key?
1524 """(.*?)""" # 2: triple-quoted value
1526 "([^"]*?)" # 3: single-quoted value
1528 '''(.*?)''' # 4: triple-single-quote
1530 <<([a-zA-Z]+)\n # 5: heredoc start
1531 (.*?)\n\5 # 6: heredoc value
1533 (\S+) # 7: unquoted value
1535 (?:\s+|$) # delimiter to next param
1545 elsif (defined $3) {
1548 elsif (defined $4) {
1551 elsif (defined $7) {
1554 elsif (defined $6) {
1559 push @params, $key, $val;
1562 push @params, $val, '';
1565 if ($preprocessing{$page}++ > 8) {
1566 # Avoid loops of preprocessed pages preprocessing
1567 # other pages that preprocess them, etc.
1568 return "[[!$command <span class=\"error\">".
1569 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1570 $page, $preprocessing{$page}).
1576 $hooks{preprocess}{$command}{call}->(
1579 destpage => $destpage,
1580 preview => $preprocess_preview,
1586 $ret="[[!$command <span class=\"error\">".
1587 gettext("Error").": $error"."</span>]]";
1591 # use void context during scan pass
1593 $hooks{preprocess}{$command}{call}->(
1596 destpage => $destpage,
1597 preview => $preprocess_preview,
1602 $preprocessing{$page}--;
1606 return "[[$prefix$command $params]]";
1611 if ($config{prefix_directives}) {
1614 \[\[(!) # directive open; 2: prefix
1615 ([-\w]+) # 3: command
1616 ( # 4: the parameters..
1617 \s+ # Must have space if parameters present
1619 (?:[-.\w]+=)? # named parameter key?
1621 """.*?""" # triple-quoted value
1623 "[^"]*?" # single-quoted value
1625 '''.*?''' # triple-single-quote
1627 <<([a-zA-Z]+)\n # 5: heredoc start
1628 (?:.*?)\n\5 # heredoc value
1630 [^"\s\]]+ # unquoted value
1632 \s* # whitespace or end
1635 *)? # 0 or more parameters
1636 \]\] # directive closed
1642 \[\[(!?) # directive open; 2: optional prefix
1643 ([-\w]+) # 3: command
1645 ( # 4: the parameters..
1647 (?:[-.\w]+=)? # named parameter key?
1649 """.*?""" # triple-quoted value
1651 "[^"]*?" # single-quoted value
1653 '''.*?''' # triple-single-quote
1655 <<([a-zA-Z]+)\n # 5: heredoc start
1656 (?:.*?)\n\5 # heredoc value
1658 [^"\s\]]+ # unquoted value
1660 \s* # whitespace or end
1663 *) # 0 or more parameters
1664 \]\] # directive closed
1668 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1677 run_hooks(filter => sub {
1678 $content=shift->(page => $page, destpage => $destpage,
1679 content => $content);
1685 sub check_canedit ($$$;$) {
1692 run_hooks(canedit => sub {
1693 return if defined $canedit;
1694 my $ret=shift->($page, $q, $session);
1699 elsif (ref $ret eq 'CODE') {
1700 $ret->() unless $nonfatal;
1703 elsif (defined $ret) {
1704 error($ret) unless $nonfatal;
1709 return defined $canedit ? $canedit : 1;
1712 sub check_content (@) {
1715 return 1 if ! exists $hooks{checkcontent}; # optimisation
1717 if (exists $pagesources{$params{page}}) {
1719 my %old=map { $_ => 1 }
1720 split("\n", readfile(srcfile($pagesources{$params{page}})));
1721 foreach my $line (split("\n", $params{content})) {
1722 push @diff, $line if ! exists $old{$line};
1724 $params{diff}=join("\n", @diff);
1728 run_hooks(checkcontent => sub {
1729 return if defined $ok;
1730 my $ret=shift->(%params);
1735 elsif (ref $ret eq 'CODE') {
1736 $ret->() unless $params{nonfatal};
1739 elsif (defined $ret) {
1740 error($ret) unless $params{nonfatal};
1746 return defined $ok ? $ok : 1;
1749 sub check_canchange (@) {
1751 my $cgi = $params{cgi};
1752 my $session = $params{session};
1753 my @changes = @{$params{changes}};
1756 foreach my $change (@changes) {
1757 # This untaint is safe because we check file_pruned and
1759 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1760 $file=possibly_foolish_untaint($file);
1761 if (! defined $file || ! length $file ||
1762 file_pruned($file)) {
1763 error(gettext("bad file name %s"), $file);
1766 my $type=pagetype($file);
1767 my $page=pagename($file) if defined $type;
1769 if ($change->{action} eq 'add') {
1773 if ($change->{action} eq 'change' ||
1774 $change->{action} eq 'add') {
1775 if (defined $page) {
1776 check_canedit($page, $cgi, $session);
1780 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1781 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1782 check_canedit($file, $cgi, $session);
1787 elsif ($change->{action} eq 'remove') {
1788 # check_canremove tests to see if the file is present
1789 # on disk. This will fail when a single commit adds a
1790 # file and then removes it again. Avoid the problem
1791 # by not testing the removal in such pairs of changes.
1792 # (The add is still tested, just to make sure that
1793 # no data is added to the repo that a web edit
1795 next if $newfiles{$file};
1797 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1798 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1799 check_canedit(defined $page ? $page : $file, $cgi, $session);
1804 error "unknown action ".$change->{action};
1807 error sprintf(gettext("you are not allowed to change %s"), $file);
1815 # Take an exclusive lock on the wiki to prevent multiple concurrent
1816 # run issues. The lock will be dropped on program exit.
1817 if (! -d $config{wikistatedir}) {
1818 mkdir($config{wikistatedir});
1820 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1821 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1822 if (! flock($wikilock, 2)) { # LOCK_EX
1823 error("failed to get lock");
1829 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1830 return close($wikilock) if $wikilock;
1836 sub commit_hook_enabled () {
1837 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1838 error("cannot write to $config{wikistatedir}/commitlock: $!");
1839 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1840 close($commitlock) || error("failed closing commitlock: $!");
1843 close($commitlock) || error("failed closing commitlock: $!");
1847 sub disable_commit_hook () {
1848 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1849 error("cannot write to $config{wikistatedir}/commitlock: $!");
1850 if (! flock($commitlock, 2)) { # LOCK_EX
1851 error("failed to get commit lock");
1856 sub enable_commit_hook () {
1857 return close($commitlock) if $commitlock;
1862 %oldrenderedfiles=%pagectime=();
1863 my $rebuild=$config{rebuild};
1865 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1866 %destsources=%renderedfiles=%pagecase=%pagestate=
1867 %depends_simple=%typedlinks=%oldtypedlinks=();
1870 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1871 if (-e "$config{wikistatedir}/index") {
1872 system("ikiwiki-transition", "indexdb", $config{srcdir});
1873 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1876 # gettime on first build
1877 $config{gettime}=1 unless defined $config{gettime};
1882 my $index=Storable::fd_retrieve($in);
1883 if (! defined $index) {
1888 if (exists $index->{version} && ! ref $index->{version}) {
1889 $pages=$index->{page};
1890 %wikistate=%{$index->{state}};
1891 # Handle plugins that got disabled by loading a new setup.
1892 if (exists $config{setupfile}) {
1893 require IkiWiki::Setup;
1894 IkiWiki::Setup::disabled_plugins(
1895 grep { ! $loaded_plugins{$_} } keys %wikistate);
1903 foreach my $src (keys %$pages) {
1904 my $d=$pages->{$src};
1906 if (exists $d->{page} && ! $rebuild) {
1910 $page=pagename($src);
1912 $pagectime{$page}=$d->{ctime};
1913 $pagesources{$page}=$src;
1915 $pagemtime{$page}=$d->{mtime};
1916 $renderedfiles{$page}=$d->{dest};
1917 if (exists $d->{links} && ref $d->{links}) {
1918 $links{$page}=$d->{links};
1919 $oldlinks{$page}=[@{$d->{links}}];
1921 if (ref $d->{depends_simple} eq 'ARRAY') {
1923 $depends_simple{$page}={
1924 map { $_ => 1 } @{$d->{depends_simple}}
1927 elsif (exists $d->{depends_simple}) {
1928 $depends_simple{$page}=$d->{depends_simple};
1930 if (exists $d->{dependslist}) {
1933 map { $_ => $DEPEND_CONTENT }
1934 @{$d->{dependslist}}
1937 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1939 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1941 elsif (exists $d->{depends}) {
1942 $depends{$page}=$d->{depends};
1944 if (exists $d->{state}) {
1945 $pagestate{$page}=$d->{state};
1947 if (exists $d->{typedlinks}) {
1948 $typedlinks{$page}=$d->{typedlinks};
1950 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1951 next unless %$links;
1952 $oldtypedlinks{$page}{$type} = {%$links};
1956 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1958 foreach my $page (keys %pagesources) {
1959 $pagecase{lc $page}=$page;
1961 foreach my $page (keys %renderedfiles) {
1962 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1964 $lastrev=$index->{lastrev};
1965 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1970 run_hooks(savestate => sub { shift->() });
1972 my @plugins=keys %loaded_plugins;
1974 if (! -d $config{wikistatedir}) {
1975 mkdir($config{wikistatedir});
1977 my $newfile="$config{wikistatedir}/indexdb.new";
1978 my $cleanup = sub { unlink($newfile) };
1979 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1982 foreach my $page (keys %pagemtime) {
1983 next unless $pagemtime{$page};
1984 my $src=$pagesources{$page};
1986 $index{page}{$src}={
1988 ctime => $pagectime{$page},
1989 mtime => $pagemtime{$page},
1990 dest => $renderedfiles{$page},
1991 links => $links{$page},
1994 if (exists $depends{$page}) {
1995 $index{page}{$src}{depends} = $depends{$page};
1998 if (exists $depends_simple{$page}) {
1999 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2002 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2003 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2006 if (exists $pagestate{$page}) {
2007 $index{page}{$src}{state}=$pagestate{$page};
2012 foreach my $id (@plugins) {
2013 $index{state}{$id}={}; # used to detect disabled plugins
2014 foreach my $key (keys %{$wikistate{$id}}) {
2015 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2019 $index{lastrev}=$lastrev;
2020 $index{underlayfiles}=\@underlayfiles;
2022 $index{version}="3";
2023 my $ret=Storable::nstore_fd(\%index, $out);
2024 return if ! defined $ret || ! $ret;
2025 close $out || error("failed saving to $newfile: $!", $cleanup);
2026 rename($newfile, "$config{wikistatedir}/indexdb") ||
2027 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2032 sub template_file ($) {
2035 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2037 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2038 $template=srcfile($pagesources{$tpage}, 1);
2042 $template=srcfile($tpage, 1);
2045 if (defined $template) {
2046 return $template, $tpage, 1 if wantarray;
2050 $name=~s:/::; # avoid path traversal
2051 foreach my $dir ($config{templatedir},
2052 "$installdir/share/ikiwiki/templates") {
2053 if (-e "$dir/$name") {
2054 $template="$dir/$name";
2058 if (defined $template) {
2059 return $template, $tpage if wantarray;
2067 sub template_depends ($$;@) {
2071 my ($filename, $tpage, $untrusted)=template_file($name);
2072 if (! defined $filename) {
2073 error(sprintf(gettext("template %s not found"), $name))
2076 if (defined $page && defined $tpage) {
2077 add_depends($page, $tpage);
2082 my $text_ref = shift;
2083 ${$text_ref} = decode_utf8(${$text_ref});
2084 run_hooks(readtemplate => sub {
2085 ${$text_ref} = shift->(
2088 content => ${$text_ref},
2089 untrusted => $untrusted,
2093 loop_context_vars => 1,
2094 die_on_bad_params => 0,
2095 parent_global_vars => 1,
2096 filename => $filename,
2098 ($untrusted ? (no_includes => 1) : ()),
2100 return @opts if wantarray;
2102 require HTML::Template;
2103 return HTML::Template->new(@opts);
2106 sub template ($;@) {
2107 template_depends(shift, undef, @_);
2110 sub templateactions ($$) {
2116 run_hooks(pageactions => sub {
2117 push @actions, map { { action => $_ } }
2118 grep { defined } shift->(page => $page);
2120 $template->param(actions => \@actions);
2122 if ($config{cgiurl} && exists $hooks{auth}) {
2123 $template->param(prefsurl => cgiurl(do => "prefs"));
2127 if ($have_actions || @actions) {
2128 $template->param(have_actions => 1);
2135 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2136 error 'hook requires type, call, and id parameters';
2139 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2141 $hooks{$param{type}}{$param{id}}=\%param;
2145 sub run_hooks ($$) {
2146 # Calls the given sub for each hook of the given type,
2147 # passing it the hook function to call.
2151 if (exists $hooks{$type}) {
2152 my (@first, @middle, @last);
2153 foreach my $id (keys %{$hooks{$type}}) {
2154 if ($hooks{$type}{$id}{first}) {
2157 elsif ($hooks{$type}{$id}{last}) {
2164 foreach my $id (@first, @middle, @last) {
2165 $sub->($hooks{$type}{$id}{call});
2173 $hooks{rcs}{rcs_update}{call}->(@_);
2176 sub rcs_prepedit ($) {
2177 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2180 sub rcs_commit (@) {
2181 $hooks{rcs}{rcs_commit}{call}->(@_);
2184 sub rcs_commit_staged (@) {
2185 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2189 $hooks{rcs}{rcs_add}{call}->(@_);
2192 sub rcs_remove ($) {
2193 $hooks{rcs}{rcs_remove}{call}->(@_);
2196 sub rcs_rename ($$) {
2197 $hooks{rcs}{rcs_rename}{call}->(@_);
2200 sub rcs_recentchanges ($) {
2201 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2204 sub rcs_diff ($;$) {
2205 $hooks{rcs}{rcs_diff}{call}->(@_);
2208 sub rcs_getctime ($) {
2209 $hooks{rcs}{rcs_getctime}{call}->(@_);
2212 sub rcs_getmtime ($) {
2213 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2216 sub rcs_receive () {
2217 $hooks{rcs}{rcs_receive}{call}->();
2220 sub add_depends ($$;$) {
2223 my $deptype=shift || $DEPEND_CONTENT;
2225 # Is the pagespec a simple page name?
2226 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2227 $pagespec !~ /[\s*?()!]/) {
2228 $depends_simple{$page}{lc $pagespec} |= $deptype;
2232 # Add explicit dependencies for influences.
2233 my $sub=pagespec_translate($pagespec);
2234 return unless defined $sub;
2235 foreach my $p (keys %pagesources) {
2236 my $r=$sub->($p, location => $page);
2237 my $i=$r->influences;
2238 my $static=$r->influences_static;
2239 foreach my $k (keys %$i) {
2240 next unless $r || $static || $k eq $page;
2241 $depends_simple{$page}{lc $k} |= $i->{$k};
2246 $depends{$page}{$pagespec} |= $deptype;
2252 foreach my $type (@_) {
2253 if ($type eq 'presence') {
2254 $deptype |= $DEPEND_PRESENCE;
2256 elsif ($type eq 'links') {
2257 $deptype |= $DEPEND_LINKS;
2259 elsif ($type eq 'content') {
2260 $deptype |= $DEPEND_CONTENT;
2266 my $file_prune_regexp;
2267 sub file_pruned ($) {
2270 if (defined $config{include} && length $config{include}) {
2271 return 0 if $file =~ m/$config{include}/;
2274 if (! defined $file_prune_regexp) {
2275 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2276 $file_prune_regexp=qr/$file_prune_regexp/;
2278 return $file =~ m/$file_prune_regexp/;
2281 sub define_gettext () {
2282 # If translation is needed, redefine the gettext function to do it.
2283 # Otherwise, it becomes a quick no-op.
2286 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2287 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2288 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2290 $gettext_obj=eval q{
2291 use Locale::gettext q{textdomain};
2292 Locale::gettext->domain('ikiwiki')
2297 no warnings 'redefine';
2299 $getobj->() if $getobj;
2301 $gettext_obj->get(shift);
2308 $getobj->() if $getobj;
2310 $gettext_obj->nget(@_);
2313 return ($_[2] == 1 ? $_[0] : $_[1])
2331 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2335 # Injects a new function into the symbol table to replace an
2336 # exported function.
2339 # This is deep ugly perl foo, beware.
2342 if (! defined $params{parent}) {
2343 $params{parent}='::';
2344 $params{old}=\&{$params{name}};
2345 $params{name}=~s/.*:://;
2347 my $parent=$params{parent};
2348 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2349 $ns = $params{parent} . $ns;
2350 inject(%params, parent => $ns) unless $ns eq '::main::';
2351 *{$ns . $params{name}} = $params{call}
2352 if exists ${$ns}{$params{name}} &&
2353 \&{${$ns}{$params{name}}} == $params{old};
2359 sub add_link ($$;$) {
2364 push @{$links{$page}}, $link
2365 unless grep { $_ eq $link } @{$links{$page}};
2367 if (defined $type) {
2368 $typedlinks{$page}{$type}{$link} = 1;
2372 sub add_autofile ($$$) {
2375 my $generator=shift;
2377 $autofiles{$file}{plugin}=$plugin;
2378 $autofiles{$file}{generator}=$generator;
2382 return LWP::UserAgent->new(
2383 cookie_jar => $config{cookiejar},
2384 env_proxy => 1, # respect proxy env vars
2385 agent => $config{useragent},
2389 sub sortspec_translate ($$) {
2391 my $reverse = shift;
2397 (-?) # group 1: perhaps negated
2400 \w+\([^\)]*\) # command(params)
2402 [^\s]+ # or anything else
2410 if ($word =~ m/^(\w+)\((.*)\)$/) {
2411 # command with parameters
2415 elsif ($word !~ m/^\w+$/) {
2416 error(sprintf(gettext("invalid sort type %s"), $word));
2427 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2428 if (defined $params) {
2429 push @data, $params;
2430 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2433 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2437 error(sprintf(gettext("unknown sort type %s"), $word));
2441 if (! length $code) {
2442 # undefined sorting method... sort arbitrarily
2451 return eval 'sub { '.$code.' }';
2454 sub pagespec_translate ($) {
2457 # Convert spec to perl code.
2461 \s* # ignore whitespace
2462 ( # 1: match a single word
2469 \w+\([^\)]*\) # command(params)
2471 [^\s()]+ # any other text
2473 \s* # ignore whitespace
2476 if (lc $word eq 'and') {
2479 elsif (lc $word eq 'or') {
2482 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2485 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2486 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2488 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2491 push @data, qq{unknown function in pagespec "$word"};
2492 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2497 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2501 if (! length $code) {
2502 $code="IkiWiki::FailReason->new('empty pagespec')";
2506 return eval 'sub { my $page=shift; '.$code.' }';
2509 sub pagespec_match ($$;@) {
2514 # Backwards compatability with old calling convention.
2516 unshift @params, 'location';
2519 my $sub=pagespec_translate($spec);
2520 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2522 return $sub->($page, @params);
2525 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2527 # Not exported yet, but could be in future if it is generally useful.
2528 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2529 # which is "more internal".
2530 sub sort_pages ($$;@) {
2534 $sort = sortspec_translate($sort, $params{reverse});
2535 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2538 sub pagespec_match_list ($$;@) {
2543 # Backwards compatability with old calling convention.
2545 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2546 $params{list}=$page;
2547 $page=$params{location}; # ugh!
2550 my $sub=pagespec_translate($pagespec);
2551 error "syntax error in pagespec \"$pagespec\""
2553 my $sort=sortspec_translate($params{sort}, $params{reverse})
2554 if defined $params{sort};
2557 if (exists $params{list}) {
2558 @candidates=exists $params{filter}
2559 ? grep { ! $params{filter}->($_) } @{$params{list}}
2563 @candidates=exists $params{filter}
2564 ? grep { ! $params{filter}->($_) } keys %pagesources
2565 : keys %pagesources;
2568 # clear params, remainder is passed to pagespec
2569 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2570 my $num=$params{num};
2571 delete @params{qw{num deptype reverse sort filter list}};
2573 # when only the top matches will be returned, it's efficient to
2574 # sort before matching to pagespec,
2575 if (defined $num && defined $sort) {
2576 @candidates=IkiWiki::SortSpec::sort_pages(
2577 $sort, @candidates);
2583 my $accum=IkiWiki::SuccessReason->new();
2584 foreach my $p (@candidates) {
2585 my $r=$sub->($p, %params, location => $page);
2586 error(sprintf(gettext("cannot match pages: %s"), $r))
2587 if $r->isa("IkiWiki::ErrorReason");
2588 unless ($r || $r->influences_static) {
2589 $r->remove_influence($p);
2594 last if defined $num && ++$count == $num;
2598 # Add simple dependencies for accumulated influences.
2599 my $i=$accum->influences;
2600 foreach my $k (keys %$i) {
2601 $depends_simple{$page}{lc $k} |= $i->{$k};
2604 # when all matches will be returned, it's efficient to
2605 # sort after matching
2606 if (! defined $num && defined $sort) {
2607 return IkiWiki::SortSpec::sort_pages(
2615 sub pagespec_valid ($) {
2618 return defined pagespec_translate($spec);
2622 my $re=quotemeta(shift);
2628 package IkiWiki::FailReason;
2631 '""' => sub { $_[0][0] },
2633 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2634 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2635 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2639 our @ISA = 'IkiWiki::SuccessReason';
2641 package IkiWiki::SuccessReason;
2643 # A blessed array-ref:
2645 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2647 # - if absent or false, the influences of this evaluation are "static",
2648 # see the influences_static method
2649 # - if true, they are dynamic (not static)
2650 # [1]{any other key}:
2651 # the dependency types of influences, as returned by the influences method
2654 # in string context, it's the human-readable reason
2655 '""' => sub { $_[0][0] },
2656 # in boolean context, SuccessReason is 1 and FailReason is 0
2658 # negating a result gives the opposite result with the same influences
2659 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2660 # A & B = (A ? B : A) with the influences of both
2661 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2662 # A | B = (A ? A : B) with the influences of both
2663 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2667 # SuccessReason->new("human-readable reason", page => deptype, ...)
2672 return bless [$value, {@_}], $class;
2675 # influences(): return a reference to a copy of the hash
2676 # { page => dependency type } describing the pages that indirectly influenced
2677 # this result, but would not cause a dependency through ikiwiki's core
2680 # See [[todo/dependency_types]] for extensive discussion of what this means.
2682 # influences(page => deptype, ...): remove all influences, replace them
2683 # with the arguments, and return a reference to a copy of the new influences.
2687 $this->[1]={@_} if @_;
2688 my %i=%{$this->[1]};
2693 # True if this result has the same influences whichever page it matches,
2694 # For instance, whether bar matches backlink(foo) is influenced only by
2695 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2696 # which does not mention bar anywhere.
2698 # False if this result would have different influences when matching
2699 # different pages. For instance, when testing whether link(foo) matches bar,
2700 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2701 # bar's links could change the outcome; so its influences are not the same
2702 # as when testing whether link(foo) matches baz.
2704 # Static influences are one of the things that make pagespec_match_list
2705 # more efficient than repeated calls to pagespec_match.
2707 sub influences_static {
2708 return ! $_[0][1]->{""};
2711 # Change the influences of $this to be the influences of "$this & $other"
2712 # or "$this | $other".
2714 # If both $this and $other are either successful or have influences,
2715 # or this is an "or" operation, the result has all the influences from
2716 # either of the arguments. It has dynamic influences if either argument
2717 # has dynamic influences.
2719 # If this is an "and" operation, and at least one argument is a
2720 # FailReason with no influences, the result has no influences, and they
2721 # are not dynamic. For instance, link(foo) matching bar is influenced
2722 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2723 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2724 # bar, because it would be false however often you edit bar.
2726 sub merge_influences {
2731 # This "if" is odd because it needs to avoid negating $this
2732 # or $other, which would alter the objects in-place. Be careful.
2733 if (! $anded || (($this || %{$this->[1]}) &&
2734 ($other || %{$other->[1]}))) {
2735 foreach my $influence (keys %{$other->[1]}) {
2736 $this->[1]{$influence} |= $other->[1]{$influence};
2745 # Change $this so it is not considered to be influenced by $torm.
2747 sub remove_influence {
2751 delete $this->[1]{$torm};
2754 package IkiWiki::ErrorReason;
2756 our @ISA = 'IkiWiki::FailReason';
2758 package IkiWiki::PageSpec;
2764 if ($path =~ m!^\.(/|$)!) {
2766 $from=~s#/?[^/]+$## if defined $from;
2768 $path="$from/$path" if defined $from && length $from;
2772 $path = "" unless defined $path;
2781 sub match_glob ($$;@) {
2786 $glob=derel($glob, $params{location});
2788 # Instead of converting the glob to a regex every time,
2789 # cache the compiled regex to save time.
2790 my $re=$glob_cache{$glob};
2791 unless (defined $re) {
2792 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2795 if (! IkiWiki::isinternal($page) || $params{internal}) {
2796 return IkiWiki::SuccessReason->new("$glob matches $page");
2799 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2803 return IkiWiki::FailReason->new("$glob does not match $page");
2807 sub match_internal ($$;@) {
2808 return match_glob(shift, shift, @_, internal => 1)
2811 sub match_page ($$;@) {
2813 my $match=match_glob($page, shift, @_);
2815 my $source=exists $IkiWiki::pagesources{$page} ?
2816 $IkiWiki::pagesources{$page} :
2817 $IkiWiki::delpagesources{$page};
2818 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2819 if (! defined $type) {
2820 return IkiWiki::FailReason->new("$page is not a page");
2826 sub match_link ($$;@) {
2831 $link=derel($link, $params{location});
2832 my $from=exists $params{location} ? $params{location} : '';
2833 my $linktype=$params{linktype};
2835 if (defined $linktype) {
2836 $qualifier=" with type $linktype";
2839 my $links = $IkiWiki::links{$page};
2840 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2841 unless $links && @{$links};
2842 my $bestlink = IkiWiki::bestlink($from, $link);
2843 foreach my $p (@{$links}) {
2844 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2846 if (length $bestlink) {
2847 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2848 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2852 if (match_glob($p, $link, %params)) {
2853 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2855 my ($p_rel)=$p=~/^\/?(.*)/;
2857 if (match_glob($p_rel, $link, %params)) {
2858 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2862 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2865 sub match_backlink ($$;@) {
2869 if ($testpage eq '.') {
2870 $testpage = $params{'location'}
2872 my $ret=match_link($testpage, $page, @_);
2873 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2877 sub match_created_before ($$;@) {
2882 $testpage=derel($testpage, $params{location});
2884 if (exists $IkiWiki::pagectime{$testpage}) {
2885 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2886 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2889 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2893 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2897 sub match_created_after ($$;@) {
2902 $testpage=derel($testpage, $params{location});
2904 if (exists $IkiWiki::pagectime{$testpage}) {
2905 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2906 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2909 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2913 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2917 sub match_creation_day ($$;@) {
2920 if ($d !~ /^\d+$/) {
2921 return IkiWiki::ErrorReason->new("invalid day $d");
2923 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2924 return IkiWiki::SuccessReason->new('creation_day matched');
2927 return IkiWiki::FailReason->new('creation_day did not match');
2931 sub match_creation_month ($$;@) {
2934 if ($m !~ /^\d+$/) {
2935 return IkiWiki::ErrorReason->new("invalid month $m");
2937 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2938 return IkiWiki::SuccessReason->new('creation_month matched');
2941 return IkiWiki::FailReason->new('creation_month did not match');
2945 sub match_creation_year ($$;@) {
2948 if ($y !~ /^\d+$/) {
2949 return IkiWiki::ErrorReason->new("invalid year $y");
2951 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2952 return IkiWiki::SuccessReason->new('creation_year matched');
2955 return IkiWiki::FailReason->new('creation_year did not match');
2959 sub match_user ($$;@) {
2964 if (! exists $params{user}) {
2965 return IkiWiki::ErrorReason->new("no user specified");
2968 my $regexp=IkiWiki::glob2re($user);
2970 if (defined $params{user} && $params{user}=~$regexp) {
2971 return IkiWiki::SuccessReason->new("user is $user");
2973 elsif (! defined $params{user}) {
2974 return IkiWiki::FailReason->new("not logged in");
2977 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2981 sub match_admin ($$;@) {
2986 if (! exists $params{user}) {
2987 return IkiWiki::ErrorReason->new("no user specified");
2990 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2991 return IkiWiki::SuccessReason->new("user is an admin");
2993 elsif (! defined $params{user}) {
2994 return IkiWiki::FailReason->new("not logged in");
2997 return IkiWiki::FailReason->new("user is not an admin");
3001 sub match_ip ($$;@) {
3006 if (! exists $params{ip}) {
3007 return IkiWiki::ErrorReason->new("no IP specified");
3010 my $regexp=IkiWiki::glob2re(lc $ip);
3012 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3013 return IkiWiki::SuccessReason->new("IP is $ip");
3016 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3020 package IkiWiki::SortSpec;
3022 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3023 # are easily available in this namespace, for cmp functions to use them.
3030 IkiWiki::pagetitle(IkiWiki::basename($a))
3032 IkiWiki::pagetitle(IkiWiki::basename($b))
3035 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3036 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3037 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }