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 example => "/var/www/wiki/ikiwiki.cgi",
115 description => "filename of cgi wrapper to generate",
122 description => "mode for cgi_wrapper (can safely be made suid)",
126 cgi_overload_delay => {
130 description => "number of seconds to delay CGI requests when overloaded",
134 cgi_overload_message => {
137 example => "Please wait",
138 description => "message to display when overloaded (may contain html)",
142 only_committed_changes => {
145 description => "enable optimization of only refreshing committed changes?",
152 description => "rcs backend to use",
153 safe => 0, # don't allow overriding
158 default => [qw{mdwn link inline meta htmlscrubber passwordauth
159 openid signinedit lockedit conditional
160 recentchanges parentlinks editpage
162 description => "plugins to enable by default",
169 description => "plugins to add to the default configuration",
176 description => "plugins to disable",
182 default => "$installdir/share/ikiwiki/templates",
183 description => "additional directory to search for template files",
190 default => "$installdir/share/ikiwiki/basewiki",
191 description => "base wiki source location",
198 default => "$installdir/share/ikiwiki",
199 description => "parent directory containing additional underlays",
206 description => "wrappers to generate",
213 description => "additional underlays to use",
220 description => "display verbose messages?",
227 description => "log to syslog?",
234 description => "create output files named page/index.html?",
235 safe => 0, # changing requires manual transition
238 prefix_directives => {
241 description => "use '!'-prefixed preprocessor directives?",
242 safe => 0, # changing requires manual transition
248 description => "use page/index.mdwn source files",
255 description => "enable Discussion pages?",
261 default => gettext("Discussion"),
262 description => "name of Discussion pages",
269 description => "generate HTML5?",
277 description => "only send cookies over SSL connections?",
285 description => "extension to use for new pages",
286 safe => 0, # not sanitized
292 description => "extension to use for html files",
293 safe => 0, # not sanitized
299 description => "strftime format string to display date",
307 example => "en_US.UTF-8",
308 description => "UTF-8 locale to use",
317 description => "put user pages below specified page",
324 description => "how many backlinks to show before hiding excess (0 to show all)",
331 description => "attempt to hardlink source files? (optimisation for large files)",
333 safe => 0, # paranoia
339 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
341 safe => 0, # paranoia
346 example => "ikiwiki",
347 description => "group for wrappers to run in",
349 safe => 0, # paranoia
355 example => "$ENV{HOME}/.ikiwiki/",
356 description => "extra library and plugin directory",
358 safe => 0, # directory
364 description => "environment variables",
365 safe => 0, # paranoia
371 example => "US/Eastern",
372 description => "time zone name",
379 example => '^\.htaccess$',
380 description => "regexp of normally excluded files to include",
388 example => '^(*\.private|Makefile)$',
389 description => "regexp of files that should be skipped",
394 wiki_file_prune_regexps => {
396 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
397 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
398 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
399 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
400 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
401 description => "regexps of source files to ignore",
407 description => "specifies the characters that are allowed in source filenames",
408 default => "-[:alnum:]+/.:_",
412 wiki_file_regexp => {
414 description => "regexp of legal source files",
418 web_commit_regexp => {
420 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
421 description => "regexp to parse web commits from logs",
428 description => "run as a cgi",
432 cgi_disable_uploads => {
435 description => "whether CGI should accept file uploads",
442 description => "run as a post-commit hook",
449 description => "running in rebuild mode",
456 description => "running in setup mode",
463 description => "running in clean mode",
470 description => "running in refresh mode",
477 description => "running in receive test mode",
481 wrapper_background_command => {
484 description => "background shell command to run",
490 description => "running in gettime mode",
497 description => "running in w3mmode",
504 description => "path to the .ikiwiki directory holding ikiwiki state",
511 description => "path to setup file",
518 description => "perl class to use to dump setup file",
522 allow_symlinks_before_srcdir => {
525 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
531 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
532 description => "cookie control",
533 safe => 0, # hooks into perl module internals
539 example => "Wget/1.13.4 (linux-gnu)",
540 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
546 sub defaultconfig () {
549 foreach my $key (keys %s) {
550 push @ret, $key, $s{$key}->{default};
555 # URL to top of wiki as a path starting with /, valid from any wiki page or
556 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
558 # URL to CGI script, similar to $local_url
562 # locale stuff; avoid LC_ALL since it overrides everything
563 if (defined $ENV{LC_ALL}) {
564 $ENV{LANG} = $ENV{LC_ALL};
567 if (defined $config{locale}) {
568 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
569 $ENV{LANG}=$config{locale};
574 if (! defined $config{wiki_file_regexp}) {
575 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
578 if (ref $config{ENV} eq 'HASH') {
579 foreach my $val (keys %{$config{ENV}}) {
580 $ENV{$val}=$config{ENV}{$val};
583 if (defined $config{timezone} && length $config{timezone}) {
584 $ENV{TZ}=$config{timezone};
587 $config{timezone}=$ENV{TZ};
590 if ($config{w3mmode}) {
591 eval q{use Cwd q{abs_path}};
593 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
594 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
595 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
596 unless $config{cgiurl} =~ m!file:///!;
597 $config{url}="file://".$config{destdir};
600 if ($config{cgi} && ! length $config{url}) {
601 error(gettext("Must specify url to wiki with --url when using --cgi"));
604 if (defined $config{url} && length $config{url}) {
606 my $baseurl = URI->new($config{url});
608 $local_url = $baseurl->path . "/";
609 $local_cgiurl = undef;
611 if (length $config{cgiurl}) {
612 my $cgiurl = URI->new($config{cgiurl});
614 $local_cgiurl = $cgiurl->path;
616 if ($cgiurl->scheme eq 'https' &&
617 $baseurl->scheme eq 'http') {
618 # We assume that the same content is available
619 # over both http and https, because if it
620 # wasn't, accessing the static content
621 # from the CGI would be mixed-content,
622 # which would be a security flaw.
624 if ($cgiurl->authority ne $baseurl->authority) {
625 # use protocol-relative URL for
627 $local_url = "$config{url}/";
628 $local_url =~ s{^http://}{//};
630 # else use host-relative URL for static content
632 # either way, CGI needs to be absolute
633 $local_cgiurl = $config{cgiurl};
635 elsif ($cgiurl->scheme ne $baseurl->scheme) {
636 # too far apart, fall back to absolute URLs
637 $local_url = "$config{url}/";
638 $local_cgiurl = $config{cgiurl};
640 elsif ($cgiurl->authority ne $baseurl->authority) {
641 # slightly too far apart, fall back to
642 # protocol-relative URLs
643 $local_url = "$config{url}/";
644 $local_url =~ s{^https?://}{//};
645 $local_cgiurl = $config{cgiurl};
646 $local_cgiurl =~ s{^https?://}{//};
648 # else keep host-relative URLs
651 $local_url =~ s{//$}{/};
654 $local_cgiurl = $config{cgiurl};
657 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
658 unless exists $config{wikistatedir} && defined $config{wikistatedir};
660 if (defined $config{umask}) {
661 my $u = possibly_foolish_untaint($config{umask});
663 if ($u =~ m/^\d+$/) {
666 elsif ($u eq 'private') {
669 elsif ($u eq 'group') {
672 elsif ($u eq 'public') {
676 error(sprintf(gettext("unsupported umask setting %s"), $u));
680 run_hooks(checkconfig => sub { shift->() });
688 foreach my $dir (@INC, $config{libdir}) {
689 next unless defined $dir && length $dir;
690 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
691 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
695 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
696 next unless defined $dir && length $dir;
697 foreach my $file (glob("$dir/plugins/*")) {
698 $ret{basename($file)}=1 if -x $file;
706 if (defined $config{libdir} && length $config{libdir}) {
707 unshift @INC, possibly_foolish_untaint($config{libdir});
710 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
715 if (exists $hooks{rcs}) {
716 error(gettext("cannot use multiple rcs plugins"));
718 loadplugin($config{rcs});
720 if (! exists $hooks{rcs}) {
724 run_hooks(getopt => sub { shift->() });
725 if (grep /^-/, @ARGV) {
726 print STDERR "Unknown option (or missing parameter): $_\n"
727 foreach grep /^-/, @ARGV;
734 sub loadplugin ($;$) {
738 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
740 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
741 "$installdir/lib/ikiwiki") {
742 if (defined $dir && -x "$dir/plugins/$plugin") {
743 eval { require IkiWiki::Plugin::external };
746 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
748 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
749 $loaded_plugins{$plugin}=1;
754 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
757 error("Failed to load plugin $mod: $@");
759 $loaded_plugins{$plugin}=1;
766 log_message('err' => $message) if $config{syslog};
767 if (defined $cleaner) {
774 return unless $config{verbose};
775 return log_message(debug => @_);
780 sub log_message ($$) {
783 if ($config{syslog}) {
786 Sys::Syslog::setlogsock('unix');
787 Sys::Syslog::openlog('ikiwiki', '', 'user');
791 # keep a copy to avoid editing the original config repeatedly
792 my $wikiname = $config{wikiname};
793 utf8::encode($wikiname);
794 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
797 print STDERR "failed to syslog: $@" unless $log_failed;
803 elsif (! $config{cgi}) {
807 return print STDERR "@_\n";
811 sub possibly_foolish_untaint ($) {
813 my ($untainted)=$tainted=~/(.*)/s;
833 return exists $pagesources{$page} &&
834 $pagesources{$page} =~ /\._([^.]+)$/;
840 if ($file =~ /\.([^.]+)$/) {
841 return $1 if exists $hooks{htmlize}{$1};
843 my $base=basename($file);
844 if (exists $hooks{htmlize}{$base} &&
845 $hooks{htmlize}{$base}{noextension}) {
856 if (exists $pagename_cache{$file}) {
857 return $pagename_cache{$file};
860 my $type=pagetype($file);
862 $page=~s/\Q.$type\E*$//
863 if defined $type && !$hooks{htmlize}{$type}{keepextension}
864 && !$hooks{htmlize}{$type}{noextension};
865 if ($config{indexpages} && $page=~/(.*)\/index$/) {
869 $pagename_cache{$file} = $page;
873 sub newpagefile ($$) {
877 if (! $config{indexpages} || $page eq 'index') {
878 return $page.".".$type;
881 return $page."/index.".$type;
885 sub targetpage ($$;$) {
890 if (defined $filename) {
891 return $page."/".$filename.".".$ext;
893 elsif (! $config{usedirs} || $page eq 'index') {
894 return $page.".".$ext;
897 return $page."/index.".$ext;
904 return targetpage($page, $config{htmlext});
911 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
912 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
913 return "$dir/$file", stat(_) if -e "$dir/$file";
915 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
920 return (srcfile_stat(@_))[0];
923 sub add_literal_underlay ($) {
926 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
927 unshift @{$config{underlaydirs}}, $dir;
931 sub add_underlay ($) {
935 $dir="$config{underlaydirbase}/$dir";
938 add_literal_underlay($dir);
939 # why does it return 1? we just don't know
943 sub readfile ($;$$) {
949 error("cannot read a symlink ($file)");
953 open (my $in, "<", $file) || error("failed to read $file: $!");
954 binmode($in) if ($binary);
955 return \*$in if $wantfd;
957 # check for invalid utf-8, and toss it back to avoid crashes
958 if (! utf8::valid($ret)) {
959 $ret=encode_utf8($ret);
961 close $in || error("failed to read $file: $!");
965 sub prep_writefile ($$) {
970 while (length $test) {
971 if (-l "$destdir/$test") {
972 error("cannot write to a symlink ($test)");
974 if (-f _ && $test ne $file) {
975 # Remove conflicting file.
976 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
977 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
979 unlink("$destdir/$test");
985 $test=dirname($test);
988 my $dir=dirname("$destdir/$file");
991 foreach my $s (split(m!/+!, $dir)) {
994 mkdir($d) || error("failed to create directory $d: $!");
1002 sub writefile ($$$;$$) {
1003 my $file=shift; # can include subdirs
1004 my $destdir=shift; # directory to put file in
1009 prep_writefile($file, $destdir);
1011 my $newfile="$destdir/$file.ikiwiki-new";
1013 error("cannot write to a symlink ($newfile)");
1016 my $cleanup = sub { unlink($newfile) };
1017 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1018 binmode($out) if ($binary);
1020 $writer->(\*$out, $cleanup);
1023 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1025 close $out || error("failed saving $newfile: $!", $cleanup);
1026 rename($newfile, "$destdir/$file") ||
1027 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1033 sub will_render ($$;$) {
1038 # Important security check for independently created files.
1039 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1040 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1041 my $from_other_page=0;
1042 # Expensive, but rarely runs.
1043 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1046 dirname($_) eq $dest
1047 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1053 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1054 unless $from_other_page;
1057 # If $dest exists as a directory, remove conflicting files in it
1058 # rendered from other pages.
1060 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1061 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1062 if (dirname($f) eq $dest) {
1063 unlink("$config{destdir}/$f");
1064 rmdir(dirname("$config{destdir}/$f"));
1070 if (! $clear || $cleared{$page}) {
1071 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1074 foreach my $old (@{$renderedfiles{$page}}) {
1075 delete $destsources{$old};
1077 $renderedfiles{$page}=[$dest];
1080 $destsources{$dest}=$page;
1090 if ($link=~s/^\/+//) {
1098 $l.="/" if length $l;
1101 if (exists $pagesources{$l}) {
1104 elsif (exists $pagecase{lc $l}) {
1105 return $pagecase{lc $l};
1107 } while $cwd=~s{/?[^/]+$}{};
1109 if (length $config{userdir}) {
1110 my $l = "$config{userdir}/".lc($link);
1111 if (exists $pagesources{$l}) {
1114 elsif (exists $pagecase{lc $l}) {
1115 return $pagecase{lc $l};
1119 #print STDERR "warning: page $page, broken link: $link\n";
1123 sub isinlinableimage ($) {
1126 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1129 sub pagetitle ($;$) {
1131 my $unescaped=shift;
1134 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1137 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1145 # support use w/o %config set
1146 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1147 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1153 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1154 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1161 my $cgiurl=$local_cgiurl;
1163 if (exists $params{cgiurl}) {
1164 $cgiurl=$params{cgiurl};
1165 delete $params{cgiurl};
1173 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1176 sub cgiurl_abs (@) {
1178 URI->new_abs(cgiurl(@_), $config{cgiurl});
1184 return $local_url if ! defined $page;
1186 $page=htmlpage($page);
1188 $page=~s/[^\/]+\//..\//g;
1196 return $url unless defined $urlbase && length $urlbase;
1199 URI->new_abs($url, $urlbase)->as_string;
1203 # Work around very innefficient behavior in File::Spec if abs2rel
1204 # is passed two relative paths. It's much faster if paths are
1205 # absolute! (Debian bug #376658; fixed in debian unstable now)
1210 my $ret=File::Spec->abs2rel($path, $base);
1211 $ret=~s/^// if defined $ret;
1215 sub displaytime ($;$$) {
1216 # Plugins can override this function to mark up the time to
1218 my $time=formattime($_[0], $_[1]);
1219 if ($config{html5}) {
1220 return '<time datetime="'.date_3339($_[0]).'"'.
1221 ($_[2] ? ' pubdate="pubdate"' : '').
1222 '>'.$time.'</time>';
1225 return '<span class="date">'.$time.'</span>';
1229 sub formattime ($;$) {
1230 # Plugins can override this function to format the time.
1233 if (! defined $format) {
1234 $format=$config{timeformat};
1237 return strftime_utf8($format, localtime($time));
1240 my $strftime_encoding;
1242 # strftime doesn't know about encodings, so make sure
1243 # its output is properly treated as utf8.
1244 # Note that this does not handle utf-8 in the format string.
1245 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1246 unless defined $strftime_encoding;
1248 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1249 : POSIX::strftime(@_);
1255 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1256 POSIX::setlocale(&POSIX::LC_TIME, "C");
1257 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1258 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1262 sub beautify_urlpath ($) {
1265 # Ensure url is not an empty link, and if necessary,
1266 # add ./ to avoid colon confusion.
1267 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1271 if ($config{usedirs}) {
1272 $url =~ s!/index.$config{htmlext}$!/!;
1287 if (! $destsources{$to}) {
1292 return $config{url}.beautify_urlpath("/".$to);
1295 if (! defined $from) {
1296 my $u = $local_url || '';
1298 return $u.beautify_urlpath("/".$to);
1301 my $link = abs2rel($to, dirname(htmlpage($from)));
1303 return beautify_urlpath($link);
1306 sub isselflink ($$) {
1307 # Plugins can override this function to support special types
1312 return $page eq $link;
1315 sub htmllink ($$$;@) {
1316 my $lpage=shift; # the page doing the linking
1317 my $page=shift; # the page that will contain the link (different for inline)
1324 if (! $opts{forcesubpage}) {
1325 $bestlink=bestlink($lpage, $link);
1328 $bestlink="$lpage/".lc($link);
1332 if (defined $opts{linktext}) {
1333 $linktext=$opts{linktext};
1336 $linktext=pagetitle(basename($link));
1339 return "<span class=\"selflink\">$linktext</span>"
1340 if length $bestlink && isselflink($page, $bestlink) &&
1341 ! defined $opts{anchor};
1343 if (! $destsources{$bestlink}) {
1344 $bestlink=htmlpage($bestlink);
1346 if (! $destsources{$bestlink}) {
1348 if (length $config{cgiurl}) {
1349 $cgilink = "<a href=\"".
1354 )."\" rel=\"nofollow\">?</a>";
1356 return "<span class=\"createlink\">$cgilink$linktext</span>"
1360 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1361 $bestlink=beautify_urlpath($bestlink);
1363 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1364 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1367 if (defined $opts{anchor}) {
1368 $bestlink.="#".$opts{anchor};
1372 foreach my $attr (qw{rel class title}) {
1373 if (defined $opts{$attr}) {
1374 push @attrs, " $attr=\"$opts{$attr}\"";
1378 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1383 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1386 sub openiduser ($) {
1389 if (defined $user && $user =~ m!^https?://! &&
1390 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1393 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1394 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1397 # backcompat with old version
1398 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1399 $display=$oid->display;
1402 # Convert "user.somehost.com" to "user [somehost.com]"
1403 # (also "user.somehost.co.uk")
1404 if ($display !~ /\[/) {
1405 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1407 # Convert "http://somehost.com/user" to "user [somehost.com]".
1408 # (also "https://somehost.com/user/")
1409 if ($display !~ /\[/) {
1410 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1412 $display=~s!^https?://!!; # make sure this is removed
1413 eval q{use CGI 'escapeHTML'};
1415 return escapeHTML($display);
1420 sub htmlize ($$$$) {
1426 my $oneline = $content !~ /\n/;
1428 if (exists $hooks{htmlize}{$type}) {
1429 $content=$hooks{htmlize}{$type}{call}->(
1431 content => $content,
1435 error("htmlization of $type not supported");
1438 run_hooks(sanitize => sub {
1441 destpage => $destpage,
1442 content => $content,
1447 # hack to get rid of enclosing junk added by markdown
1448 # and other htmlizers/sanitizers
1449 $content=~s/^<p>//i;
1450 $content=~s/<\/p>\n*$//i;
1461 run_hooks(linkify => sub {
1464 destpage => $destpage,
1465 content => $content,
1473 our $preprocess_preview=0;
1474 sub preprocess ($$$;$$) {
1475 my $page=shift; # the page the data comes from
1476 my $destpage=shift; # the page the data will appear in (different for inline)
1481 # Using local because it needs to be set within any nested calls
1483 local $preprocess_preview=$preview if defined $preview;
1490 $params="" if ! defined $params;
1492 if (length $escape) {
1493 return "[[$prefix$command $params]]";
1495 elsif (exists $hooks{preprocess}{$command}) {
1496 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1497 # Note: preserve order of params, some plugins may
1498 # consider it significant.
1500 while ($params =~ m{
1501 (?:([-.\w]+)=)? # 1: named parameter key?
1503 """(.*?)""" # 2: triple-quoted value
1505 "([^"]*?)" # 3: single-quoted value
1507 '''(.*?)''' # 4: triple-single-quote
1509 <<([a-zA-Z]+)\n # 5: heredoc start
1510 (.*?)\n\5 # 6: heredoc value
1512 (\S+) # 7: unquoted value
1514 (?:\s+|$) # delimiter to next param
1524 elsif (defined $3) {
1527 elsif (defined $4) {
1530 elsif (defined $7) {
1533 elsif (defined $6) {
1538 push @params, $key, $val;
1541 push @params, $val, '';
1544 if ($preprocessing{$page}++ > 8) {
1545 # Avoid loops of preprocessed pages preprocessing
1546 # other pages that preprocess them, etc.
1547 return "[[!$command <span class=\"error\">".
1548 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1549 $page, $preprocessing{$page}).
1555 $hooks{preprocess}{$command}{call}->(
1558 destpage => $destpage,
1559 preview => $preprocess_preview,
1565 $ret="[[!$command <span class=\"error\">".
1566 gettext("Error").": $error"."</span>]]";
1570 # use void context during scan pass
1572 $hooks{preprocess}{$command}{call}->(
1575 destpage => $destpage,
1576 preview => $preprocess_preview,
1581 $preprocessing{$page}--;
1585 return "[[$prefix$command $params]]";
1590 if ($config{prefix_directives}) {
1593 \[\[(!) # directive open; 2: prefix
1594 ([-\w]+) # 3: command
1595 ( # 4: the parameters..
1596 \s+ # Must have space if parameters present
1598 (?:[-.\w]+=)? # named parameter key?
1600 """.*?""" # triple-quoted value
1602 "[^"]*?" # single-quoted value
1604 '''.*?''' # triple-single-quote
1606 <<([a-zA-Z]+)\n # 5: heredoc start
1607 (?:.*?)\n\5 # heredoc value
1609 [^"\s\]]+ # unquoted value
1611 \s* # whitespace or end
1614 *)? # 0 or more parameters
1615 \]\] # directive closed
1621 \[\[(!?) # directive open; 2: optional prefix
1622 ([-\w]+) # 3: command
1624 ( # 4: the parameters..
1626 (?:[-.\w]+=)? # named parameter key?
1628 """.*?""" # triple-quoted value
1630 "[^"]*?" # single-quoted value
1632 '''.*?''' # triple-single-quote
1634 <<([a-zA-Z]+)\n # 5: heredoc start
1635 (?:.*?)\n\5 # heredoc value
1637 [^"\s\]]+ # unquoted value
1639 \s* # whitespace or end
1642 *) # 0 or more parameters
1643 \]\] # directive closed
1647 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1656 run_hooks(filter => sub {
1657 $content=shift->(page => $page, destpage => $destpage,
1658 content => $content);
1664 sub check_canedit ($$$;$) {
1671 run_hooks(canedit => sub {
1672 return if defined $canedit;
1673 my $ret=shift->($page, $q, $session);
1678 elsif (ref $ret eq 'CODE') {
1679 $ret->() unless $nonfatal;
1682 elsif (defined $ret) {
1683 error($ret) unless $nonfatal;
1688 return defined $canedit ? $canedit : 1;
1691 sub check_content (@) {
1694 return 1 if ! exists $hooks{checkcontent}; # optimisation
1696 if (exists $pagesources{$params{page}}) {
1698 my %old=map { $_ => 1 }
1699 split("\n", readfile(srcfile($pagesources{$params{page}})));
1700 foreach my $line (split("\n", $params{content})) {
1701 push @diff, $line if ! exists $old{$line};
1703 $params{diff}=join("\n", @diff);
1707 run_hooks(checkcontent => sub {
1708 return if defined $ok;
1709 my $ret=shift->(%params);
1714 elsif (ref $ret eq 'CODE') {
1715 $ret->() unless $params{nonfatal};
1718 elsif (defined $ret) {
1719 error($ret) unless $params{nonfatal};
1725 return defined $ok ? $ok : 1;
1728 sub check_canchange (@) {
1730 my $cgi = $params{cgi};
1731 my $session = $params{session};
1732 my @changes = @{$params{changes}};
1735 foreach my $change (@changes) {
1736 # This untaint is safe because we check file_pruned and
1738 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1739 $file=possibly_foolish_untaint($file);
1740 if (! defined $file || ! length $file ||
1741 file_pruned($file)) {
1742 error(gettext("bad file name %s"), $file);
1745 my $type=pagetype($file);
1746 my $page=pagename($file) if defined $type;
1748 if ($change->{action} eq 'add') {
1752 if ($change->{action} eq 'change' ||
1753 $change->{action} eq 'add') {
1754 if (defined $page) {
1755 check_canedit($page, $cgi, $session);
1759 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1760 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1761 check_canedit($file, $cgi, $session);
1766 elsif ($change->{action} eq 'remove') {
1767 # check_canremove tests to see if the file is present
1768 # on disk. This will fail when a single commit adds a
1769 # file and then removes it again. Avoid the problem
1770 # by not testing the removal in such pairs of changes.
1771 # (The add is still tested, just to make sure that
1772 # no data is added to the repo that a web edit
1774 next if $newfiles{$file};
1776 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1777 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1778 check_canedit(defined $page ? $page : $file, $cgi, $session);
1783 error "unknown action ".$change->{action};
1786 error sprintf(gettext("you are not allowed to change %s"), $file);
1794 # Take an exclusive lock on the wiki to prevent multiple concurrent
1795 # run issues. The lock will be dropped on program exit.
1796 if (! -d $config{wikistatedir}) {
1797 mkdir($config{wikistatedir});
1799 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1800 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1801 if (! flock($wikilock, 2)) { # LOCK_EX
1802 error("failed to get lock");
1808 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1809 return close($wikilock) if $wikilock;
1815 sub commit_hook_enabled () {
1816 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1817 error("cannot write to $config{wikistatedir}/commitlock: $!");
1818 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1819 close($commitlock) || error("failed closing commitlock: $!");
1822 close($commitlock) || error("failed closing commitlock: $!");
1826 sub disable_commit_hook () {
1827 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1828 error("cannot write to $config{wikistatedir}/commitlock: $!");
1829 if (! flock($commitlock, 2)) { # LOCK_EX
1830 error("failed to get commit lock");
1835 sub enable_commit_hook () {
1836 return close($commitlock) if $commitlock;
1841 %oldrenderedfiles=%pagectime=();
1842 my $rebuild=$config{rebuild};
1844 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1845 %destsources=%renderedfiles=%pagecase=%pagestate=
1846 %depends_simple=%typedlinks=%oldtypedlinks=();
1849 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1850 if (-e "$config{wikistatedir}/index") {
1851 system("ikiwiki-transition", "indexdb", $config{srcdir});
1852 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1855 # gettime on first build
1856 $config{gettime}=1 unless defined $config{gettime};
1861 my $index=Storable::fd_retrieve($in);
1862 if (! defined $index) {
1867 if (exists $index->{version} && ! ref $index->{version}) {
1868 $pages=$index->{page};
1869 %wikistate=%{$index->{state}};
1870 # Handle plugins that got disabled by loading a new setup.
1871 if (exists $config{setupfile}) {
1872 require IkiWiki::Setup;
1873 IkiWiki::Setup::disabled_plugins(
1874 grep { ! $loaded_plugins{$_} } keys %wikistate);
1882 foreach my $src (keys %$pages) {
1883 my $d=$pages->{$src};
1885 if (exists $d->{page} && ! $rebuild) {
1889 $page=pagename($src);
1891 $pagectime{$page}=$d->{ctime};
1892 $pagesources{$page}=$src;
1894 $pagemtime{$page}=$d->{mtime};
1895 $renderedfiles{$page}=$d->{dest};
1896 if (exists $d->{links} && ref $d->{links}) {
1897 $links{$page}=$d->{links};
1898 $oldlinks{$page}=[@{$d->{links}}];
1900 if (ref $d->{depends_simple} eq 'ARRAY') {
1902 $depends_simple{$page}={
1903 map { $_ => 1 } @{$d->{depends_simple}}
1906 elsif (exists $d->{depends_simple}) {
1907 $depends_simple{$page}=$d->{depends_simple};
1909 if (exists $d->{dependslist}) {
1912 map { $_ => $DEPEND_CONTENT }
1913 @{$d->{dependslist}}
1916 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1918 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1920 elsif (exists $d->{depends}) {
1921 $depends{$page}=$d->{depends};
1923 if (exists $d->{state}) {
1924 $pagestate{$page}=$d->{state};
1926 if (exists $d->{typedlinks}) {
1927 $typedlinks{$page}=$d->{typedlinks};
1929 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1930 next unless %$links;
1931 $oldtypedlinks{$page}{$type} = {%$links};
1935 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1937 foreach my $page (keys %pagesources) {
1938 $pagecase{lc $page}=$page;
1940 foreach my $page (keys %renderedfiles) {
1941 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1943 $lastrev=$index->{lastrev};
1944 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1949 run_hooks(savestate => sub { shift->() });
1951 my @plugins=keys %loaded_plugins;
1953 if (! -d $config{wikistatedir}) {
1954 mkdir($config{wikistatedir});
1956 my $newfile="$config{wikistatedir}/indexdb.new";
1957 my $cleanup = sub { unlink($newfile) };
1958 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1961 foreach my $page (keys %pagemtime) {
1962 next unless $pagemtime{$page};
1963 my $src=$pagesources{$page};
1965 $index{page}{$src}={
1967 ctime => $pagectime{$page},
1968 mtime => $pagemtime{$page},
1969 dest => $renderedfiles{$page},
1970 links => $links{$page},
1973 if (exists $depends{$page}) {
1974 $index{page}{$src}{depends} = $depends{$page};
1977 if (exists $depends_simple{$page}) {
1978 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1981 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1982 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1985 if (exists $pagestate{$page}) {
1986 $index{page}{$src}{state}=$pagestate{$page};
1991 foreach my $id (@plugins) {
1992 $index{state}{$id}={}; # used to detect disabled plugins
1993 foreach my $key (keys %{$wikistate{$id}}) {
1994 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1998 $index{lastrev}=$lastrev;
1999 $index{underlayfiles}=\@underlayfiles;
2001 $index{version}="3";
2002 my $ret=Storable::nstore_fd(\%index, $out);
2003 return if ! defined $ret || ! $ret;
2004 close $out || error("failed saving to $newfile: $!", $cleanup);
2005 rename($newfile, "$config{wikistatedir}/indexdb") ||
2006 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2011 sub template_file ($) {
2014 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2016 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2017 $template=srcfile($pagesources{$tpage}, 1);
2021 $template=srcfile($tpage, 1);
2024 if (defined $template) {
2025 return $template, $tpage, 1 if wantarray;
2029 $name=~s:/::; # avoid path traversal
2030 foreach my $dir ($config{templatedir},
2031 "$installdir/share/ikiwiki/templates") {
2032 if (-e "$dir/$name") {
2033 $template="$dir/$name";
2037 if (defined $template) {
2038 return $template, $tpage if wantarray;
2046 sub template_depends ($$;@) {
2050 my ($filename, $tpage, $untrusted)=template_file($name);
2051 if (! defined $filename) {
2052 error(sprintf(gettext("template %s not found"), $name))
2055 if (defined $page && defined $tpage) {
2056 add_depends($page, $tpage);
2061 my $text_ref = shift;
2062 ${$text_ref} = decode_utf8(${$text_ref});
2063 run_hooks(readtemplate => sub {
2064 ${$text_ref} = shift->(
2067 content => ${$text_ref},
2068 untrusted => $untrusted,
2072 loop_context_vars => 1,
2073 die_on_bad_params => 0,
2074 parent_global_vars => 1,
2075 filename => $filename,
2077 ($untrusted ? (no_includes => 1) : ()),
2079 return @opts if wantarray;
2081 require HTML::Template;
2082 return HTML::Template->new(@opts);
2085 sub template ($;@) {
2086 template_depends(shift, undef, @_);
2089 sub templateactions ($$) {
2095 run_hooks(pageactions => sub {
2096 push @actions, map { { action => $_ } }
2097 grep { defined } shift->(page => $page);
2099 $template->param(actions => \@actions);
2101 if ($config{cgiurl} && exists $hooks{auth}) {
2102 $template->param(prefsurl => cgiurl(do => "prefs"));
2106 if ($have_actions || @actions) {
2107 $template->param(have_actions => 1);
2114 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2115 error 'hook requires type, call, and id parameters';
2118 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2120 $hooks{$param{type}}{$param{id}}=\%param;
2124 sub run_hooks ($$) {
2125 # Calls the given sub for each hook of the given type,
2126 # passing it the hook function to call.
2130 if (exists $hooks{$type}) {
2131 my (@first, @middle, @last);
2132 foreach my $id (keys %{$hooks{$type}}) {
2133 if ($hooks{$type}{$id}{first}) {
2136 elsif ($hooks{$type}{$id}{last}) {
2143 foreach my $id (@first, @middle, @last) {
2144 $sub->($hooks{$type}{$id}{call});
2152 $hooks{rcs}{rcs_update}{call}->(@_);
2155 sub rcs_prepedit ($) {
2156 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2159 sub rcs_commit (@) {
2160 $hooks{rcs}{rcs_commit}{call}->(@_);
2163 sub rcs_commit_staged (@) {
2164 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2168 $hooks{rcs}{rcs_add}{call}->(@_);
2171 sub rcs_remove ($) {
2172 $hooks{rcs}{rcs_remove}{call}->(@_);
2175 sub rcs_rename ($$) {
2176 $hooks{rcs}{rcs_rename}{call}->(@_);
2179 sub rcs_recentchanges ($) {
2180 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2183 sub rcs_diff ($;$) {
2184 $hooks{rcs}{rcs_diff}{call}->(@_);
2187 sub rcs_getctime ($) {
2188 $hooks{rcs}{rcs_getctime}{call}->(@_);
2191 sub rcs_getmtime ($) {
2192 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2195 sub rcs_receive () {
2196 $hooks{rcs}{rcs_receive}{call}->();
2199 sub add_depends ($$;$) {
2202 my $deptype=shift || $DEPEND_CONTENT;
2204 # Is the pagespec a simple page name?
2205 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2206 $pagespec !~ /[\s*?()!]/) {
2207 $depends_simple{$page}{lc $pagespec} |= $deptype;
2211 # Add explicit dependencies for influences.
2212 my $sub=pagespec_translate($pagespec);
2213 return unless defined $sub;
2214 foreach my $p (keys %pagesources) {
2215 my $r=$sub->($p, location => $page);
2216 my $i=$r->influences;
2217 my $static=$r->influences_static;
2218 foreach my $k (keys %$i) {
2219 next unless $r || $static || $k eq $page;
2220 $depends_simple{$page}{lc $k} |= $i->{$k};
2225 $depends{$page}{$pagespec} |= $deptype;
2231 foreach my $type (@_) {
2232 if ($type eq 'presence') {
2233 $deptype |= $DEPEND_PRESENCE;
2235 elsif ($type eq 'links') {
2236 $deptype |= $DEPEND_LINKS;
2238 elsif ($type eq 'content') {
2239 $deptype |= $DEPEND_CONTENT;
2245 my $file_prune_regexp;
2246 sub file_pruned ($) {
2249 if (defined $config{include} && length $config{include}) {
2250 return 0 if $file =~ m/$config{include}/;
2253 if (! defined $file_prune_regexp) {
2254 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2255 $file_prune_regexp=qr/$file_prune_regexp/;
2257 return $file =~ m/$file_prune_regexp/;
2260 sub define_gettext () {
2261 # If translation is needed, redefine the gettext function to do it.
2262 # Otherwise, it becomes a quick no-op.
2265 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2266 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2267 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2269 $gettext_obj=eval q{
2270 use Locale::gettext q{textdomain};
2271 Locale::gettext->domain('ikiwiki')
2276 no warnings 'redefine';
2278 $getobj->() if $getobj;
2280 $gettext_obj->get(shift);
2287 $getobj->() if $getobj;
2289 $gettext_obj->nget(@_);
2292 return ($_[2] == 1 ? $_[0] : $_[1])
2310 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2314 # Injects a new function into the symbol table to replace an
2315 # exported function.
2318 # This is deep ugly perl foo, beware.
2321 if (! defined $params{parent}) {
2322 $params{parent}='::';
2323 $params{old}=\&{$params{name}};
2324 $params{name}=~s/.*:://;
2326 my $parent=$params{parent};
2327 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2328 $ns = $params{parent} . $ns;
2329 inject(%params, parent => $ns) unless $ns eq '::main::';
2330 *{$ns . $params{name}} = $params{call}
2331 if exists ${$ns}{$params{name}} &&
2332 \&{${$ns}{$params{name}}} == $params{old};
2338 sub add_link ($$;$) {
2343 push @{$links{$page}}, $link
2344 unless grep { $_ eq $link } @{$links{$page}};
2346 if (defined $type) {
2347 $typedlinks{$page}{$type}{$link} = 1;
2351 sub add_autofile ($$$) {
2354 my $generator=shift;
2356 $autofiles{$file}{plugin}=$plugin;
2357 $autofiles{$file}{generator}=$generator;
2361 return LWP::UserAgent->new(
2362 cookie_jar => $config{cookiejar},
2363 env_proxy => 1, # respect proxy env vars
2364 agent => $config{useragent},
2368 sub sortspec_translate ($$) {
2370 my $reverse = shift;
2376 (-?) # group 1: perhaps negated
2379 \w+\([^\)]*\) # command(params)
2381 [^\s]+ # or anything else
2389 if ($word =~ m/^(\w+)\((.*)\)$/) {
2390 # command with parameters
2394 elsif ($word !~ m/^\w+$/) {
2395 error(sprintf(gettext("invalid sort type %s"), $word));
2406 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2407 if (defined $params) {
2408 push @data, $params;
2409 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2412 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2416 error(sprintf(gettext("unknown sort type %s"), $word));
2420 if (! length $code) {
2421 # undefined sorting method... sort arbitrarily
2430 return eval 'sub { '.$code.' }';
2433 sub pagespec_translate ($) {
2436 # Convert spec to perl code.
2440 \s* # ignore whitespace
2441 ( # 1: match a single word
2448 \w+\([^\)]*\) # command(params)
2450 [^\s()]+ # any other text
2452 \s* # ignore whitespace
2455 if (lc $word eq 'and') {
2458 elsif (lc $word eq 'or') {
2461 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2464 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2465 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2467 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2470 push @data, qq{unknown function in pagespec "$word"};
2471 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2476 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2480 if (! length $code) {
2481 $code="IkiWiki::FailReason->new('empty pagespec')";
2485 return eval 'sub { my $page=shift; '.$code.' }';
2488 sub pagespec_match ($$;@) {
2493 # Backwards compatability with old calling convention.
2495 unshift @params, 'location';
2498 my $sub=pagespec_translate($spec);
2499 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2501 return $sub->($page, @params);
2504 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2506 # Not exported yet, but could be in future if it is generally useful.
2507 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2508 # which is "more internal".
2509 sub sort_pages ($$;@) {
2513 $sort = sortspec_translate($sort, $params{reverse});
2514 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2517 sub pagespec_match_list ($$;@) {
2522 # Backwards compatability with old calling convention.
2524 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2525 $params{list}=$page;
2526 $page=$params{location}; # ugh!
2529 my $sub=pagespec_translate($pagespec);
2530 error "syntax error in pagespec \"$pagespec\""
2532 my $sort=sortspec_translate($params{sort}, $params{reverse})
2533 if defined $params{sort};
2536 if (exists $params{list}) {
2537 @candidates=exists $params{filter}
2538 ? grep { ! $params{filter}->($_) } @{$params{list}}
2542 @candidates=exists $params{filter}
2543 ? grep { ! $params{filter}->($_) } keys %pagesources
2544 : keys %pagesources;
2547 # clear params, remainder is passed to pagespec
2548 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2549 my $num=$params{num};
2550 delete @params{qw{num deptype reverse sort filter list}};
2552 # when only the top matches will be returned, it's efficient to
2553 # sort before matching to pagespec,
2554 if (defined $num && defined $sort) {
2555 @candidates=IkiWiki::SortSpec::sort_pages(
2556 $sort, @candidates);
2562 my $accum=IkiWiki::SuccessReason->new();
2563 foreach my $p (@candidates) {
2564 my $r=$sub->($p, %params, location => $page);
2565 error(sprintf(gettext("cannot match pages: %s"), $r))
2566 if $r->isa("IkiWiki::ErrorReason");
2567 unless ($r || $r->influences_static) {
2568 $r->remove_influence($p);
2573 last if defined $num && ++$count == $num;
2577 # Add simple dependencies for accumulated influences.
2578 my $i=$accum->influences;
2579 foreach my $k (keys %$i) {
2580 $depends_simple{$page}{lc $k} |= $i->{$k};
2583 # when all matches will be returned, it's efficient to
2584 # sort after matching
2585 if (! defined $num && defined $sort) {
2586 return IkiWiki::SortSpec::sort_pages(
2594 sub pagespec_valid ($) {
2597 return defined pagespec_translate($spec);
2601 my $re=quotemeta(shift);
2607 package IkiWiki::FailReason;
2610 '""' => sub { $_[0][0] },
2612 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2613 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2614 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2618 our @ISA = 'IkiWiki::SuccessReason';
2620 package IkiWiki::SuccessReason;
2622 # A blessed array-ref:
2624 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2626 # - if absent or false, the influences of this evaluation are "static",
2627 # see the influences_static method
2628 # - if true, they are dynamic (not static)
2629 # [1]{any other key}:
2630 # the dependency types of influences, as returned by the influences method
2633 # in string context, it's the human-readable reason
2634 '""' => sub { $_[0][0] },
2635 # in boolean context, SuccessReason is 1 and FailReason is 0
2637 # negating a result gives the opposite result with the same influences
2638 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2639 # A & B = (A ? B : A) with the influences of both
2640 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2641 # A | B = (A ? A : B) with the influences of both
2642 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2646 # SuccessReason->new("human-readable reason", page => deptype, ...)
2651 return bless [$value, {@_}], $class;
2654 # influences(): return a reference to a copy of the hash
2655 # { page => dependency type } describing the pages that indirectly influenced
2656 # this result, but would not cause a dependency through ikiwiki's core
2659 # See [[todo/dependency_types]] for extensive discussion of what this means.
2661 # influences(page => deptype, ...): remove all influences, replace them
2662 # with the arguments, and return a reference to a copy of the new influences.
2666 $this->[1]={@_} if @_;
2667 my %i=%{$this->[1]};
2672 # True if this result has the same influences whichever page it matches,
2673 # For instance, whether bar matches backlink(foo) is influenced only by
2674 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2675 # which does not mention bar anywhere.
2677 # False if this result would have different influences when matching
2678 # different pages. For instance, when testing whether link(foo) matches bar,
2679 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2680 # bar's links could change the outcome; so its influences are not the same
2681 # as when testing whether link(foo) matches baz.
2683 # Static influences are one of the things that make pagespec_match_list
2684 # more efficient than repeated calls to pagespec_match.
2686 sub influences_static {
2687 return ! $_[0][1]->{""};
2690 # Change the influences of $this to be the influences of "$this & $other"
2691 # or "$this | $other".
2693 # If both $this and $other are either successful or have influences,
2694 # or this is an "or" operation, the result has all the influences from
2695 # either of the arguments. It has dynamic influences if either argument
2696 # has dynamic influences.
2698 # If this is an "and" operation, and at least one argument is a
2699 # FailReason with no influences, the result has no influences, and they
2700 # are not dynamic. For instance, link(foo) matching bar is influenced
2701 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2702 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2703 # bar, because it would be false however often you edit bar.
2705 sub merge_influences {
2710 # This "if" is odd because it needs to avoid negating $this
2711 # or $other, which would alter the objects in-place. Be careful.
2712 if (! $anded || (($this || %{$this->[1]}) &&
2713 ($other || %{$other->[1]}))) {
2714 foreach my $influence (keys %{$other->[1]}) {
2715 $this->[1]{$influence} |= $other->[1]{$influence};
2724 # Change $this so it is not considered to be influenced by $torm.
2726 sub remove_influence {
2730 delete $this->[1]{$torm};
2733 package IkiWiki::ErrorReason;
2735 our @ISA = 'IkiWiki::FailReason';
2737 package IkiWiki::PageSpec;
2743 if ($path =~ m!^\.(/|$)!) {
2745 $from=~s#/?[^/]+$## if defined $from;
2747 $path="$from/$path" if defined $from && length $from;
2751 $path = "" unless defined $path;
2760 sub match_glob ($$;@) {
2765 $glob=derel($glob, $params{location});
2767 # Instead of converting the glob to a regex every time,
2768 # cache the compiled regex to save time.
2769 my $re=$glob_cache{$glob};
2770 unless (defined $re) {
2771 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2774 if (! IkiWiki::isinternal($page) || $params{internal}) {
2775 return IkiWiki::SuccessReason->new("$glob matches $page");
2778 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2782 return IkiWiki::FailReason->new("$glob does not match $page");
2786 sub match_internal ($$;@) {
2787 return match_glob(shift, shift, @_, internal => 1)
2790 sub match_page ($$;@) {
2792 my $match=match_glob($page, shift, @_);
2794 my $source=exists $IkiWiki::pagesources{$page} ?
2795 $IkiWiki::pagesources{$page} :
2796 $IkiWiki::delpagesources{$page};
2797 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2798 if (! defined $type) {
2799 return IkiWiki::FailReason->new("$page is not a page");
2805 sub match_link ($$;@) {
2810 $link=derel($link, $params{location});
2811 my $from=exists $params{location} ? $params{location} : '';
2812 my $linktype=$params{linktype};
2814 if (defined $linktype) {
2815 $qualifier=" with type $linktype";
2818 my $links = $IkiWiki::links{$page};
2819 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2820 unless $links && @{$links};
2821 my $bestlink = IkiWiki::bestlink($from, $link);
2822 foreach my $p (@{$links}) {
2823 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2825 if (length $bestlink) {
2826 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2827 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2831 if (match_glob($p, $link, %params)) {
2832 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2834 my ($p_rel)=$p=~/^\/?(.*)/;
2836 if (match_glob($p_rel, $link, %params)) {
2837 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2841 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2844 sub match_backlink ($$;@) {
2848 if ($testpage eq '.') {
2849 $testpage = $params{'location'}
2851 my $ret=match_link($testpage, $page, @_);
2852 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2856 sub match_created_before ($$;@) {
2861 $testpage=derel($testpage, $params{location});
2863 if (exists $IkiWiki::pagectime{$testpage}) {
2864 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2865 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2868 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2872 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2876 sub match_created_after ($$;@) {
2881 $testpage=derel($testpage, $params{location});
2883 if (exists $IkiWiki::pagectime{$testpage}) {
2884 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2885 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2888 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2892 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2896 sub match_creation_day ($$;@) {
2899 if ($d !~ /^\d+$/) {
2900 return IkiWiki::ErrorReason->new("invalid day $d");
2902 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2903 return IkiWiki::SuccessReason->new('creation_day matched');
2906 return IkiWiki::FailReason->new('creation_day did not match');
2910 sub match_creation_month ($$;@) {
2913 if ($m !~ /^\d+$/) {
2914 return IkiWiki::ErrorReason->new("invalid month $m");
2916 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2917 return IkiWiki::SuccessReason->new('creation_month matched');
2920 return IkiWiki::FailReason->new('creation_month did not match');
2924 sub match_creation_year ($$;@) {
2927 if ($y !~ /^\d+$/) {
2928 return IkiWiki::ErrorReason->new("invalid year $y");
2930 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2931 return IkiWiki::SuccessReason->new('creation_year matched');
2934 return IkiWiki::FailReason->new('creation_year did not match');
2938 sub match_user ($$;@) {
2943 if (! exists $params{user}) {
2944 return IkiWiki::ErrorReason->new("no user specified");
2947 my $regexp=IkiWiki::glob2re($user);
2949 if (defined $params{user} && $params{user}=~$regexp) {
2950 return IkiWiki::SuccessReason->new("user is $user");
2952 elsif (! defined $params{user}) {
2953 return IkiWiki::FailReason->new("not logged in");
2956 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2960 sub match_admin ($$;@) {
2965 if (! exists $params{user}) {
2966 return IkiWiki::ErrorReason->new("no user specified");
2969 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2970 return IkiWiki::SuccessReason->new("user is an admin");
2972 elsif (! defined $params{user}) {
2973 return IkiWiki::FailReason->new("not logged in");
2976 return IkiWiki::FailReason->new("user is not an admin");
2980 sub match_ip ($$;@) {
2985 if (! exists $params{ip}) {
2986 return IkiWiki::ErrorReason->new("no IP specified");
2989 my $regexp=IkiWiki::glob2re(lc $ip);
2991 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2992 return IkiWiki::SuccessReason->new("IP is $ip");
2995 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2999 package IkiWiki::SortSpec;
3001 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3002 # are easily available in this namespace, for cmp functions to use them.
3009 IkiWiki::pagetitle(IkiWiki::basename($a))
3011 IkiWiki::pagetitle(IkiWiki::basename($b))
3014 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3015 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3016 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }