9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %wikistate %renderedfiles %oldrenderedfiles
16 %pagesources %delpagesources %destsources %depends %depends_simple
17 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
18 %oldtypedlinks %autofiles @underlayfiles $lastrev $phase};
20 use Exporter q{import};
21 our @EXPORT = qw(hook debug error htmlpage template template_depends
22 deptype add_depends pagespec_match pagespec_match_list bestlink
23 htmllink readfile writefile pagetype srcfile pagename
24 displaytime strftime_utf8 will_render gettext ngettext urlto targetpage
25 add_underlay pagetitle titlepage linkpage newpagefile
26 inject add_link add_autofile useragent
27 %config %links %pagestate %wikistate %renderedfiles
28 %pagesources %destsources %typedlinks);
29 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
30 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
31 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
33 # Page dependency types.
34 our $DEPEND_CONTENT=1;
35 our $DEPEND_PRESENCE=2;
38 # Phases of processing.
39 sub PHASE_SCAN () { 0 }
40 sub PHASE_RENDER () { 1 }
46 memoize("sortspec_translate");
47 memoize("pagespec_translate");
48 memoize("template_file");
54 description => "name of the wiki",
61 example => 'me@example.com',
62 description => "contact email for wiki",
69 description => "users who are wiki admins",
76 description => "users who are banned from the wiki",
83 example => "$ENV{HOME}/wiki",
84 description => "where the source of the wiki is located",
91 example => "/var/www/wiki",
92 description => "where to build the wiki",
99 example => "http://example.com/wiki",
100 description => "base url to the wiki",
107 example => "http://example.com/wiki/ikiwiki.cgi",
108 description => "url to the ikiwiki.cgi",
115 description => "do not adjust cgiurl if CGI is accessed via different URL",
118 rebuild => 0, # only affects CGI requests
123 example => "/var/www/wiki/ikiwiki.cgi",
124 description => "filename of cgi wrapper to generate",
131 description => "mode for cgi_wrapper (can safely be made suid)",
135 cgi_overload_delay => {
139 description => "number of seconds to delay CGI requests when overloaded",
143 cgi_overload_message => {
146 example => "Please wait",
147 description => "message to display when overloaded (may contain html)",
151 only_committed_changes => {
154 description => "enable optimization of only refreshing committed changes?",
161 description => "rcs backend to use",
162 safe => 0, # don't allow overriding
167 default => [qw{mdwn link inline meta htmlscrubber passwordauth
168 openid signinedit lockedit conditional
169 recentchanges parentlinks editpage
171 description => "plugins to enable by default",
178 description => "plugins to add to the default configuration",
185 description => "plugins to disable",
191 default => "$installdir/share/ikiwiki/templates",
192 description => "additional directory to search for template files",
199 default => "$installdir/share/ikiwiki/basewiki",
200 description => "base wiki source location",
207 default => "$installdir/share/ikiwiki",
208 description => "parent directory containing additional underlays",
215 description => "wrappers to generate",
222 description => "additional underlays to use",
229 description => "display verbose messages?",
236 description => "log to syslog?",
243 description => "create output files named page/index.html?",
244 safe => 0, # changing requires manual transition
247 prefix_directives => {
250 description => "use '!'-prefixed preprocessor directives?",
251 safe => 0, # changing requires manual transition
257 description => "use page/index.mdwn source files",
264 description => "enable Discussion pages?",
270 default => gettext("Discussion"),
271 description => "name of Discussion pages",
278 description => "use elements new in HTML5 like <section>?",
286 description => "only send cookies over SSL connections?",
294 description => "extension to use for new pages",
295 safe => 0, # not sanitized
301 description => "extension to use for html files",
302 safe => 0, # not sanitized
308 description => "strftime format string to display date",
316 example => "en_US.UTF-8",
317 description => "UTF-8 locale to use",
326 description => "put user pages below specified page",
333 description => "how many backlinks to show before hiding excess (0 to show all)",
340 description => "attempt to hardlink source files? (optimisation for large files)",
342 safe => 0, # paranoia
348 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
350 safe => 0, # paranoia
355 example => "ikiwiki",
356 description => "group for wrappers to run in",
358 safe => 0, # paranoia
364 example => "$ENV{HOME}/.ikiwiki/",
365 description => "extra library and plugin directorys. Can be either a string (for backward compatibility) or a list of strings.",
367 safe => 0, # directory
373 description => "environment variables",
374 safe => 0, # paranoia
380 example => "US/Eastern",
381 description => "time zone name",
388 example => '^\.htaccess$',
389 description => "regexp of normally excluded files to include",
397 example => '^(*\.private|Makefile)$',
398 description => "regexp of files that should be skipped",
403 wiki_file_prune_regexps => {
405 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
406 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
407 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
408 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
409 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
410 description => "regexps of source files to ignore",
416 description => "specifies the characters that are allowed in source filenames",
417 default => "-[:alnum:]+/.:_",
421 wiki_file_regexp => {
423 description => "regexp of legal source files",
427 web_commit_regexp => {
429 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
430 description => "regexp to parse web commits from logs",
437 description => "run as a cgi",
441 cgi_disable_uploads => {
444 description => "whether CGI should accept file uploads",
451 description => "run as a post-commit hook",
458 description => "running in rebuild mode",
465 description => "running in setup mode",
472 description => "running in clean mode",
479 description => "running in refresh mode",
486 description => "running in receive test mode",
490 wrapper_background_command => {
493 description => "background shell command to run",
499 description => "running in gettime mode",
506 description => "running in w3mmode",
513 description => "path to the .ikiwiki directory holding ikiwiki state",
520 description => "path to setup file",
527 description => "perl class to use to dump setup file",
531 allow_symlinks_before_srcdir => {
534 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
540 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
541 description => "cookie control",
542 safe => 0, # hooks into perl module internals
547 default => "ikiwiki/$version",
548 example => "Wget/1.13.4 (linux-gnu)",
549 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
553 responsive_layout => {
556 description => "theme has a responsive layout? (mobile-optimized)",
564 if (! ref $config{libdir}) {
565 if (length $config{libdir}) {
566 $libdirs = [$config{libdir}];
571 $libdirs = $config{libdir};
576 sub defaultconfig () {
579 foreach my $key (keys %s) {
580 push @ret, $key, $s{$key}->{default};
585 # URL to top of wiki as a path starting with /, valid from any wiki page or
586 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
588 # URL to CGI script, similar to $local_url
592 # locale stuff; avoid LC_ALL since it overrides everything
593 if (defined $ENV{LC_ALL}) {
594 $ENV{LANG} = $ENV{LC_ALL};
597 if (defined $config{locale}) {
598 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
599 $ENV{LANG}=$config{locale};
604 if (! defined $config{wiki_file_regexp}) {
605 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
608 if (ref $config{ENV} eq 'HASH') {
609 foreach my $val (keys %{$config{ENV}}) {
610 $ENV{$val}=$config{ENV}{$val};
613 if (defined $config{timezone} && length $config{timezone}) {
614 $ENV{TZ}=$config{timezone};
617 $config{timezone}=$ENV{TZ};
620 if ($config{w3mmode}) {
621 eval q{use Cwd q{abs_path}};
623 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
624 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
625 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
626 unless $config{cgiurl} =~ m!file:///!;
627 $config{url}="file://".$config{destdir};
630 if ($config{cgi} && ! length $config{url}) {
631 error(gettext("Must specify url to wiki with --url when using --cgi"));
634 if (defined $config{url} && length $config{url}) {
636 my $baseurl = URI->new($config{url});
638 $local_url = $baseurl->path . "/";
639 $local_cgiurl = undef;
641 if (length $config{cgiurl}) {
642 my $cgiurl = URI->new($config{cgiurl});
644 $local_cgiurl = $cgiurl->path;
646 if ($cgiurl->scheme eq 'https' &&
647 $baseurl->scheme eq 'http') {
648 # We assume that the same content is available
649 # over both http and https, because if it
650 # wasn't, accessing the static content
651 # from the CGI would be mixed-content,
652 # which would be a security flaw.
654 if ($cgiurl->authority ne $baseurl->authority) {
655 # use protocol-relative URL for
657 $local_url = "$config{url}/";
658 $local_url =~ s{^http://}{//};
660 # else use host-relative URL for static content
662 # either way, CGI needs to be absolute
663 $local_cgiurl = $config{cgiurl};
665 elsif ($cgiurl->scheme ne $baseurl->scheme) {
666 # too far apart, fall back to absolute URLs
667 $local_url = "$config{url}/";
668 $local_cgiurl = $config{cgiurl};
670 elsif ($cgiurl->authority ne $baseurl->authority) {
671 # slightly too far apart, fall back to
672 # protocol-relative URLs
673 $local_url = "$config{url}/";
674 $local_url =~ s{^https?://}{//};
675 $local_cgiurl = $config{cgiurl};
676 $local_cgiurl =~ s{^https?://}{//};
678 # else keep host-relative URLs
681 $local_url =~ s{//$}{/};
684 $local_cgiurl = $config{cgiurl};
687 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
688 unless exists $config{wikistatedir} && defined $config{wikistatedir};
690 if (defined $config{umask}) {
691 my $u = possibly_foolish_untaint($config{umask});
693 if ($u =~ m/^\d+$/) {
696 elsif ($u eq 'private') {
699 elsif ($u eq 'group') {
702 elsif ($u eq 'public') {
706 error(sprintf(gettext("unsupported umask setting %s"), $u));
710 run_hooks(checkconfig => sub { shift->() });
718 foreach my $dir (@INC, getlibdirs()) {
719 next unless defined $dir && length $dir;
720 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
721 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
725 foreach my $dir (getlibdirs(), "$installdir/lib/ikiwiki") {
726 next unless defined $dir && length $dir;
727 foreach my $file (glob("$dir/plugins/*")) {
728 $ret{basename($file)}=1 if -x $file;
736 if (defined $config{libdir} && length $config{libdir}) {
737 foreach my $dir (getlibdirs()) {
738 unshift @INC, possibly_foolish_untaint($dir);
742 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
747 if (exists $hooks{rcs}) {
748 error(gettext("cannot use multiple rcs plugins"));
750 loadplugin($config{rcs});
752 if (! exists $hooks{rcs}) {
756 run_hooks(getopt => sub { shift->() });
757 if (grep /^-/, @ARGV) {
758 print STDERR "Unknown option (or missing parameter): $_\n"
759 foreach grep /^-/, @ARGV;
766 sub loadplugin ($;$) {
770 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
772 foreach my $possiblytainteddir (getlibdirs(), "$installdir/lib/ikiwiki") {
773 my $dir = defined $possiblytainteddir ? possibly_foolish_untaint($possiblytainteddir) : undef;
774 if (defined $dir && -x "$dir/plugins/$plugin") {
775 eval { require IkiWiki::Plugin::external };
778 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
780 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
781 $loaded_plugins{$plugin}=1;
786 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
789 error("Failed to load plugin $mod: $@");
791 $loaded_plugins{$plugin}=1;
798 log_message('err' => $message) if $config{syslog};
799 if (defined $cleaner) {
806 return unless $config{verbose};
807 return log_message(debug => @_);
812 sub log_message ($$) {
815 if ($config{syslog}) {
818 Sys::Syslog::setlogsock('unix');
819 Sys::Syslog::openlog('ikiwiki', '', 'user');
823 # keep a copy to avoid editing the original config repeatedly
824 my $wikiname = $config{wikiname};
825 utf8::encode($wikiname);
826 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
829 print STDERR "failed to syslog: $@" unless $log_failed;
835 elsif (! $config{cgi}) {
839 return print STDERR "@_\n";
843 sub possibly_foolish_untaint ($) {
845 my ($untainted)=$tainted=~/(.*)/s;
865 return exists $pagesources{$page} &&
866 $pagesources{$page} =~ /\._([^.]+)$/;
872 if ($file =~ /\.([^.]+)$/) {
873 return $1 if exists $hooks{htmlize}{$1};
875 my $base=basename($file);
876 if (exists $hooks{htmlize}{$base} &&
877 $hooks{htmlize}{$base}{noextension}) {
888 if (exists $pagename_cache{$file}) {
889 return $pagename_cache{$file};
892 my $type=pagetype($file);
894 $page=~s/\Q.$type\E*$//
895 if defined $type && !$hooks{htmlize}{$type}{keepextension}
896 && !$hooks{htmlize}{$type}{noextension};
897 if ($config{indexpages} && $page=~/(.*)\/index$/) {
901 $pagename_cache{$file} = $page;
905 sub newpagefile ($$) {
909 if (! $config{indexpages} || $page eq 'index') {
910 return $page.".".$type;
913 return $page."/index.".$type;
917 sub targetpage ($$;$) {
922 if (defined $filename) {
923 return $page."/".$filename.".".$ext;
925 elsif (! $config{usedirs} || $page eq 'index') {
926 return $page.".".$ext;
929 return $page."/index.".$ext;
936 return targetpage($page, $config{htmlext});
943 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
944 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
945 return "$dir/$file", stat(_) if -e "$dir/$file";
947 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
952 return (srcfile_stat(@_))[0];
955 sub add_literal_underlay ($) {
958 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
959 unshift @{$config{underlaydirs}}, $dir;
963 sub add_underlay ($) {
967 $dir="$config{underlaydirbase}/$dir";
970 add_literal_underlay($dir);
971 # why does it return 1? we just don't know
975 sub readfile ($;$$) {
981 error("cannot read a symlink ($file)");
985 open (my $in, "<", $file) || error("failed to read $file: $!");
986 binmode($in) if ($binary);
987 return \*$in if $wantfd;
989 # check for invalid utf-8, and toss it back to avoid crashes
990 if (! utf8::valid($ret)) {
991 $ret=encode_utf8($ret);
993 close $in || error("failed to read $file: $!");
997 sub prep_writefile ($$) {
1002 while (length $test) {
1003 if (-l "$destdir/$test") {
1004 error("cannot write to a symlink ($test)");
1006 if (-f _ && $test ne $file) {
1007 # Remove conflicting file.
1008 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1009 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1011 unlink("$destdir/$test");
1017 $test=dirname($test);
1020 my $dir=dirname("$destdir/$file");
1023 foreach my $s (split(m!/+!, $dir)) {
1026 mkdir($d) || error("failed to create directory $d: $!");
1034 sub writefile ($$$;$$) {
1035 my $file=shift; # can include subdirs
1036 my $destdir=shift; # directory to put file in
1041 prep_writefile($file, $destdir);
1043 my $newfile="$destdir/$file.ikiwiki-new";
1045 error("cannot write to a symlink ($newfile)");
1048 my $cleanup = sub { unlink($newfile) };
1049 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1050 binmode($out) if ($binary);
1052 $writer->(\*$out, $cleanup);
1055 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1057 close $out || error("failed saving $newfile: $!", $cleanup);
1058 rename($newfile, "$destdir/$file") ||
1059 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1065 sub will_render ($$;$) {
1070 # Important security check for independently created files.
1071 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1072 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1073 my $from_other_page=0;
1074 # Expensive, but rarely runs.
1075 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1078 dirname($_) eq $dest
1079 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1085 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1086 unless $from_other_page;
1089 # If $dest exists as a directory, remove conflicting files in it
1090 # rendered from other pages.
1092 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1093 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1094 if (dirname($f) eq $dest) {
1095 unlink("$config{destdir}/$f");
1096 rmdir(dirname("$config{destdir}/$f"));
1102 if (! $clear || $cleared{$page}) {
1103 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1106 foreach my $old (@{$renderedfiles{$page}}) {
1107 delete $destsources{$old};
1109 $renderedfiles{$page}=[$dest];
1112 $destsources{$dest}=$page;
1122 if ($link=~s/^\/+//) {
1130 $l.="/" if length $l;
1133 if (exists $pagesources{$l}) {
1136 elsif (exists $pagecase{lc $l}) {
1137 return $pagecase{lc $l};
1139 } while $cwd=~s{/?[^/]+$}{};
1141 if (length $config{userdir}) {
1142 my $l = "$config{userdir}/".lc($link);
1143 if (exists $pagesources{$l}) {
1146 elsif (exists $pagecase{lc $l}) {
1147 return $pagecase{lc $l};
1151 #print STDERR "warning: page $page, broken link: $link\n";
1155 sub isinlinableimage ($) {
1158 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1161 sub pagetitle ($;$) {
1163 my $unescaped=shift;
1166 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1169 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1177 # support use w/o %config set
1178 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1179 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1185 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1186 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1193 my $cgiurl=$local_cgiurl;
1195 if (exists $params{cgiurl}) {
1196 $cgiurl=$params{cgiurl};
1197 delete $params{cgiurl};
1205 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1208 sub cgiurl_abs (@) {
1210 URI->new_abs(cgiurl(@_), $config{cgiurl});
1216 return $local_url if ! defined $page;
1218 $page=htmlpage($page);
1220 $page=~s/[^\/]+\//..\//g;
1228 return $url unless defined $urlbase && length $urlbase;
1231 URI->new_abs($url, $urlbase)->as_string;
1235 # Work around very innefficient behavior in File::Spec if abs2rel
1236 # is passed two relative paths. It's much faster if paths are
1237 # absolute! (Debian bug #376658; fixed in debian unstable now)
1242 my $ret=File::Spec->abs2rel($path, $base);
1243 $ret=~s/^// if defined $ret;
1247 sub displaytime ($;$$) {
1248 # Plugins can override this function to mark up the time to
1250 my $time=formattime($_[0], $_[1]);
1251 if ($config{html5}) {
1252 return '<time datetime="'.date_3339($_[0]).'"'.
1253 ($_[2] ? ' pubdate="pubdate"' : '').
1254 '>'.$time.'</time>';
1257 return '<span class="date">'.$time.'</span>';
1261 sub formattime ($;$) {
1262 # Plugins can override this function to format the time.
1265 if (! defined $format) {
1266 $format=$config{timeformat};
1269 return strftime_utf8($format, localtime($time));
1272 my $strftime_encoding;
1274 # strftime doesn't know about encodings, so make sure
1275 # its output is properly treated as utf8.
1276 # Note that this does not handle utf-8 in the format string.
1277 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1278 unless defined $strftime_encoding;
1280 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1281 : POSIX::strftime(@_);
1287 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1288 POSIX::setlocale(&POSIX::LC_TIME, "C");
1289 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1290 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1294 sub beautify_urlpath ($) {
1297 # Ensure url is not an empty link, and if necessary,
1298 # add ./ to avoid colon confusion.
1299 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1303 if ($config{usedirs}) {
1304 $url =~ s!/index.$config{htmlext}$!/!;
1319 if (! $destsources{$to}) {
1324 return $config{url}.beautify_urlpath("/".$to);
1327 if (! defined $from) {
1328 my $u = $local_url || '';
1330 return $u.beautify_urlpath("/".$to);
1333 my $link = abs2rel($to, dirname(htmlpage($from)));
1335 return beautify_urlpath($link);
1338 sub isselflink ($$) {
1339 # Plugins can override this function to support special types
1344 return $page eq $link;
1347 sub htmllink ($$$;@) {
1348 my $lpage=shift; # the page doing the linking
1349 my $page=shift; # the page that will contain the link (different for inline)
1356 if (! $opts{forcesubpage}) {
1357 $bestlink=bestlink($lpage, $link);
1360 $bestlink="$lpage/".lc($link);
1364 if (defined $opts{linktext}) {
1365 $linktext=$opts{linktext};
1368 $linktext=pagetitle(basename($link));
1371 return "<span class=\"selflink\">$linktext</span>"
1372 if length $bestlink && isselflink($page, $bestlink) &&
1373 ! defined $opts{anchor};
1375 if (! $destsources{$bestlink}) {
1376 $bestlink=htmlpage($bestlink);
1378 if (! $destsources{$bestlink}) {
1380 if (length $config{cgiurl}) {
1381 $cgilink = "<a href=\"".
1386 )."\" rel=\"nofollow\">?</a>";
1388 return "<span class=\"createlink\">$cgilink$linktext</span>"
1392 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1393 $bestlink=beautify_urlpath($bestlink);
1395 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1396 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1399 if (defined $opts{anchor}) {
1400 $bestlink.="#".$opts{anchor};
1404 foreach my $attr (qw{rel class title}) {
1405 if (defined $opts{$attr}) {
1406 push @attrs, " $attr=\"$opts{$attr}\"";
1410 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1415 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1418 sub openiduser ($) {
1421 if (defined $user && $user =~ m!^https?://! &&
1422 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1425 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1426 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1429 # backcompat with old version
1430 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1431 $display=$oid->display;
1434 # Convert "user.somehost.com" to "user [somehost.com]"
1435 # (also "user.somehost.co.uk")
1436 if ($display !~ /\[/) {
1437 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1439 # Convert "http://somehost.com/user" to "user [somehost.com]".
1440 # (also "https://somehost.com/user/")
1441 if ($display !~ /\[/) {
1442 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1444 $display=~s!^https?://!!; # make sure this is removed
1445 eval q{use CGI 'escapeHTML'};
1447 return escapeHTML($display);
1452 sub htmlize ($$$$) {
1458 my $oneline = $content !~ /\n/;
1460 if (exists $hooks{htmlize}{$type}) {
1461 $content=$hooks{htmlize}{$type}{call}->(
1463 content => $content,
1467 error("htmlization of $type not supported");
1470 run_hooks(sanitize => sub {
1473 destpage => $destpage,
1474 content => $content,
1479 # hack to get rid of enclosing junk added by markdown
1480 # and other htmlizers/sanitizers
1481 $content=~s/^<p>//i;
1482 $content=~s/<\/p>\n*$//i;
1493 run_hooks(linkify => sub {
1496 destpage => $destpage,
1497 content => $content,
1505 our $preprocess_preview=0;
1506 sub preprocess ($$$;$$) {
1507 my $page=shift; # the page the data comes from
1508 my $destpage=shift; # the page the data will appear in (different for inline)
1513 # Using local because it needs to be set within any nested calls
1515 local $preprocess_preview=$preview if defined $preview;
1522 $params="" if ! defined $params;
1524 if (length $escape) {
1525 return "[[$prefix$command $params]]";
1527 elsif (exists $hooks{preprocess}{$command}) {
1528 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1529 # Note: preserve order of params, some plugins may
1530 # consider it significant.
1532 while ($params =~ m{
1533 (?:([-.\w]+)=)? # 1: named parameter key?
1535 """(.*?)""" # 2: triple-quoted value
1537 "([^"]*?)" # 3: single-quoted value
1539 '''(.*?)''' # 4: triple-single-quote
1541 <<([a-zA-Z]+)\n # 5: heredoc start
1542 (.*?)\n\5 # 6: heredoc value
1544 (\S+) # 7: unquoted value
1546 (?:\s+|$) # delimiter to next param
1556 elsif (defined $3) {
1559 elsif (defined $4) {
1562 elsif (defined $7) {
1565 elsif (defined $6) {
1570 push @params, $key, $val;
1573 push @params, $val, '';
1576 if ($preprocessing{$page}++ > 8) {
1577 # Avoid loops of preprocessed pages preprocessing
1578 # other pages that preprocess them, etc.
1579 return "[[!$command <span class=\"error\">".
1580 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1581 $page, $preprocessing{$page}).
1587 $hooks{preprocess}{$command}{call}->(
1590 destpage => $destpage,
1591 preview => $preprocess_preview,
1597 $ret="[[!$command <span class=\"error\">".
1598 gettext("Error").": $error"."</span>]]";
1602 # use void context during scan pass
1604 $hooks{preprocess}{$command}{call}->(
1607 destpage => $destpage,
1608 preview => $preprocess_preview,
1613 $preprocessing{$page}--;
1617 return "[[$prefix$command $params]]";
1622 if ($config{prefix_directives}) {
1625 \[\[(!) # directive open; 2: prefix
1626 ([-\w]+) # 3: command
1627 ( # 4: the parameters..
1628 \s+ # Must have space if parameters present
1630 (?:[-.\w]+=)? # named parameter key?
1632 """.*?""" # triple-quoted value
1634 "[^"]*?" # single-quoted value
1636 '''.*?''' # triple-single-quote
1638 <<([a-zA-Z]+)\n # 5: heredoc start
1639 (?:.*?)\n\5 # heredoc value
1641 [^"\s\]]+ # unquoted value
1643 \s* # whitespace or end
1646 *)? # 0 or more parameters
1647 \]\] # directive closed
1653 \[\[(!?) # directive open; 2: optional prefix
1654 ([-\w]+) # 3: command
1656 ( # 4: the parameters..
1658 (?:[-.\w]+=)? # named parameter key?
1660 """.*?""" # triple-quoted value
1662 "[^"]*?" # single-quoted value
1664 '''.*?''' # triple-single-quote
1666 <<([a-zA-Z]+)\n # 5: heredoc start
1667 (?:.*?)\n\5 # heredoc value
1669 [^"\s\]]+ # unquoted value
1671 \s* # whitespace or end
1674 *) # 0 or more parameters
1675 \]\] # directive closed
1679 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1688 run_hooks(filter => sub {
1689 $content=shift->(page => $page, destpage => $destpage,
1690 content => $content);
1696 sub check_canedit ($$$;$) {
1703 run_hooks(canedit => sub {
1704 return if defined $canedit;
1705 my $ret=shift->($page, $q, $session);
1710 elsif (ref $ret eq 'CODE') {
1711 $ret->() unless $nonfatal;
1714 elsif (defined $ret) {
1715 error($ret) unless $nonfatal;
1720 return defined $canedit ? $canedit : 1;
1723 sub check_content (@) {
1726 return 1 if ! exists $hooks{checkcontent}; # optimisation
1728 if (exists $pagesources{$params{page}}) {
1730 my %old=map { $_ => 1 }
1731 split("\n", readfile(srcfile($pagesources{$params{page}})));
1732 foreach my $line (split("\n", $params{content})) {
1733 push @diff, $line if ! exists $old{$line};
1735 $params{diff}=join("\n", @diff);
1739 run_hooks(checkcontent => sub {
1740 return if defined $ok;
1741 my $ret=shift->(%params);
1746 elsif (ref $ret eq 'CODE') {
1747 $ret->() unless $params{nonfatal};
1750 elsif (defined $ret) {
1751 error($ret) unless $params{nonfatal};
1757 return defined $ok ? $ok : 1;
1760 sub check_canchange (@) {
1762 my $cgi = $params{cgi};
1763 my $session = $params{session};
1764 my @changes = @{$params{changes}};
1767 foreach my $change (@changes) {
1768 # This untaint is safe because we check file_pruned and
1770 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1771 $file=possibly_foolish_untaint($file);
1772 if (! defined $file || ! length $file ||
1773 file_pruned($file)) {
1774 error(gettext("bad file name %s"), $file);
1777 my $type=pagetype($file);
1778 my $page=pagename($file) if defined $type;
1780 if ($change->{action} eq 'add') {
1784 if ($change->{action} eq 'change' ||
1785 $change->{action} eq 'add') {
1786 if (defined $page) {
1787 check_canedit($page, $cgi, $session);
1791 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1792 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1793 check_canedit($file, $cgi, $session);
1798 elsif ($change->{action} eq 'remove') {
1799 # check_canremove tests to see if the file is present
1800 # on disk. This will fail when a single commit adds a
1801 # file and then removes it again. Avoid the problem
1802 # by not testing the removal in such pairs of changes.
1803 # (The add is still tested, just to make sure that
1804 # no data is added to the repo that a web edit
1806 next if $newfiles{$file};
1808 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1809 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1810 check_canedit(defined $page ? $page : $file, $cgi, $session);
1815 error "unknown action ".$change->{action};
1818 error sprintf(gettext("you are not allowed to change %s"), $file);
1826 # Take an exclusive lock on the wiki to prevent multiple concurrent
1827 # run issues. The lock will be dropped on program exit.
1828 if (! -d $config{wikistatedir}) {
1829 mkdir($config{wikistatedir});
1831 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1832 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1833 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1834 debug("failed to get lock; waiting...");
1835 if (! flock($wikilock, LOCK_EX)) {
1836 error("failed to get lock");
1843 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1844 return close($wikilock) if $wikilock;
1850 sub commit_hook_enabled () {
1851 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1852 error("cannot write to $config{wikistatedir}/commitlock: $!");
1853 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1854 close($commitlock) || error("failed closing commitlock: $!");
1857 close($commitlock) || error("failed closing commitlock: $!");
1861 sub disable_commit_hook () {
1862 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1863 error("cannot write to $config{wikistatedir}/commitlock: $!");
1864 if (! flock($commitlock, 2)) { # LOCK_EX
1865 error("failed to get commit lock");
1870 sub enable_commit_hook () {
1871 return close($commitlock) if $commitlock;
1876 %oldrenderedfiles=%pagectime=();
1877 my $rebuild=$config{rebuild};
1879 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1880 %destsources=%renderedfiles=%pagecase=%pagestate=
1881 %depends_simple=%typedlinks=%oldtypedlinks=();
1884 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1885 if (-e "$config{wikistatedir}/index") {
1886 system("ikiwiki-transition", "indexdb", $config{srcdir});
1887 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1890 # gettime on first build
1891 $config{gettime}=1 unless defined $config{gettime};
1896 my $index=Storable::fd_retrieve($in);
1897 if (! defined $index) {
1902 if (exists $index->{version} && ! ref $index->{version}) {
1903 $pages=$index->{page};
1904 %wikistate=%{$index->{state}};
1905 # Handle plugins that got disabled by loading a new setup.
1906 if (exists $config{setupfile}) {
1907 require IkiWiki::Setup;
1908 IkiWiki::Setup::disabled_plugins(
1909 grep { ! $loaded_plugins{$_} } keys %wikistate);
1917 foreach my $src (keys %$pages) {
1918 my $d=$pages->{$src};
1920 if (exists $d->{page} && ! $rebuild) {
1924 $page=pagename($src);
1926 $pagectime{$page}=$d->{ctime};
1927 $pagesources{$page}=$src;
1929 $pagemtime{$page}=$d->{mtime};
1930 $renderedfiles{$page}=$d->{dest};
1931 if (exists $d->{links} && ref $d->{links}) {
1932 $links{$page}=$d->{links};
1933 $oldlinks{$page}=[@{$d->{links}}];
1935 if (ref $d->{depends_simple} eq 'ARRAY') {
1937 $depends_simple{$page}={
1938 map { $_ => 1 } @{$d->{depends_simple}}
1941 elsif (exists $d->{depends_simple}) {
1942 $depends_simple{$page}=$d->{depends_simple};
1944 if (exists $d->{dependslist}) {
1947 map { $_ => $DEPEND_CONTENT }
1948 @{$d->{dependslist}}
1951 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1953 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1955 elsif (exists $d->{depends}) {
1956 $depends{$page}=$d->{depends};
1958 if (exists $d->{state}) {
1959 $pagestate{$page}=$d->{state};
1961 if (exists $d->{typedlinks}) {
1962 $typedlinks{$page}=$d->{typedlinks};
1964 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1965 next unless %$links;
1966 $oldtypedlinks{$page}{$type} = {%$links};
1970 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1972 foreach my $page (keys %pagesources) {
1973 $pagecase{lc $page}=$page;
1975 foreach my $page (keys %renderedfiles) {
1976 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1978 $lastrev=$index->{lastrev};
1979 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1984 run_hooks(savestate => sub { shift->() });
1986 my @plugins=keys %loaded_plugins;
1988 if (! -d $config{wikistatedir}) {
1989 mkdir($config{wikistatedir});
1991 my $newfile="$config{wikistatedir}/indexdb.new";
1992 my $cleanup = sub { unlink($newfile) };
1993 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1996 foreach my $page (keys %pagemtime) {
1997 next unless $pagemtime{$page};
1998 my $src=$pagesources{$page};
2000 $index{page}{$src}={
2002 ctime => $pagectime{$page},
2003 mtime => $pagemtime{$page},
2004 dest => $renderedfiles{$page},
2005 links => $links{$page},
2008 if (exists $depends{$page}) {
2009 $index{page}{$src}{depends} = $depends{$page};
2012 if (exists $depends_simple{$page}) {
2013 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2016 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2017 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2020 if (exists $pagestate{$page}) {
2021 $index{page}{$src}{state}=$pagestate{$page};
2026 foreach my $id (@plugins) {
2027 $index{state}{$id}={}; # used to detect disabled plugins
2028 foreach my $key (keys %{$wikistate{$id}}) {
2029 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2033 $index{lastrev}=$lastrev;
2034 $index{underlayfiles}=\@underlayfiles;
2036 $index{version}="3";
2037 my $ret=Storable::nstore_fd(\%index, $out);
2038 return if ! defined $ret || ! $ret;
2039 close $out || error("failed saving to $newfile: $!", $cleanup);
2040 rename($newfile, "$config{wikistatedir}/indexdb") ||
2041 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2046 sub template_file ($) {
2049 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2051 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2052 $template=srcfile($pagesources{$tpage}, 1);
2056 $template=srcfile($tpage, 1);
2059 if (defined $template) {
2060 return $template, $tpage, 1 if wantarray;
2064 $name=~s:/::; # avoid path traversal
2065 foreach my $dir ($config{templatedir},
2066 "$installdir/share/ikiwiki/templates") {
2067 if (-e "$dir/$name") {
2068 $template="$dir/$name";
2072 if (defined $template) {
2073 return $template, $tpage if wantarray;
2081 sub template_depends ($$;@) {
2085 my ($filename, $tpage, $untrusted)=template_file($name);
2086 if (! defined $filename) {
2087 error(sprintf(gettext("template %s not found"), $name))
2090 if (defined $page && defined $tpage) {
2091 add_depends($page, $tpage);
2096 my $text_ref = shift;
2097 ${$text_ref} = decode_utf8(${$text_ref});
2098 run_hooks(readtemplate => sub {
2099 ${$text_ref} = shift->(
2102 content => ${$text_ref},
2103 untrusted => $untrusted,
2107 loop_context_vars => 1,
2108 die_on_bad_params => 0,
2109 parent_global_vars => 1,
2110 filename => $filename,
2112 ($untrusted ? (no_includes => 1) : ()),
2114 return @opts if wantarray;
2116 require HTML::Template;
2117 return HTML::Template->new(@opts);
2120 sub template ($;@) {
2121 template_depends(shift, undef, @_);
2124 sub templateactions ($$) {
2130 run_hooks(pageactions => sub {
2131 push @actions, map { { action => $_ } }
2132 grep { defined } shift->(page => $page);
2134 $template->param(actions => \@actions);
2136 if ($config{cgiurl} && exists $hooks{auth}) {
2137 $template->param(prefsurl => cgiurl(do => "prefs"));
2141 if ($have_actions || @actions) {
2142 $template->param(have_actions => 1);
2149 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2150 error 'hook requires type, call, and id parameters';
2153 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2155 $hooks{$param{type}}{$param{id}}=\%param;
2159 sub run_hooks ($$) {
2160 # Calls the given sub for each hook of the given type,
2161 # passing it the hook function to call.
2165 if (exists $hooks{$type}) {
2166 my (@first, @middle, @last);
2167 foreach my $id (keys %{$hooks{$type}}) {
2168 if ($hooks{$type}{$id}{first}) {
2171 elsif ($hooks{$type}{$id}{last}) {
2178 foreach my $id (@first, @middle, @last) {
2179 $sub->($hooks{$type}{$id}{call});
2187 $hooks{rcs}{rcs_update}{call}->(@_);
2190 sub rcs_prepedit ($) {
2191 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2194 sub rcs_commit (@) {
2195 $hooks{rcs}{rcs_commit}{call}->(@_);
2198 sub rcs_commit_staged (@) {
2199 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2203 $hooks{rcs}{rcs_add}{call}->(@_);
2206 sub rcs_remove ($) {
2207 $hooks{rcs}{rcs_remove}{call}->(@_);
2210 sub rcs_rename ($$) {
2211 $hooks{rcs}{rcs_rename}{call}->(@_);
2214 sub rcs_recentchanges ($) {
2215 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2218 sub rcs_diff ($;$) {
2219 $hooks{rcs}{rcs_diff}{call}->(@_);
2222 sub rcs_getctime ($) {
2223 $hooks{rcs}{rcs_getctime}{call}->(@_);
2226 sub rcs_getmtime ($) {
2227 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2230 sub rcs_receive () {
2231 $hooks{rcs}{rcs_receive}{call}->();
2234 sub add_depends ($$;$) {
2237 my $deptype=shift || $DEPEND_CONTENT;
2239 # Is the pagespec a simple page name?
2240 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2241 $pagespec !~ /[\s*?()!]/) {
2242 $depends_simple{$page}{lc $pagespec} |= $deptype;
2246 # Add explicit dependencies for influences.
2247 my $sub=pagespec_translate($pagespec);
2248 return unless defined $sub;
2249 foreach my $p (keys %pagesources) {
2250 my $r=$sub->($p, location => $page);
2251 my $i=$r->influences;
2252 my $static=$r->influences_static;
2253 foreach my $k (keys %$i) {
2254 next unless $r || $static || $k eq $page;
2255 $depends_simple{$page}{lc $k} |= $i->{$k};
2260 $depends{$page}{$pagespec} |= $deptype;
2266 foreach my $type (@_) {
2267 if ($type eq 'presence') {
2268 $deptype |= $DEPEND_PRESENCE;
2270 elsif ($type eq 'links') {
2271 $deptype |= $DEPEND_LINKS;
2273 elsif ($type eq 'content') {
2274 $deptype |= $DEPEND_CONTENT;
2280 my $file_prune_regexp;
2281 sub file_pruned ($) {
2284 if (defined $config{include} && length $config{include}) {
2285 return 0 if $file =~ m/$config{include}/;
2288 if (! defined $file_prune_regexp) {
2289 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2290 $file_prune_regexp=qr/$file_prune_regexp/;
2292 return $file =~ m/$file_prune_regexp/;
2295 sub define_gettext () {
2296 # If translation is needed, redefine the gettext function to do it.
2297 # Otherwise, it becomes a quick no-op.
2300 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2301 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2302 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2304 $gettext_obj=eval q{
2305 use Locale::gettext q{textdomain};
2306 Locale::gettext->domain('ikiwiki')
2311 no warnings 'redefine';
2313 $getobj->() if $getobj;
2315 $gettext_obj->get(shift);
2322 $getobj->() if $getobj;
2324 $gettext_obj->nget(@_);
2327 return ($_[2] == 1 ? $_[0] : $_[1])
2345 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2349 # Injects a new function into the symbol table to replace an
2350 # exported function.
2353 # This is deep ugly perl foo, beware.
2356 if (! defined $params{parent}) {
2357 $params{parent}='::';
2358 $params{old}=\&{$params{name}};
2359 $params{name}=~s/.*:://;
2361 my $parent=$params{parent};
2362 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2363 $ns = $params{parent} . $ns;
2364 inject(%params, parent => $ns) unless $ns eq '::main::';
2365 *{$ns . $params{name}} = $params{call}
2366 if exists ${$ns}{$params{name}} &&
2367 \&{${$ns}{$params{name}}} == $params{old};
2373 sub add_link ($$;$) {
2378 push @{$links{$page}}, $link
2379 unless grep { $_ eq $link } @{$links{$page}};
2381 if (defined $type) {
2382 $typedlinks{$page}{$type}{$link} = 1;
2386 sub add_autofile ($$$) {
2389 my $generator=shift;
2391 $autofiles{$file}{plugin}=$plugin;
2392 $autofiles{$file}{generator}=$generator;
2396 return LWP::UserAgent->new(
2397 cookie_jar => $config{cookiejar},
2398 env_proxy => 1, # respect proxy env vars
2399 agent => $config{useragent},
2403 sub sortspec_translate ($$) {
2405 my $reverse = shift;
2411 (-?) # group 1: perhaps negated
2414 \w+\([^\)]*\) # command(params)
2416 [^\s]+ # or anything else
2424 if ($word =~ m/^(\w+)\((.*)\)$/) {
2425 # command with parameters
2429 elsif ($word !~ m/^\w+$/) {
2430 error(sprintf(gettext("invalid sort type %s"), $word));
2441 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2442 if (defined $params) {
2443 push @data, $params;
2444 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2447 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2451 error(sprintf(gettext("unknown sort type %s"), $word));
2455 if (! length $code) {
2456 # undefined sorting method... sort arbitrarily
2465 return eval 'sub { '.$code.' }';
2468 sub pagespec_translate ($) {
2471 # Convert spec to perl code.
2475 \s* # ignore whitespace
2476 ( # 1: match a single word
2483 \w+\([^\)]*\) # command(params)
2485 [^\s()]+ # any other text
2487 \s* # ignore whitespace
2490 if (lc $word eq 'and') {
2493 elsif (lc $word eq 'or') {
2496 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2499 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2500 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2502 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2505 push @data, qq{unknown function in pagespec "$word"};
2506 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2511 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2515 if (! length $code) {
2516 $code="IkiWiki::FailReason->new('empty pagespec')";
2520 return eval 'sub { my $page=shift; '.$code.' }';
2523 sub pagespec_match ($$;@) {
2528 # Backwards compatability with old calling convention.
2530 unshift @params, 'location';
2533 my $sub=pagespec_translate($spec);
2534 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2536 return $sub->($page, @params);
2539 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2541 # Not exported yet, but could be in future if it is generally useful.
2542 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2543 # which is "more internal".
2544 sub sort_pages ($$;@) {
2548 $sort = sortspec_translate($sort, $params{reverse});
2549 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2552 sub pagespec_match_list ($$;@) {
2557 # Backwards compatability with old calling convention.
2559 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2560 $params{list}=$page;
2561 $page=$params{location}; # ugh!
2564 my $sub=pagespec_translate($pagespec);
2565 error "syntax error in pagespec \"$pagespec\""
2567 my $sort=sortspec_translate($params{sort}, $params{reverse})
2568 if defined $params{sort};
2571 if (exists $params{list}) {
2572 @candidates=exists $params{filter}
2573 ? grep { ! $params{filter}->($_) } @{$params{list}}
2577 @candidates=exists $params{filter}
2578 ? grep { ! $params{filter}->($_) } keys %pagesources
2579 : keys %pagesources;
2582 # clear params, remainder is passed to pagespec
2583 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2584 my $num=$params{num};
2585 delete @params{qw{num deptype reverse sort filter list}};
2587 # when only the top matches will be returned, it's efficient to
2588 # sort before matching to pagespec,
2589 if (defined $num && defined $sort) {
2590 @candidates=IkiWiki::SortSpec::sort_pages(
2591 $sort, @candidates);
2597 my $accum=IkiWiki::SuccessReason->new();
2598 foreach my $p (@candidates) {
2599 my $r=$sub->($p, %params, location => $page);
2600 error(sprintf(gettext("cannot match pages: %s"), $r))
2601 if $r->isa("IkiWiki::ErrorReason");
2602 unless ($r || $r->influences_static) {
2603 $r->remove_influence($p);
2608 last if defined $num && ++$count == $num;
2612 # Add simple dependencies for accumulated influences.
2613 my $i=$accum->influences;
2614 foreach my $k (keys %$i) {
2615 $depends_simple{$page}{lc $k} |= $i->{$k};
2618 # when all matches will be returned, it's efficient to
2619 # sort after matching
2620 if (! defined $num && defined $sort) {
2621 return IkiWiki::SortSpec::sort_pages(
2629 sub pagespec_valid ($) {
2632 return defined pagespec_translate($spec);
2636 my $re=quotemeta(shift);
2642 package IkiWiki::FailReason;
2645 '""' => sub { $_[0][0] },
2647 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2648 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2649 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2653 our @ISA = 'IkiWiki::SuccessReason';
2655 package IkiWiki::SuccessReason;
2657 # A blessed array-ref:
2659 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2661 # - if absent or false, the influences of this evaluation are "static",
2662 # see the influences_static method
2663 # - if true, they are dynamic (not static)
2664 # [1]{any other key}:
2665 # the dependency types of influences, as returned by the influences method
2668 # in string context, it's the human-readable reason
2669 '""' => sub { $_[0][0] },
2670 # in boolean context, SuccessReason is 1 and FailReason is 0
2672 # negating a result gives the opposite result with the same influences
2673 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2674 # A & B = (A ? B : A) with the influences of both
2675 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2676 # A | B = (A ? A : B) with the influences of both
2677 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2681 # SuccessReason->new("human-readable reason", page => deptype, ...)
2686 return bless [$value, {@_}], $class;
2689 # influences(): return a reference to a copy of the hash
2690 # { page => dependency type } describing the pages that indirectly influenced
2691 # this result, but would not cause a dependency through ikiwiki's core
2694 # See [[todo/dependency_types]] for extensive discussion of what this means.
2696 # influences(page => deptype, ...): remove all influences, replace them
2697 # with the arguments, and return a reference to a copy of the new influences.
2701 $this->[1]={@_} if @_;
2702 my %i=%{$this->[1]};
2707 # True if this result has the same influences whichever page it matches,
2708 # For instance, whether bar matches backlink(foo) is influenced only by
2709 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2710 # which does not mention bar anywhere.
2712 # False if this result would have different influences when matching
2713 # different pages. For instance, when testing whether link(foo) matches bar,
2714 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2715 # bar's links could change the outcome; so its influences are not the same
2716 # as when testing whether link(foo) matches baz.
2718 # Static influences are one of the things that make pagespec_match_list
2719 # more efficient than repeated calls to pagespec_match.
2721 sub influences_static {
2722 return ! $_[0][1]->{""};
2725 # Change the influences of $this to be the influences of "$this & $other"
2726 # or "$this | $other".
2728 # If both $this and $other are either successful or have influences,
2729 # or this is an "or" operation, the result has all the influences from
2730 # either of the arguments. It has dynamic influences if either argument
2731 # has dynamic influences.
2733 # If this is an "and" operation, and at least one argument is a
2734 # FailReason with no influences, the result has no influences, and they
2735 # are not dynamic. For instance, link(foo) matching bar is influenced
2736 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2737 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2738 # bar, because it would be false however often you edit bar.
2740 sub merge_influences {
2745 # This "if" is odd because it needs to avoid negating $this
2746 # or $other, which would alter the objects in-place. Be careful.
2747 if (! $anded || (($this || %{$this->[1]}) &&
2748 ($other || %{$other->[1]}))) {
2749 foreach my $influence (keys %{$other->[1]}) {
2750 $this->[1]{$influence} |= $other->[1]{$influence};
2759 # Change $this so it is not considered to be influenced by $torm.
2761 sub remove_influence {
2765 delete $this->[1]{$torm};
2768 package IkiWiki::ErrorReason;
2770 our @ISA = 'IkiWiki::FailReason';
2772 package IkiWiki::PageSpec;
2778 if ($path =~ m!^\.(/|$)!) {
2780 $from=~s#/?[^/]+$## if defined $from;
2782 $path="$from/$path" if defined $from && length $from;
2786 $path = "" unless defined $path;
2795 sub match_glob ($$;@) {
2800 $glob=derel($glob, $params{location});
2802 # Instead of converting the glob to a regex every time,
2803 # cache the compiled regex to save time.
2804 my $re=$glob_cache{$glob};
2805 unless (defined $re) {
2806 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2809 if (! IkiWiki::isinternal($page) || $params{internal}) {
2810 return IkiWiki::SuccessReason->new("$glob matches $page");
2813 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2817 return IkiWiki::FailReason->new("$glob does not match $page");
2821 sub match_internal ($$;@) {
2822 return match_glob(shift, shift, @_, internal => 1)
2825 sub match_page ($$;@) {
2827 my $match=match_glob($page, shift, @_);
2829 my $source=exists $IkiWiki::pagesources{$page} ?
2830 $IkiWiki::pagesources{$page} :
2831 $IkiWiki::delpagesources{$page};
2832 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2833 if (! defined $type) {
2834 return IkiWiki::FailReason->new("$page is not a page");
2840 sub match_link ($$;@) {
2845 $link=derel($link, $params{location});
2846 my $from=exists $params{location} ? $params{location} : '';
2847 my $linktype=$params{linktype};
2849 if (defined $linktype) {
2850 $qualifier=" with type $linktype";
2853 my $links = $IkiWiki::links{$page};
2854 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2855 unless $links && @{$links};
2856 my $bestlink = IkiWiki::bestlink($from, $link);
2857 foreach my $p (@{$links}) {
2858 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2860 if (length $bestlink) {
2861 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2862 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2866 if (match_glob($p, $link, %params)) {
2867 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2869 my ($p_rel)=$p=~/^\/?(.*)/;
2871 if (match_glob($p_rel, $link, %params)) {
2872 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2876 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2879 sub match_backlink ($$;@) {
2883 if ($testpage eq '.') {
2884 $testpage = $params{'location'}
2886 my $ret=match_link($testpage, $page, @_);
2887 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2891 sub match_created_before ($$;@) {
2896 $testpage=derel($testpage, $params{location});
2898 if (exists $IkiWiki::pagectime{$testpage}) {
2899 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2900 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2903 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2907 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2911 sub match_created_after ($$;@) {
2916 $testpage=derel($testpage, $params{location});
2918 if (exists $IkiWiki::pagectime{$testpage}) {
2919 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2920 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2923 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2927 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2931 sub match_creation_day ($$;@) {
2934 if ($d !~ /^\d+$/) {
2935 return IkiWiki::ErrorReason->new("invalid day $d");
2937 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2938 return IkiWiki::SuccessReason->new('creation_day matched');
2941 return IkiWiki::FailReason->new('creation_day did not match');
2945 sub match_creation_month ($$;@) {
2948 if ($m !~ /^\d+$/) {
2949 return IkiWiki::ErrorReason->new("invalid month $m");
2951 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2952 return IkiWiki::SuccessReason->new('creation_month matched');
2955 return IkiWiki::FailReason->new('creation_month did not match');
2959 sub match_creation_year ($$;@) {
2962 if ($y !~ /^\d+$/) {
2963 return IkiWiki::ErrorReason->new("invalid year $y");
2965 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2966 return IkiWiki::SuccessReason->new('creation_year matched');
2969 return IkiWiki::FailReason->new('creation_year did not match');
2973 sub match_user ($$;@) {
2978 if (! exists $params{user}) {
2979 return IkiWiki::ErrorReason->new("no user specified");
2982 my $regexp=IkiWiki::glob2re($user);
2984 if (defined $params{user} && $params{user}=~$regexp) {
2985 return IkiWiki::SuccessReason->new("user is $user");
2987 elsif (! defined $params{user}) {
2988 return IkiWiki::FailReason->new("not logged in");
2991 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2995 sub match_admin ($$;@) {
3000 if (! exists $params{user}) {
3001 return IkiWiki::ErrorReason->new("no user specified");
3004 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3005 return IkiWiki::SuccessReason->new("user is an admin");
3007 elsif (! defined $params{user}) {
3008 return IkiWiki::FailReason->new("not logged in");
3011 return IkiWiki::FailReason->new("user is not an admin");
3015 sub match_ip ($$;@) {
3020 if (! exists $params{ip}) {
3021 return IkiWiki::ErrorReason->new("no IP specified");
3024 my $regexp=IkiWiki::glob2re(lc $ip);
3026 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3027 return IkiWiki::SuccessReason->new("IP is $ip");
3030 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3034 package IkiWiki::SortSpec;
3036 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3037 # are easily available in this namespace, for cmp functions to use them.
3044 IkiWiki::pagetitle(IkiWiki::basename($a))
3046 IkiWiki::pagetitle(IkiWiki::basename($b))
3049 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3050 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3051 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }