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}/.local/share/ikiwiki"],
365 description => "extra library and plugin directories",
367 safe => 0, # directory
373 example => "$ENV{HOME}/.ikiwiki/",
374 description => "extra library and plugin directory (searched after libdirs)",
376 safe => 0, # directory
382 description => "environment variables",
383 safe => 0, # paranoia
389 example => "US/Eastern",
390 description => "time zone name",
397 example => '^\.htaccess$',
398 description => "regexp of normally excluded files to include",
406 example => '^(*\.private|Makefile)$',
407 description => "regexp of files that should be skipped",
412 wiki_file_prune_regexps => {
414 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
415 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
416 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
417 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
418 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
419 description => "regexps of source files to ignore",
425 description => "specifies the characters that are allowed in source filenames",
426 default => "-[:alnum:]+/.:_",
430 wiki_file_regexp => {
432 description => "regexp of legal source files",
436 web_commit_regexp => {
438 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
439 description => "regexp to parse web commits from logs",
446 description => "run as a cgi",
450 cgi_disable_uploads => {
453 description => "whether CGI should accept file uploads",
460 description => "run as a post-commit hook",
467 description => "running in rebuild mode",
474 description => "running in setup mode",
481 description => "running in clean mode",
488 description => "running in refresh mode",
495 description => "running in receive test mode",
499 wrapper_background_command => {
502 description => "background shell command to run",
508 description => "running in gettime mode",
515 description => "running in w3mmode",
522 description => "path to the .ikiwiki directory holding ikiwiki state",
529 description => "path to setup file",
536 description => "perl class to use to dump setup file",
540 allow_symlinks_before_srcdir => {
543 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
549 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
550 description => "cookie control",
551 safe => 0, # hooks into perl module internals
556 default => "ikiwiki/$version",
557 example => "Wget/1.13.4 (linux-gnu)",
558 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
562 responsive_layout => {
565 description => "theme has a responsive layout? (mobile-optimized)",
572 description => "try harder to produce deterministic output",
581 if ($config{libdirs}) {
582 @libdirs = @{$config{libdirs}};
584 if (length $config{libdir}) {
585 push @libdirs, $config{libdir};
590 sub defaultconfig () {
593 foreach my $key (keys %s) {
594 push @ret, $key, $s{$key}->{default};
599 # URL to top of wiki as a path starting with /, valid from any wiki page or
600 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
602 # URL to CGI script, similar to $local_url
606 # locale stuff; avoid LC_ALL since it overrides everything
607 if (defined $ENV{LC_ALL}) {
608 $ENV{LANG} = $ENV{LC_ALL};
611 if (defined $config{locale}) {
612 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
613 $ENV{LANG}=$config{locale};
618 if (! defined $config{wiki_file_regexp}) {
619 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
622 if (ref $config{ENV} eq 'HASH') {
623 foreach my $val (keys %{$config{ENV}}) {
624 $ENV{$val}=$config{ENV}{$val};
627 if (defined $config{timezone} && length $config{timezone}) {
628 $ENV{TZ}=$config{timezone};
630 elsif (defined $ENV{TZ} && length $ENV{TZ}) {
631 $config{timezone}=$ENV{TZ};
634 eval q{use Config qw()};
637 if ($Config::Config{d_gnulibc} && -e '/etc/localtime') {
638 $config{timezone}=$ENV{TZ}=':/etc/localtime';
641 $config{timezone}=$ENV{TZ}='GMT';
645 if ($config{w3mmode}) {
646 eval q{use Cwd q{abs_path}};
648 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
649 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
650 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
651 unless $config{cgiurl} =~ m!file:///!;
652 $config{url}="file://".$config{destdir};
655 if ($config{cgi} && ! length $config{url}) {
656 error(gettext("Must specify url to wiki with --url when using --cgi"));
659 if (defined $config{url} && length $config{url}) {
661 my $baseurl = URI->new($config{url});
663 $local_url = $baseurl->path . "/";
664 $local_cgiurl = undef;
666 if (length $config{cgiurl}) {
667 my $cgiurl = URI->new($config{cgiurl});
669 $local_cgiurl = $cgiurl->path;
671 if ($cgiurl->scheme eq 'https' &&
672 $baseurl->scheme eq 'http') {
673 # We assume that the same content is available
674 # over both http and https, because if it
675 # wasn't, accessing the static content
676 # from the CGI would be mixed-content,
677 # which would be a security flaw.
679 if ($cgiurl->authority ne $baseurl->authority) {
680 # use protocol-relative URL for
682 $local_url = "$config{url}/";
683 $local_url =~ s{^http://}{//};
685 # else use host-relative URL for static content
687 # either way, CGI needs to be absolute
688 $local_cgiurl = $config{cgiurl};
690 elsif ($cgiurl->scheme ne $baseurl->scheme) {
691 # too far apart, fall back to absolute URLs
692 $local_url = "$config{url}/";
693 $local_cgiurl = $config{cgiurl};
695 elsif ($cgiurl->authority ne $baseurl->authority) {
696 # slightly too far apart, fall back to
697 # protocol-relative URLs
698 $local_url = "$config{url}/";
699 $local_url =~ s{^https?://}{//};
700 $local_cgiurl = $config{cgiurl};
701 $local_cgiurl =~ s{^https?://}{//};
703 # else keep host-relative URLs
706 $local_url =~ s{//$}{/};
709 $local_cgiurl = $config{cgiurl};
712 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
713 unless exists $config{wikistatedir} && defined $config{wikistatedir};
715 if (defined $config{umask}) {
716 my $u = possibly_foolish_untaint($config{umask});
718 if ($u =~ m/^\d+$/) {
721 elsif ($u eq 'private') {
724 elsif ($u eq 'group') {
727 elsif ($u eq 'public') {
731 error(sprintf(gettext("unsupported umask setting %s"), $u));
735 run_hooks(checkconfig => sub { shift->() });
743 foreach my $dir (@INC, getlibdirs()) {
744 next unless defined $dir && length $dir;
745 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
746 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
750 foreach my $dir (getlibdirs(), "$installdir/lib/ikiwiki") {
751 next unless defined $dir && length $dir;
752 foreach my $file (glob("$dir/plugins/*")) {
753 $ret{basename($file)}=1 if -x $file;
761 foreach my $dir (getlibdirs()) {
762 unshift @INC, possibly_foolish_untaint($dir);
765 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
770 if (exists $hooks{rcs}) {
771 error(gettext("cannot use multiple rcs plugins"));
773 loadplugin($config{rcs});
775 if (! exists $hooks{rcs}) {
779 run_hooks(getopt => sub { shift->() });
780 if (grep /^-/, @ARGV) {
781 print STDERR "Unknown option (or missing parameter): $_\n"
782 foreach grep /^-/, @ARGV;
789 sub loadplugin ($;$) {
793 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
795 foreach my $possiblytainteddir (getlibdirs(), "$installdir/lib/ikiwiki") {
796 my $dir = possibly_foolish_untaint($possiblytainteddir);
797 if (defined $dir && -x "$dir/plugins/$plugin") {
798 eval { require IkiWiki::Plugin::external };
801 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
803 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
804 $loaded_plugins{$plugin}=1;
809 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
812 error("Failed to load plugin $mod: $@");
814 $loaded_plugins{$plugin}=1;
821 log_message('err' => $message) if $config{syslog};
822 if (defined $cleaner) {
829 return unless $config{verbose};
830 return log_message(debug => @_);
835 sub log_message ($$) {
838 if ($config{syslog}) {
841 Sys::Syslog::setlogsock('unix');
842 Sys::Syslog::openlog('ikiwiki', '', 'user');
846 # keep a copy to avoid editing the original config repeatedly
847 my $wikiname = $config{wikiname};
848 utf8::encode($wikiname);
849 my $message = join(" ", @_);
850 utf8::encode($message);
851 Sys::Syslog::syslog($type, "[$wikiname] %s", $message);
854 print STDERR "failed to syslog: $@" unless $log_failed;
860 elsif (! $config{cgi}) {
864 return print STDERR "@_\n";
868 sub possibly_foolish_untaint ($) {
870 my ($untainted)=$tainted=~/(.*)/s;
890 return exists $pagesources{$page} &&
891 $pagesources{$page} =~ /\._([^.]+)$/;
897 if ($file =~ /\.([^.]+)$/) {
898 return $1 if exists $hooks{htmlize}{$1};
900 my $base=basename($file);
901 if (exists $hooks{htmlize}{$base} &&
902 $hooks{htmlize}{$base}{noextension}) {
913 if (exists $pagename_cache{$file}) {
914 return $pagename_cache{$file};
917 my $type=pagetype($file);
919 $page=~s/\Q.$type\E*$//
920 if defined $type && !$hooks{htmlize}{$type}{keepextension}
921 && !$hooks{htmlize}{$type}{noextension};
922 if ($config{indexpages} && $page=~/(.*)\/index$/) {
926 $pagename_cache{$file} = $page;
930 sub newpagefile ($$) {
934 if (! $config{indexpages} || $page eq 'index') {
935 return $page.".".$type;
938 return $page."/index.".$type;
942 sub targetpage ($$;$) {
947 if (defined $filename) {
948 return $page."/".$filename.".".$ext;
950 elsif (! $config{usedirs} || $page eq 'index') {
951 return $page.".".$ext;
954 return $page."/index.".$ext;
961 return targetpage($page, $config{htmlext});
968 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
969 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
970 return "$dir/$file", stat(_) if -e "$dir/$file";
972 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
977 return (srcfile_stat(@_))[0];
980 sub add_literal_underlay ($) {
983 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
984 unshift @{$config{underlaydirs}}, $dir;
988 sub add_underlay ($) {
992 $dir="$config{underlaydirbase}/$dir";
995 add_literal_underlay($dir);
996 # why does it return 1? we just don't know
1000 sub readfile ($;$$) {
1006 error("cannot read a symlink ($file)");
1010 open (my $in, "<", $file) || error("failed to read $file: $!");
1011 binmode($in) if ($binary);
1012 return \*$in if $wantfd;
1014 # check for invalid utf-8, and toss it back to avoid crashes
1015 if (! utf8::valid($ret)) {
1016 $ret=encode_utf8($ret);
1018 close $in || error("failed to read $file: $!");
1022 sub prep_writefile ($$) {
1027 while (length $test) {
1028 if (-l "$destdir/$test") {
1029 error("cannot write to a symlink ($test)");
1031 if (-f _ && $test ne $file) {
1032 # Remove conflicting file.
1033 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1034 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1036 unlink("$destdir/$test");
1042 $test=dirname($test);
1045 my $dir=dirname("$destdir/$file");
1048 foreach my $s (split(m!/+!, $dir)) {
1051 mkdir($d) || error("failed to create directory $d: $!");
1059 sub writefile ($$$;$$) {
1060 my $file=shift; # can include subdirs
1061 my $destdir=shift; # directory to put file in
1066 prep_writefile($file, $destdir);
1068 my $newfile="$destdir/$file.ikiwiki-new";
1070 error("cannot write to a symlink ($newfile)");
1073 my $cleanup = sub { unlink($newfile) };
1074 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1075 binmode($out) if ($binary);
1077 $writer->(\*$out, $cleanup);
1080 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1082 close $out || error("failed saving $newfile: $!", $cleanup);
1083 rename($newfile, "$destdir/$file") ||
1084 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1090 sub will_render ($$;$) {
1095 # Important security check for independently created files.
1096 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1097 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1098 my $from_other_page=0;
1099 # Expensive, but rarely runs.
1100 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1103 dirname($_) eq $dest
1104 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1110 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1111 unless $from_other_page;
1114 # If $dest exists as a directory, remove conflicting files in it
1115 # rendered from other pages.
1117 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1118 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1119 if (dirname($f) eq $dest) {
1120 unlink("$config{destdir}/$f");
1121 rmdir(dirname("$config{destdir}/$f"));
1127 if (! $clear || $cleared{$page}) {
1128 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1131 foreach my $old (@{$renderedfiles{$page}}) {
1132 delete $destsources{$old};
1134 $renderedfiles{$page}=[$dest];
1137 $destsources{$dest}=$page;
1147 if ($link=~s/^\/+//) {
1155 $l.="/" if length $l;
1158 if (exists $pagesources{$l}) {
1161 elsif (exists $pagecase{lc $l}) {
1162 return $pagecase{lc $l};
1164 } while $cwd=~s{/?[^/]+$}{};
1166 if (length $config{userdir}) {
1167 my $l = "$config{userdir}/".lc($link);
1168 if (exists $pagesources{$l}) {
1171 elsif (exists $pagecase{lc $l}) {
1172 return $pagecase{lc $l};
1176 #print STDERR "warning: page $page, broken link: $link\n";
1180 sub isinlinableimage ($) {
1183 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1186 sub pagetitle ($;$) {
1188 my $unescaped=shift;
1191 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1194 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1202 # support use w/o %config set
1203 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1204 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1210 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1211 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1218 my $cgiurl=$local_cgiurl;
1220 if (exists $params{cgiurl}) {
1221 $cgiurl=$params{cgiurl};
1222 delete $params{cgiurl};
1230 join("&", map $_."=".uri_escape_utf8($params{$_}), sort(keys %params));
1233 sub cgiurl_abs (@) {
1235 URI->new_abs(cgiurl(@_), $config{cgiurl});
1241 return $local_url if ! defined $page;
1243 $page=htmlpage($page);
1245 $page=~s/[^\/]+\//..\//g;
1253 return $url unless defined $urlbase && length $urlbase;
1256 URI->new_abs($url, $urlbase)->as_string;
1260 # Work around very innefficient behavior in File::Spec if abs2rel
1261 # is passed two relative paths. It's much faster if paths are
1262 # absolute! (Debian bug #376658; fixed in debian unstable now)
1267 my $ret=File::Spec->abs2rel($path, $base);
1268 $ret=~s/^// if defined $ret;
1272 sub displaytime ($;$$) {
1273 # Plugins can override this function to mark up the time to
1275 my $time=formattime($_[0], $_[1]);
1276 if ($config{html5}) {
1277 return '<time datetime="'.date_3339($_[0]).'"'.
1278 ($_[2] ? ' pubdate="pubdate"' : '').
1279 '>'.$time.'</time>';
1282 return '<span class="date">'.$time.'</span>';
1286 sub formattime ($;$) {
1287 # Plugins can override this function to format the time.
1290 if (! defined $format) {
1291 $format=$config{timeformat};
1294 return strftime_utf8($format, localtime($time));
1297 my $strftime_encoding;
1299 # strftime doesn't know about encodings, so make sure
1300 # its output is properly treated as utf8.
1301 # Note that this does not handle utf-8 in the format string.
1302 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1303 unless defined $strftime_encoding;
1305 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1306 : POSIX::strftime(@_);
1312 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1313 POSIX::setlocale(&POSIX::LC_TIME, "C");
1314 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1315 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1319 sub beautify_urlpath ($) {
1322 # Ensure url is not an empty link, and if necessary,
1323 # add ./ to avoid colon confusion.
1324 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1328 if ($config{usedirs}) {
1329 $url =~ s!/index.$config{htmlext}$!/!;
1344 if (! $destsources{$to}) {
1349 return $config{url}.beautify_urlpath("/".$to);
1352 if (! defined $from) {
1353 my $u = $local_url || '';
1355 return $u.beautify_urlpath("/".$to);
1358 my $link = abs2rel($to, dirname(htmlpage($from)));
1360 return beautify_urlpath($link);
1363 sub isselflink ($$) {
1364 # Plugins can override this function to support special types
1369 return $page eq $link;
1372 sub htmllink ($$$;@) {
1373 my $lpage=shift; # the page doing the linking
1374 my $page=shift; # the page that will contain the link (different for inline)
1381 if (! $opts{forcesubpage}) {
1382 $bestlink=bestlink($lpage, $link);
1385 $bestlink="$lpage/".lc($link);
1389 if (defined $opts{linktext}) {
1390 $linktext=$opts{linktext};
1393 $linktext=pagetitle(basename($link));
1396 return "<span class=\"selflink\">$linktext</span>"
1397 if length $bestlink && isselflink($page, $bestlink) &&
1398 ! defined $opts{anchor};
1400 if (! $destsources{$bestlink}) {
1401 $bestlink=htmlpage($bestlink);
1403 if (! $destsources{$bestlink}) {
1405 if (length $config{cgiurl}) {
1406 $cgilink = "<a href=\"".
1411 )."\" rel=\"nofollow\">?</a>";
1413 return "<span class=\"createlink\">$cgilink$linktext</span>"
1417 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1418 $bestlink=beautify_urlpath($bestlink);
1420 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1421 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1424 if (defined $opts{anchor}) {
1425 $bestlink.="#".$opts{anchor};
1429 foreach my $attr (qw{rel class title}) {
1430 if (defined $opts{$attr}) {
1431 push @attrs, " $attr=\"$opts{$attr}\"";
1435 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1440 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1443 # Username to display for openid accounts.
1444 sub openiduser ($) {
1447 if (defined $user && $user =~ m!^https?://! &&
1448 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1451 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1452 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1455 # backcompat with old version
1456 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1457 $display=$oid->display;
1460 # Convert "user.somehost.com" to "user [somehost.com]"
1461 # (also "user.somehost.co.uk")
1462 if ($display !~ /\[/) {
1463 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1465 # Convert "http://somehost.com/user" to "user [somehost.com]".
1466 # (also "https://somehost.com/user/")
1467 if ($display !~ /\[/) {
1468 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1470 $display=~s!^https?://!!; # make sure this is removed
1471 eval q{use CGI 'escapeHTML'};
1473 return escapeHTML($display);
1478 # Username to display for emailauth accounts.
1481 if (defined $user && $user =~ m/(.+)@/) {
1483 # remove any characters from not allowed in wiki files
1484 # support use w/o %config set
1485 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1486 $nick=~s/[^$chars]/_/g;
1492 # Some user information should not be exposed in commit metadata, etc.
1493 # This generates a cloaked form of such information.
1496 # cloak email address using http://xmlns.com/foaf/spec/#term_mbox_sha1sum
1497 if ($user=~m/(.+)@/) {
1499 eval q{use Digest::SHA};
1501 return $nick.'@'.Digest::SHA::sha1_hex("mailto:$user");
1508 sub htmlize ($$$$) {
1514 my $oneline = $content !~ /\n/;
1516 if (exists $hooks{htmlize}{$type}) {
1517 $content=$hooks{htmlize}{$type}{call}->(
1519 content => $content,
1523 error("htmlization of $type not supported");
1526 run_hooks(sanitize => sub {
1529 destpage => $destpage,
1530 content => $content,
1535 # hack to get rid of enclosing junk added by markdown
1536 # and other htmlizers/sanitizers
1537 $content=~s/^<p>//i;
1538 $content=~s/<\/p>\n*$//i;
1549 run_hooks(linkify => sub {
1552 destpage => $destpage,
1553 content => $content,
1561 our $preprocess_preview=0;
1562 sub preprocess ($$$;$$) {
1563 my $page=shift; # the page the data comes from
1564 my $destpage=shift; # the page the data will appear in (different for inline)
1569 # Using local because it needs to be set within any nested calls
1571 local $preprocess_preview=$preview if defined $preview;
1578 $params="" if ! defined $params;
1580 if (length $escape) {
1581 return "[[$prefix$command $params]]";
1583 elsif (exists $hooks{preprocess}{$command}) {
1584 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1585 # Note: preserve order of params, some plugins may
1586 # consider it significant.
1588 while ($params =~ m{
1589 (?:([-.\w]+)=)? # 1: named parameter key?
1591 """(.*?)""" # 2: triple-quoted value
1593 "([^"]*?)" # 3: single-quoted value
1595 '''(.*?)''' # 4: triple-single-quote
1597 <<([a-zA-Z]+)\n # 5: heredoc start
1598 (.*?)\n\5 # 6: heredoc value
1600 (\S+) # 7: unquoted value
1602 (?:\s+|$) # delimiter to next param
1612 elsif (defined $3) {
1615 elsif (defined $4) {
1618 elsif (defined $7) {
1621 elsif (defined $6) {
1626 push @params, $key, $val;
1629 push @params, $val, '';
1632 if ($preprocessing{$page}++ > 8) {
1633 # Avoid loops of preprocessed pages preprocessing
1634 # other pages that preprocess them, etc.
1635 return "[[!$command <span class=\"error\">".
1636 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1637 $page, $preprocessing{$page}).
1643 $hooks{preprocess}{$command}{call}->(
1646 destpage => $destpage,
1647 preview => $preprocess_preview,
1653 $ret="[[!$command <span class=\"error\">".
1654 gettext("Error").": $error"."</span>]]";
1658 # use void context during scan pass
1660 $hooks{preprocess}{$command}{call}->(
1663 destpage => $destpage,
1664 preview => $preprocess_preview,
1669 $preprocessing{$page}--;
1673 return "[[$prefix$command $params]]";
1678 if ($config{prefix_directives}) {
1681 \[\[(!) # directive open; 2: prefix
1682 ([-\w]+) # 3: command
1683 ( # 4: the parameters..
1684 \s+ # Must have space if parameters present
1686 (?:[-.\w]+=)? # named parameter key?
1688 """.*?""" # triple-quoted value
1690 "[^"]*?" # single-quoted value
1692 '''.*?''' # triple-single-quote
1694 <<([a-zA-Z]+)\n # 5: heredoc start
1695 (?:.*?)\n\5 # heredoc value
1697 [^"\s\]]+ # unquoted value
1699 \s* # whitespace or end
1702 *)? # 0 or more parameters
1703 \]\] # directive closed
1709 \[\[(!?) # directive open; 2: optional prefix
1710 ([-\w]+) # 3: command
1712 ( # 4: the parameters..
1714 (?:[-.\w]+=)? # named parameter key?
1716 """.*?""" # triple-quoted value
1718 "[^"]*?" # single-quoted value
1720 '''.*?''' # triple-single-quote
1722 <<([a-zA-Z]+)\n # 5: heredoc start
1723 (?:.*?)\n\5 # heredoc value
1725 [^"\s\]]+ # unquoted value
1727 \s* # whitespace or end
1730 *) # 0 or more parameters
1731 \]\] # directive closed
1735 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1744 run_hooks(filter => sub {
1745 $content=shift->(page => $page, destpage => $destpage,
1746 content => $content);
1752 sub check_canedit ($$$;$) {
1759 run_hooks(canedit => sub {
1760 return if defined $canedit;
1761 my $ret=shift->($page, $q, $session);
1766 elsif (ref $ret eq 'CODE') {
1767 $ret->() unless $nonfatal;
1770 elsif (defined $ret) {
1771 error($ret) unless $nonfatal;
1776 return defined $canedit ? $canedit : 1;
1779 sub check_content (@) {
1782 return 1 if ! exists $hooks{checkcontent}; # optimisation
1784 if (exists $pagesources{$params{page}}) {
1786 my %old=map { $_ => 1 }
1787 split("\n", readfile(srcfile($pagesources{$params{page}})));
1788 foreach my $line (split("\n", $params{content})) {
1789 push @diff, $line if ! exists $old{$line};
1791 $params{diff}=join("\n", @diff);
1795 run_hooks(checkcontent => sub {
1796 return if defined $ok;
1797 my $ret=shift->(%params);
1802 elsif (ref $ret eq 'CODE') {
1803 $ret->() unless $params{nonfatal};
1806 elsif (defined $ret) {
1807 error($ret) unless $params{nonfatal};
1813 return defined $ok ? $ok : 1;
1816 sub check_canchange (@) {
1818 my $cgi = $params{cgi};
1819 my $session = $params{session};
1820 my @changes = @{$params{changes}};
1823 foreach my $change (@changes) {
1824 # This untaint is safe because we check file_pruned and
1826 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1827 $file=possibly_foolish_untaint($file);
1828 if (! defined $file || ! length $file ||
1829 file_pruned($file)) {
1830 error(gettext("bad file name %s"), $file);
1833 my $type=pagetype($file);
1834 my $page=pagename($file) if defined $type;
1836 if ($change->{action} eq 'add') {
1840 if ($change->{action} eq 'change' ||
1841 $change->{action} eq 'add') {
1842 if (defined $page) {
1843 check_canedit($page, $cgi, $session);
1847 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1848 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1849 check_canedit($file, $cgi, $session);
1854 elsif ($change->{action} eq 'remove') {
1855 # check_canremove tests to see if the file is present
1856 # on disk. This will fail when a single commit adds a
1857 # file and then removes it again. Avoid the problem
1858 # by not testing the removal in such pairs of changes.
1859 # (The add is still tested, just to make sure that
1860 # no data is added to the repo that a web edit
1862 next if $newfiles{$file};
1864 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1865 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1866 check_canedit(defined $page ? $page : $file, $cgi, $session);
1871 error "unknown action ".$change->{action};
1874 error sprintf(gettext("you are not allowed to change %s"), $file);
1882 # Take an exclusive lock on the wiki to prevent multiple concurrent
1883 # run issues. The lock will be dropped on program exit.
1884 if (! -d $config{wikistatedir}) {
1885 mkdir($config{wikistatedir});
1887 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1888 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1889 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1890 debug("failed to get lock; waiting...");
1891 if (! flock($wikilock, LOCK_EX)) {
1892 error("failed to get lock");
1899 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1900 return close($wikilock) if $wikilock;
1906 sub commit_hook_enabled () {
1907 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1908 error("cannot write to $config{wikistatedir}/commitlock: $!");
1909 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1910 close($commitlock) || error("failed closing commitlock: $!");
1913 close($commitlock) || error("failed closing commitlock: $!");
1917 sub disable_commit_hook () {
1918 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1919 error("cannot write to $config{wikistatedir}/commitlock: $!");
1920 if (! flock($commitlock, 2)) { # LOCK_EX
1921 error("failed to get commit lock");
1926 sub enable_commit_hook () {
1927 return close($commitlock) if $commitlock;
1932 %oldrenderedfiles=%pagectime=();
1933 my $rebuild=$config{rebuild};
1935 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1936 %destsources=%renderedfiles=%pagecase=%pagestate=
1937 %depends_simple=%typedlinks=%oldtypedlinks=();
1940 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1941 if (-e "$config{wikistatedir}/index") {
1942 system("ikiwiki-transition", "indexdb", $config{srcdir});
1943 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1946 # gettime on first build
1947 $config{gettime}=1 unless defined $config{gettime};
1952 my $index=Storable::fd_retrieve($in);
1953 if (! defined $index) {
1958 if (exists $index->{version} && ! ref $index->{version}) {
1959 $pages=$index->{page};
1960 %wikistate=%{$index->{state}};
1961 # Handle plugins that got disabled by loading a new setup.
1962 if (exists $config{setupfile}) {
1963 require IkiWiki::Setup;
1964 IkiWiki::Setup::disabled_plugins(
1965 grep { ! $loaded_plugins{$_} } keys %wikistate);
1973 foreach my $src (keys %$pages) {
1974 my $d=$pages->{$src};
1976 if (exists $d->{page} && ! $rebuild) {
1980 $page=pagename($src);
1982 $pagectime{$page}=$d->{ctime};
1983 $pagesources{$page}=$src;
1985 $pagemtime{$page}=$d->{mtime};
1986 $renderedfiles{$page}=$d->{dest};
1987 if (exists $d->{links} && ref $d->{links}) {
1988 $links{$page}=$d->{links};
1989 $oldlinks{$page}=[@{$d->{links}}];
1991 if (ref $d->{depends_simple} eq 'ARRAY') {
1993 $depends_simple{$page}={
1994 map { $_ => 1 } @{$d->{depends_simple}}
1997 elsif (exists $d->{depends_simple}) {
1998 $depends_simple{$page}=$d->{depends_simple};
2000 if (exists $d->{dependslist}) {
2003 map { $_ => $DEPEND_CONTENT }
2004 @{$d->{dependslist}}
2007 elsif (exists $d->{depends} && ! ref $d->{depends}) {
2009 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
2011 elsif (exists $d->{depends}) {
2012 $depends{$page}=$d->{depends};
2014 if (exists $d->{state}) {
2015 $pagestate{$page}=$d->{state};
2017 if (exists $d->{typedlinks}) {
2018 $typedlinks{$page}=$d->{typedlinks};
2020 while (my ($type, $links) = each %{$typedlinks{$page}}) {
2021 next unless %$links;
2022 $oldtypedlinks{$page}{$type} = {%$links};
2026 $oldrenderedfiles{$page}=[@{$d->{dest}}];
2028 foreach my $page (keys %pagesources) {
2029 $pagecase{lc $page}=$page;
2031 foreach my $page (keys %renderedfiles) {
2032 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
2034 $lastrev=$index->{lastrev};
2035 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
2040 run_hooks(savestate => sub { shift->() });
2042 my @plugins=keys %loaded_plugins;
2044 if (! -d $config{wikistatedir}) {
2045 mkdir($config{wikistatedir});
2047 my $newfile="$config{wikistatedir}/indexdb.new";
2048 my $cleanup = sub { unlink($newfile) };
2049 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
2052 foreach my $page (keys %pagemtime) {
2053 next unless $pagemtime{$page};
2054 my $src=$pagesources{$page};
2056 $index{page}{$src}={
2058 ctime => $pagectime{$page},
2059 mtime => $pagemtime{$page},
2060 dest => $renderedfiles{$page},
2061 links => $links{$page},
2064 if (exists $depends{$page}) {
2065 $index{page}{$src}{depends} = $depends{$page};
2068 if (exists $depends_simple{$page}) {
2069 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2072 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2073 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2076 if (exists $pagestate{$page}) {
2077 $index{page}{$src}{state}=$pagestate{$page};
2082 foreach my $id (@plugins) {
2083 $index{state}{$id}={}; # used to detect disabled plugins
2084 foreach my $key (keys %{$wikistate{$id}}) {
2085 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2089 $index{lastrev}=$lastrev;
2090 $index{underlayfiles}=\@underlayfiles;
2092 $index{version}="3";
2093 my $ret=Storable::nstore_fd(\%index, $out);
2094 return if ! defined $ret || ! $ret;
2095 close $out || error("failed saving to $newfile: $!", $cleanup);
2096 rename($newfile, "$config{wikistatedir}/indexdb") ||
2097 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2102 sub template_file ($) {
2105 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2107 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2108 $template=srcfile($pagesources{$tpage}, 1);
2112 $template=srcfile($tpage, 1);
2115 if (defined $template) {
2116 return $template, $tpage, 1 if wantarray;
2120 $name=~s:/::; # avoid path traversal
2121 foreach my $dir ($config{templatedir},
2122 "$installdir/share/ikiwiki/templates") {
2123 if (-e "$dir/$name") {
2124 $template="$dir/$name";
2128 if (defined $template) {
2129 return $template, $tpage if wantarray;
2137 sub template_depends ($$;@) {
2141 my ($filename, $tpage, $untrusted)=template_file($name);
2142 if (! defined $filename) {
2143 error(sprintf(gettext("template %s not found"), $name))
2146 if (defined $page && defined $tpage) {
2147 add_depends($page, $tpage);
2152 my $text_ref = shift;
2153 ${$text_ref} = decode_utf8(${$text_ref});
2154 run_hooks(readtemplate => sub {
2155 ${$text_ref} = shift->(
2158 content => ${$text_ref},
2159 untrusted => $untrusted,
2163 loop_context_vars => 1,
2164 die_on_bad_params => 0,
2165 parent_global_vars => 1,
2166 filename => $filename,
2168 ($untrusted ? (no_includes => 1) : ()),
2170 return @opts if wantarray;
2172 require HTML::Template;
2173 return HTML::Template->new(@opts);
2176 sub template ($;@) {
2177 template_depends(shift, undef, @_);
2180 sub templateactions ($$) {
2186 run_hooks(pageactions => sub {
2187 push @actions, map { { action => $_ } }
2188 grep { defined } shift->(page => $page);
2190 $template->param(actions => \@actions);
2192 if ($config{cgiurl} && exists $hooks{auth}) {
2193 $template->param(prefsurl => cgiurl(do => "prefs"));
2197 if ($have_actions || @actions) {
2198 $template->param(have_actions => 1);
2205 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2206 error 'hook requires type, call, and id parameters';
2209 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2211 $hooks{$param{type}}{$param{id}}=\%param;
2215 sub run_hooks ($$) {
2216 # Calls the given sub for each hook of the given type,
2217 # passing it the hook function to call.
2221 if (exists $hooks{$type}) {
2222 my (@first, @middle, @last);
2223 foreach my $id (keys %{$hooks{$type}}) {
2224 if ($hooks{$type}{$id}{first}) {
2227 elsif ($hooks{$type}{$id}{last}) {
2234 foreach my $id (@first, @middle, @last) {
2235 $sub->($hooks{$type}{$id}{call});
2243 $hooks{rcs}{rcs_update}{call}->(@_);
2246 sub rcs_prepedit ($) {
2247 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2250 sub rcs_commit (@) {
2251 $hooks{rcs}{rcs_commit}{call}->(@_);
2254 sub rcs_commit_staged (@) {
2255 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2259 $hooks{rcs}{rcs_add}{call}->(@_);
2262 sub rcs_remove ($) {
2263 $hooks{rcs}{rcs_remove}{call}->(@_);
2266 sub rcs_rename ($$) {
2267 $hooks{rcs}{rcs_rename}{call}->(@_);
2270 sub rcs_recentchanges ($) {
2271 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2274 sub rcs_diff ($;$) {
2275 $hooks{rcs}{rcs_diff}{call}->(@_);
2278 sub rcs_getctime ($) {
2279 $hooks{rcs}{rcs_getctime}{call}->(@_);
2282 sub rcs_getmtime ($) {
2283 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2286 sub rcs_receive () {
2287 $hooks{rcs}{rcs_receive}{call}->();
2290 sub add_depends ($$;$) {
2293 my $deptype=shift || $DEPEND_CONTENT;
2295 # Is the pagespec a simple page name?
2296 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2297 $pagespec !~ /[\s*?()!]/) {
2298 $depends_simple{$page}{lc $pagespec} |= $deptype;
2302 # Add explicit dependencies for influences.
2303 my $sub=pagespec_translate($pagespec);
2304 return unless defined $sub;
2305 foreach my $p (keys %pagesources) {
2306 my $r=$sub->($p, location => $page);
2307 my $i=$r->influences;
2308 my $static=$r->influences_static;
2309 foreach my $k (keys %$i) {
2310 next unless $r || $static || $k eq $page;
2311 $depends_simple{$page}{lc $k} |= $i->{$k};
2316 $depends{$page}{$pagespec} |= $deptype;
2322 foreach my $type (@_) {
2323 if ($type eq 'presence') {
2324 $deptype |= $DEPEND_PRESENCE;
2326 elsif ($type eq 'links') {
2327 $deptype |= $DEPEND_LINKS;
2329 elsif ($type eq 'content') {
2330 $deptype |= $DEPEND_CONTENT;
2336 my $file_prune_regexp;
2337 sub file_pruned ($) {
2340 if (defined $config{include} && length $config{include}) {
2341 return 0 if $file =~ m/$config{include}/;
2344 if (! defined $file_prune_regexp) {
2345 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2346 $file_prune_regexp=qr/$file_prune_regexp/;
2348 return $file =~ m/$file_prune_regexp/;
2351 sub define_gettext () {
2352 # If translation is needed, redefine the gettext function to do it.
2353 # Otherwise, it becomes a quick no-op.
2356 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2357 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2358 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2360 $gettext_obj=eval q{
2361 use Locale::gettext q{textdomain};
2362 Locale::gettext->domain('ikiwiki')
2367 no warnings 'redefine';
2369 $getobj->() if $getobj;
2371 $gettext_obj->get(shift);
2378 $getobj->() if $getobj;
2380 $gettext_obj->nget(@_);
2383 return ($_[2] == 1 ? $_[0] : $_[1])
2401 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2405 # Injects a new function into the symbol table to replace an
2406 # exported function.
2409 # This is deep ugly perl foo, beware.
2412 if (! defined $params{parent}) {
2413 $params{parent}='::';
2414 $params{old}=\&{$params{name}};
2415 $params{name}=~s/.*:://;
2417 my $parent=$params{parent};
2418 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2419 $ns = $params{parent} . $ns;
2420 inject(%params, parent => $ns) unless $ns eq '::main::';
2421 *{$ns . $params{name}} = $params{call}
2422 if exists ${$ns}{$params{name}} &&
2423 \&{${$ns}{$params{name}}} == $params{old};
2429 sub add_link ($$;$) {
2434 push @{$links{$page}}, $link
2435 unless grep { $_ eq $link } @{$links{$page}};
2437 if (defined $type) {
2438 $typedlinks{$page}{$type}{$link} = 1;
2442 sub add_autofile ($$$) {
2445 my $generator=shift;
2447 $autofiles{$file}{plugin}=$plugin;
2448 $autofiles{$file}{generator}=$generator;
2452 return LWP::UserAgent->new(
2453 cookie_jar => $config{cookiejar},
2454 env_proxy => 1, # respect proxy env vars
2455 agent => $config{useragent},
2459 sub sortspec_translate ($$) {
2461 my $reverse = shift;
2467 (-?) # group 1: perhaps negated
2470 \w+\([^\)]*\) # command(params)
2472 [^\s]+ # or anything else
2480 if ($word =~ m/^(\w+)\((.*)\)$/) {
2481 # command with parameters
2485 elsif ($word !~ m/^\w+$/) {
2486 error(sprintf(gettext("invalid sort type %s"), $word));
2497 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2498 if (defined $params) {
2499 push @data, $params;
2500 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2503 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2507 error(sprintf(gettext("unknown sort type %s"), $word));
2511 if (! length $code) {
2512 # undefined sorting method... sort arbitrarily
2521 return eval 'sub { '.$code.' }';
2524 sub pagespec_translate ($) {
2527 # Convert spec to perl code.
2531 \s* # ignore whitespace
2532 ( # 1: match a single word
2539 \w+\([^\)]*\) # command(params)
2541 [^\s()]+ # any other text
2543 \s* # ignore whitespace
2546 if (lc $word eq 'and') {
2549 elsif (lc $word eq 'or') {
2552 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2555 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2556 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2558 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2561 push @data, qq{unknown function in pagespec "$word"};
2562 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2567 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2571 if (! length $code) {
2572 $code="IkiWiki::FailReason->new('empty pagespec')";
2576 return eval 'sub { my $page=shift; '.$code.' }';
2579 sub pagespec_match ($$;@) {
2584 # Backwards compatability with old calling convention.
2586 unshift @params, 'location';
2589 my $sub=pagespec_translate($spec);
2590 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2592 return $sub->($page, @params);
2595 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2597 # Not exported yet, but could be in future if it is generally useful.
2598 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2599 # which is "more internal".
2600 sub sort_pages ($$;@) {
2604 $sort = sortspec_translate($sort, $params{reverse});
2605 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2608 sub pagespec_match_list ($$;@) {
2613 # Backwards compatability with old calling convention.
2615 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2616 $params{list}=$page;
2617 $page=$params{location}; # ugh!
2620 my $sub=pagespec_translate($pagespec);
2621 error "syntax error in pagespec \"$pagespec\""
2623 my $sort=sortspec_translate($params{sort}, $params{reverse})
2624 if defined $params{sort};
2627 if (exists $params{list}) {
2628 @candidates=exists $params{filter}
2629 ? grep { ! $params{filter}->($_) } @{$params{list}}
2633 @candidates=exists $params{filter}
2634 ? grep { ! $params{filter}->($_) } keys %pagesources
2635 : keys %pagesources;
2638 # clear params, remainder is passed to pagespec
2639 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2640 my $num=$params{num};
2641 delete @params{qw{num deptype reverse sort filter list}};
2643 # when only the top matches will be returned, it's efficient to
2644 # sort before matching to pagespec,
2645 if (defined $num && defined $sort) {
2646 @candidates=IkiWiki::SortSpec::sort_pages(
2647 $sort, @candidates);
2653 my $accum=IkiWiki::SuccessReason->new();
2654 foreach my $p (@candidates) {
2655 my $r=$sub->($p, %params, location => $page);
2656 error(sprintf(gettext("cannot match pages: %s"), $r))
2657 if $r->isa("IkiWiki::ErrorReason");
2658 unless ($r || $r->influences_static) {
2659 $r->remove_influence($p);
2664 last if defined $num && ++$count == $num;
2668 # Add simple dependencies for accumulated influences.
2669 my $i=$accum->influences;
2670 foreach my $k (keys %$i) {
2671 $depends_simple{$page}{lc $k} |= $i->{$k};
2674 # when all matches will be returned, it's efficient to
2675 # sort after matching
2676 if (! defined $num && defined $sort) {
2677 return IkiWiki::SortSpec::sort_pages(
2685 sub pagespec_valid ($) {
2688 return defined pagespec_translate($spec);
2692 my $re=quotemeta(shift);
2698 package IkiWiki::FailReason;
2701 '""' => sub { $_[0][0] },
2703 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2704 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2705 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2709 our @ISA = 'IkiWiki::SuccessReason';
2711 package IkiWiki::SuccessReason;
2713 # A blessed array-ref:
2715 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2717 # - if absent or false, the influences of this evaluation are "static",
2718 # see the influences_static method
2719 # - if true, they are dynamic (not static)
2720 # [1]{any other key}:
2721 # the dependency types of influences, as returned by the influences method
2724 # in string context, it's the human-readable reason
2725 '""' => sub { $_[0][0] },
2726 # in boolean context, SuccessReason is 1 and FailReason is 0
2728 # negating a result gives the opposite result with the same influences
2729 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2730 # A & B = (A ? B : A) with the influences of both
2731 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2732 # A | B = (A ? A : B) with the influences of both
2733 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2737 # SuccessReason->new("human-readable reason", page => deptype, ...)
2742 return bless [$value, {@_}], $class;
2745 # influences(): return a reference to a copy of the hash
2746 # { page => dependency type } describing the pages that indirectly influenced
2747 # this result, but would not cause a dependency through ikiwiki's core
2750 # See [[todo/dependency_types]] for extensive discussion of what this means.
2752 # influences(page => deptype, ...): remove all influences, replace them
2753 # with the arguments, and return a reference to a copy of the new influences.
2757 $this->[1]={@_} if @_;
2758 my %i=%{$this->[1]};
2763 # True if this result has the same influences whichever page it matches,
2764 # For instance, whether bar matches backlink(foo) is influenced only by
2765 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2766 # which does not mention bar anywhere.
2768 # False if this result would have different influences when matching
2769 # different pages. For instance, when testing whether link(foo) matches bar,
2770 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2771 # bar's links could change the outcome; so its influences are not the same
2772 # as when testing whether link(foo) matches baz.
2774 # Static influences are one of the things that make pagespec_match_list
2775 # more efficient than repeated calls to pagespec_match.
2777 sub influences_static {
2778 return ! $_[0][1]->{""};
2781 # Change the influences of $this to be the influences of "$this & $other"
2782 # or "$this | $other".
2784 # If both $this and $other are either successful or have influences,
2785 # or this is an "or" operation, the result has all the influences from
2786 # either of the arguments. It has dynamic influences if either argument
2787 # has dynamic influences.
2789 # If this is an "and" operation, and at least one argument is a
2790 # FailReason with no influences, the result has no influences, and they
2791 # are not dynamic. For instance, link(foo) matching bar is influenced
2792 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2793 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2794 # bar, because it would be false however often you edit bar.
2796 sub merge_influences {
2801 # This "if" is odd because it needs to avoid negating $this
2802 # or $other, which would alter the objects in-place. Be careful.
2803 if (! $anded || (($this || %{$this->[1]}) &&
2804 ($other || %{$other->[1]}))) {
2805 foreach my $influence (keys %{$other->[1]}) {
2806 $this->[1]{$influence} |= $other->[1]{$influence};
2815 # Change $this so it is not considered to be influenced by $torm.
2817 sub remove_influence {
2821 delete $this->[1]{$torm};
2824 package IkiWiki::ErrorReason;
2826 our @ISA = 'IkiWiki::FailReason';
2828 package IkiWiki::PageSpec;
2834 if ($path =~ m!^\.(/|$)!) {
2836 $from=~s#/?[^/]+$## if defined $from;
2838 $path="$from/$path" if defined $from && length $from;
2842 $path = "" unless defined $path;
2851 sub match_glob ($$;@) {
2856 $glob=derel($glob, $params{location});
2858 # Instead of converting the glob to a regex every time,
2859 # cache the compiled regex to save time.
2860 my $re=$glob_cache{$glob};
2861 unless (defined $re) {
2862 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2865 if (! IkiWiki::isinternal($page) || $params{internal}) {
2866 return IkiWiki::SuccessReason->new("$glob matches $page");
2869 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2873 return IkiWiki::FailReason->new("$glob does not match $page");
2877 sub match_internal ($$;@) {
2878 return match_glob(shift, shift, @_, internal => 1)
2881 sub match_page ($$;@) {
2883 my $match=match_glob($page, shift, @_);
2885 my $source=exists $IkiWiki::pagesources{$page} ?
2886 $IkiWiki::pagesources{$page} :
2887 $IkiWiki::delpagesources{$page};
2888 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2889 if (! defined $type) {
2890 return IkiWiki::FailReason->new("$page is not a page");
2896 sub match_link ($$;@) {
2901 $link=derel($link, $params{location});
2902 my $from=exists $params{location} ? $params{location} : '';
2903 my $linktype=$params{linktype};
2905 if (defined $linktype) {
2906 $qualifier=" with type $linktype";
2909 my $links = $IkiWiki::links{$page};
2910 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2911 unless $links && @{$links};
2912 my $bestlink = IkiWiki::bestlink($from, $link);
2913 foreach my $p (@{$links}) {
2914 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2916 if (length $bestlink) {
2917 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2918 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2922 if (match_glob($p, $link, %params)) {
2923 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2925 my ($p_rel)=$p=~/^\/?(.*)/;
2927 if (match_glob($p_rel, $link, %params)) {
2928 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2932 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2935 sub match_backlink ($$;@) {
2939 if ($testpage eq '.') {
2940 $testpage = $params{'location'}
2942 my $ret=match_link($testpage, $page, @_);
2943 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2947 sub match_created_before ($$;@) {
2952 $testpage=derel($testpage, $params{location});
2954 if (exists $IkiWiki::pagectime{$testpage}) {
2955 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2956 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2959 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2963 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2967 sub match_created_after ($$;@) {
2972 $testpage=derel($testpage, $params{location});
2974 if (exists $IkiWiki::pagectime{$testpage}) {
2975 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2976 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2979 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2983 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2987 sub match_creation_day ($$;@) {
2990 if ($d !~ /^\d+$/) {
2991 return IkiWiki::ErrorReason->new("invalid day $d");
2993 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2994 return IkiWiki::SuccessReason->new('creation_day matched');
2997 return IkiWiki::FailReason->new('creation_day did not match');
3001 sub match_creation_month ($$;@) {
3004 if ($m !~ /^\d+$/) {
3005 return IkiWiki::ErrorReason->new("invalid month $m");
3007 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
3008 return IkiWiki::SuccessReason->new('creation_month matched');
3011 return IkiWiki::FailReason->new('creation_month did not match');
3015 sub match_creation_year ($$;@) {
3018 if ($y !~ /^\d+$/) {
3019 return IkiWiki::ErrorReason->new("invalid year $y");
3021 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
3022 return IkiWiki::SuccessReason->new('creation_year matched');
3025 return IkiWiki::FailReason->new('creation_year did not match');
3029 sub match_user ($$;@) {
3034 if (! exists $params{user}) {
3035 return IkiWiki::ErrorReason->new("no user specified");
3038 my $regexp=IkiWiki::glob2re($user);
3040 if (defined $params{user} && $params{user}=~$regexp) {
3041 return IkiWiki::SuccessReason->new("user is $user");
3043 elsif (! defined $params{user}) {
3044 return IkiWiki::FailReason->new("not logged in");
3047 return IkiWiki::FailReason->new("user is $params{user}, not $user");
3051 sub match_admin ($$;@) {
3056 if (! exists $params{user}) {
3057 return IkiWiki::ErrorReason->new("no user specified");
3060 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3061 return IkiWiki::SuccessReason->new("user is an admin");
3063 elsif (! defined $params{user}) {
3064 return IkiWiki::FailReason->new("not logged in");
3067 return IkiWiki::FailReason->new("user is not an admin");
3071 sub match_ip ($$;@) {
3076 if (! exists $params{ip}) {
3077 return IkiWiki::ErrorReason->new("no IP specified");
3080 my $regexp=IkiWiki::glob2re(lc $ip);
3082 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3083 return IkiWiki::SuccessReason->new("IP is $ip");
3086 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3090 package IkiWiki::SortSpec;
3092 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3093 # are easily available in this namespace, for cmp functions to use them.
3100 IkiWiki::pagetitle(IkiWiki::basename($a))
3102 IkiWiki::pagetitle(IkiWiki::basename($b))
3105 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3106 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3107 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }