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 my $message = "[$config{wikiname}] ".join(" ", @_);
847 utf8::encode($message);
848 Sys::Syslog::syslog($type, "%s", $message);
851 print STDERR "failed to syslog: $@" unless $log_failed;
857 elsif (! $config{cgi}) {
861 return print STDERR "@_\n";
865 sub possibly_foolish_untaint ($) {
867 my ($untainted)=$tainted=~/(.*)/s;
887 return exists $pagesources{$page} &&
888 $pagesources{$page} =~ /\._([^.]+)$/;
894 if ($file =~ /\.([^.]+)$/) {
895 return $1 if exists $hooks{htmlize}{$1};
897 my $base=basename($file);
898 if (exists $hooks{htmlize}{$base} &&
899 $hooks{htmlize}{$base}{noextension}) {
910 if (exists $pagename_cache{$file}) {
911 return $pagename_cache{$file};
914 my $type=pagetype($file);
916 $page=~s/\Q.$type\E*$//
917 if defined $type && !$hooks{htmlize}{$type}{keepextension}
918 && !$hooks{htmlize}{$type}{noextension};
919 if ($config{indexpages} && $page=~/(.*)\/index$/) {
923 $pagename_cache{$file} = $page;
927 sub newpagefile ($$) {
931 if (! $config{indexpages} || $page eq 'index') {
932 return $page.".".$type;
935 return $page."/index.".$type;
939 sub targetpage ($$;$) {
944 if (defined $filename) {
945 return $page."/".$filename.".".$ext;
947 elsif (! $config{usedirs} || $page eq 'index') {
948 return $page.".".$ext;
951 return $page."/index.".$ext;
958 return targetpage($page, $config{htmlext});
965 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
966 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
967 return "$dir/$file", stat(_) if -e "$dir/$file";
969 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
974 return (srcfile_stat(@_))[0];
977 sub add_literal_underlay ($) {
980 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
981 unshift @{$config{underlaydirs}}, $dir;
985 sub add_underlay ($) {
989 $dir="$config{underlaydirbase}/$dir";
992 add_literal_underlay($dir);
993 # why does it return 1? we just don't know
997 sub readfile ($;$$) {
1003 error("cannot read a symlink ($file)");
1007 open (my $in, "<", $file) || error("failed to read $file: $!");
1008 binmode($in) if ($binary);
1009 return \*$in if $wantfd;
1011 # check for invalid utf-8, and toss it back to avoid crashes
1012 if (! utf8::valid($ret)) {
1013 $ret=encode_utf8($ret);
1015 close $in || error("failed to read $file: $!");
1019 sub prep_writefile ($$) {
1024 while (length $test) {
1025 if (-l "$destdir/$test") {
1026 error("cannot write to a symlink ($test)");
1028 if (-f _ && $test ne $file) {
1029 # Remove conflicting file.
1030 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1031 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1033 unlink("$destdir/$test");
1039 $test=dirname($test);
1042 my $dir=dirname("$destdir/$file");
1045 foreach my $s (split(m!/+!, $dir)) {
1048 mkdir($d) || error("failed to create directory $d: $!");
1056 sub writefile ($$$;$$) {
1057 my $file=shift; # can include subdirs
1058 my $destdir=shift; # directory to put file in
1063 prep_writefile($file, $destdir);
1065 my $newfile="$destdir/$file.ikiwiki-new";
1067 error("cannot write to a symlink ($newfile)");
1070 my $cleanup = sub { unlink($newfile) };
1071 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1072 binmode($out) if ($binary);
1074 $writer->(\*$out, $cleanup);
1077 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1079 close $out || error("failed saving $newfile: $!", $cleanup);
1080 rename($newfile, "$destdir/$file") ||
1081 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1087 sub will_render ($$;$) {
1092 # Important security check for independently created files.
1093 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1094 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1095 my $from_other_page=0;
1096 # Expensive, but rarely runs.
1097 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1100 dirname($_) eq $dest
1101 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1107 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1108 unless $from_other_page;
1111 # If $dest exists as a directory, remove conflicting files in it
1112 # rendered from other pages.
1114 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1115 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1116 if (dirname($f) eq $dest) {
1117 unlink("$config{destdir}/$f");
1118 rmdir(dirname("$config{destdir}/$f"));
1124 if (! $clear || $cleared{$page}) {
1125 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1128 foreach my $old (@{$renderedfiles{$page}}) {
1129 delete $destsources{$old};
1131 $renderedfiles{$page}=[$dest];
1134 $destsources{$dest}=$page;
1144 if ($link=~s/^\/+//) {
1152 $l.="/" if length $l;
1155 if (exists $pagesources{$l}) {
1158 elsif (exists $pagecase{lc $l}) {
1159 return $pagecase{lc $l};
1161 } while $cwd=~s{/?[^/]+$}{};
1163 if (length $config{userdir}) {
1164 my $l = "$config{userdir}/".lc($link);
1165 if (exists $pagesources{$l}) {
1168 elsif (exists $pagecase{lc $l}) {
1169 return $pagecase{lc $l};
1173 #print STDERR "warning: page $page, broken link: $link\n";
1177 sub isinlinableimage ($) {
1180 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1183 sub pagetitle ($;$) {
1185 my $unescaped=shift;
1188 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1191 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1199 # support use w/o %config set
1200 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1201 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1207 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1208 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1215 my $cgiurl=$local_cgiurl;
1217 if (exists $params{cgiurl}) {
1218 $cgiurl=$params{cgiurl};
1219 delete $params{cgiurl};
1227 join("&", map $_."=".uri_escape_utf8($params{$_}), sort(keys %params));
1230 sub cgiurl_abs (@) {
1232 URI->new_abs(cgiurl(@_), $config{cgiurl});
1235 # Same as cgiurl_abs, but when the user connected using https,
1236 # will be a https url even if the cgiurl is normally a http url.
1238 # This should be used for anything involving emailing a login link,
1239 # because a https session cookie will not be sent over http.
1240 sub cgiurl_abs_samescheme (@) {
1241 my $u=cgiurl_abs(@_);
1242 if (($ENV{HTTPS} && lc $ENV{HTTPS} ne "off")) {
1243 $u=~s/^http:/https:/i;
1251 return $local_url if ! defined $page;
1253 $page=htmlpage($page);
1255 $page=~s/[^\/]+\//..\//g;
1263 return $url unless defined $urlbase && length $urlbase;
1266 URI->new_abs($url, $urlbase)->as_string;
1270 # Work around very innefficient behavior in File::Spec if abs2rel
1271 # is passed two relative paths. It's much faster if paths are
1272 # absolute! (Debian bug #376658; fixed in debian unstable now)
1277 my $ret=File::Spec->abs2rel($path, $base);
1278 $ret=~s/^// if defined $ret;
1282 sub displaytime ($;$$) {
1283 # Plugins can override this function to mark up the time to
1285 my $time=formattime($_[0], $_[1]);
1286 if ($config{html5}) {
1287 return '<time datetime="'.date_3339($_[0]).'"'.
1288 ($_[2] ? ' pubdate="pubdate"' : '').
1289 '>'.$time.'</time>';
1292 return '<span class="date">'.$time.'</span>';
1296 sub formattime ($;$) {
1297 # Plugins can override this function to format the time.
1300 if (! defined $format) {
1301 $format=$config{timeformat};
1304 return strftime_utf8($format, localtime($time));
1307 my $strftime_encoding;
1309 # strftime didn't know about encodings in older Perl, so make sure
1310 # its output is properly treated as utf8.
1311 # Note that this does not handle utf-8 in the format string.
1312 my $result = POSIX::strftime(@_);
1314 if (Encode::is_utf8($result)) {
1318 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1319 unless defined $strftime_encoding;
1321 ? Encode::decode($strftime_encoding, $result)
1328 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1329 POSIX::setlocale(&POSIX::LC_TIME, "C");
1330 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1331 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1335 sub beautify_urlpath ($) {
1338 # Ensure url is not an empty link, and if necessary,
1339 # add ./ to avoid colon confusion.
1340 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1344 if ($config{usedirs}) {
1345 $url =~ s!/index.$config{htmlext}$!/!;
1360 if (! $destsources{$to}) {
1365 return $config{url}.beautify_urlpath("/".$to);
1368 if (! defined $from) {
1369 my $u = $local_url || '';
1371 return $u.beautify_urlpath("/".$to);
1374 my $link = abs2rel($to, dirname(htmlpage($from)));
1376 return beautify_urlpath($link);
1379 sub isselflink ($$) {
1380 # Plugins can override this function to support special types
1385 return $page eq $link;
1388 sub htmllink ($$$;@) {
1389 my $lpage=shift; # the page doing the linking
1390 my $page=shift; # the page that will contain the link (different for inline)
1397 if (! $opts{forcesubpage}) {
1398 $bestlink=bestlink($lpage, $link);
1401 $bestlink="$lpage/".lc($link);
1405 if (defined $opts{linktext}) {
1406 $linktext=$opts{linktext};
1409 $linktext=pagetitle(basename($link));
1412 return "<span class=\"selflink\">$linktext</span>"
1413 if length $bestlink && isselflink($page, $bestlink) &&
1414 ! defined $opts{anchor};
1416 if (! $destsources{$bestlink}) {
1417 $bestlink=htmlpage($bestlink);
1419 if (! $destsources{$bestlink}) {
1421 if (length $config{cgiurl}) {
1422 $cgilink = "<a href=\"".
1427 )."\" rel=\"nofollow\">?</a>";
1429 return "<span class=\"createlink\">$cgilink$linktext</span>"
1433 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1434 $bestlink=beautify_urlpath($bestlink);
1436 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1437 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1440 if (defined $opts{anchor}) {
1441 $bestlink.="#".$opts{anchor};
1445 foreach my $attr (qw{rel class title}) {
1446 if (defined $opts{$attr}) {
1447 push @attrs, " $attr=\"$opts{$attr}\"";
1451 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1456 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1459 # Username to display for openid accounts.
1460 sub openiduser ($) {
1463 if (defined $user && $user =~ m!^https?://! &&
1464 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1467 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1468 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1471 # backcompat with old version
1472 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1473 $display=$oid->display;
1476 # Convert "user.somehost.com" to "user [somehost.com]"
1477 # (also "user.somehost.co.uk")
1478 if ($display !~ /\[/) {
1479 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1481 # Convert "http://somehost.com/user" to "user [somehost.com]".
1482 # (also "https://somehost.com/user/")
1483 if ($display !~ /\[/) {
1484 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1486 $display=~s!^https?://!!; # make sure this is removed
1487 eval q{use CGI 'escapeHTML'};
1489 return escapeHTML($display);
1494 # Username to display for emailauth accounts.
1497 if (defined $user && $user =~ m/(.+)@/) {
1499 # remove any characters from not allowed in wiki files
1500 # support use w/o %config set
1501 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1502 $nick=~s/[^$chars]/_/g;
1508 # Some user information should not be exposed in commit metadata, etc.
1509 # This generates a cloaked form of such information.
1512 # cloak email address using http://xmlns.com/foaf/spec/#term_mbox_sha1sum
1513 if ($user=~m/(.+)@/) {
1515 eval q{use Digest::SHA};
1517 return $nick.'@'.Digest::SHA::sha1_hex("mailto:$user");
1524 sub htmlize ($$$$) {
1530 my $oneline = $content !~ /\n/;
1532 if (exists $hooks{htmlize}{$type}) {
1533 $content=$hooks{htmlize}{$type}{call}->(
1535 content => $content,
1539 error("htmlization of $type not supported");
1542 run_hooks(sanitize => sub {
1545 destpage => $destpage,
1546 content => $content,
1551 # hack to get rid of enclosing junk added by markdown
1552 # and other htmlizers/sanitizers
1553 $content=~s/^<p>//i;
1554 $content=~s/<\/p>\n*$//i;
1565 run_hooks(linkify => sub {
1568 destpage => $destpage,
1569 content => $content,
1577 our $preprocess_preview=0;
1578 sub preprocess ($$$;$$) {
1579 my $page=shift; # the page the data comes from
1580 my $destpage=shift; # the page the data will appear in (different for inline)
1585 # Using local because it needs to be set within any nested calls
1587 local $preprocess_preview=$preview if defined $preview;
1594 $params="" if ! defined $params;
1596 if (length $escape) {
1597 return "[[$prefix$command $params]]";
1599 elsif (exists $hooks{preprocess}{$command}) {
1600 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1601 # Note: preserve order of params, some plugins may
1602 # consider it significant.
1604 while ($params =~ m{
1605 (?:([-.\w]+)=)? # 1: named parameter key?
1607 """(.*?)""" # 2: triple-quoted value
1609 "([^"]*?)" # 3: single-quoted value
1611 '''(.*?)''' # 4: triple-single-quote
1613 <<([a-zA-Z]+)\n # 5: heredoc start
1614 (.*?)\n\5 # 6: heredoc value
1616 (\S+) # 7: unquoted value
1618 (?:\s+|$) # delimiter to next param
1628 elsif (defined $3) {
1631 elsif (defined $4) {
1634 elsif (defined $7) {
1637 elsif (defined $6) {
1642 push @params, $key, $val;
1645 push @params, $val, '';
1648 if ($preprocessing{$page}++ > 8) {
1649 # Avoid loops of preprocessed pages preprocessing
1650 # other pages that preprocess them, etc.
1651 return "[[!$command <span class=\"error\">".
1652 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1653 $page, $preprocessing{$page}).
1659 $hooks{preprocess}{$command}{call}->(
1662 destpage => $destpage,
1663 preview => $preprocess_preview,
1669 eval q{use HTML::Entities};
1670 $error = encode_entities($error);
1671 # Also encode most ASCII punctuation
1672 # as entities so that error messages
1673 # are not interpreted as Markdown etc.
1674 $error = encode_entities($error, '[](){}!#$%*?@^`|~'."\\");
1675 $ret="[[!$command <span class=\"error\">".
1676 gettext("Error").": $error"."</span>]]";
1680 # use void context during scan pass
1682 $hooks{preprocess}{$command}{call}->(
1685 destpage => $destpage,
1686 preview => $preprocess_preview,
1691 $preprocessing{$page}--;
1695 return "[[$prefix$command $params]]";
1700 if ($config{prefix_directives}) {
1703 \[\[(!) # directive open; 2: prefix
1704 ([-\w]+) # 3: command
1705 ( # 4: the parameters..
1706 \s+ # Must have space if parameters present
1708 (?:[-.\w]+=)? # named parameter key?
1710 """.*?""" # triple-quoted value
1712 "[^"]*?" # single-quoted value
1714 '''.*?''' # triple-single-quote
1716 <<([a-zA-Z]+)\n # 5: heredoc start
1717 (?:.*?)\n\5 # heredoc value
1719 [^"\s\]]+ # unquoted value
1721 \s* # whitespace or end
1724 *)? # 0 or more parameters
1725 \]\] # directive closed
1731 \[\[(!?) # directive open; 2: optional prefix
1732 ([-\w]+) # 3: command
1734 ( # 4: the parameters..
1736 (?:[-.\w]+=)? # named parameter key?
1738 """.*?""" # triple-quoted value
1740 "[^"]*?" # single-quoted value
1742 '''.*?''' # triple-single-quote
1744 <<([a-zA-Z]+)\n # 5: heredoc start
1745 (?:.*?)\n\5 # heredoc value
1747 [^"\s\]]+ # unquoted value
1749 \s* # whitespace or end
1752 *) # 0 or more parameters
1753 \]\] # directive closed
1757 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1766 run_hooks(filter => sub {
1767 $content=shift->(page => $page, destpage => $destpage,
1768 content => $content);
1774 sub check_canedit ($$$;$) {
1781 run_hooks(canedit => sub {
1782 return if defined $canedit;
1783 my $ret=shift->($page, $q, $session);
1788 elsif (ref $ret eq 'CODE') {
1789 $ret->() unless $nonfatal;
1792 elsif (defined $ret) {
1793 error($ret) unless $nonfatal;
1798 return defined $canedit ? $canedit : 1;
1801 sub check_content (@) {
1804 return 1 if ! exists $hooks{checkcontent}; # optimisation
1806 if (exists $pagesources{$params{page}}) {
1808 my %old=map { $_ => 1 }
1809 split("\n", readfile(srcfile($pagesources{$params{page}})));
1810 foreach my $line (split("\n", $params{content})) {
1811 push @diff, $line if ! exists $old{$line};
1813 $params{diff}=join("\n", @diff);
1817 run_hooks(checkcontent => sub {
1818 return if defined $ok;
1819 my $ret=shift->(%params);
1824 elsif (ref $ret eq 'CODE') {
1825 $ret->() unless $params{nonfatal};
1828 elsif (defined $ret) {
1829 error($ret) unless $params{nonfatal};
1835 return defined $ok ? $ok : 1;
1838 sub check_canchange (@) {
1840 my $cgi = $params{cgi};
1841 my $session = $params{session};
1842 my @changes = @{$params{changes}};
1845 foreach my $change (@changes) {
1846 # This untaint is safe because we check file_pruned and
1848 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1849 $file=possibly_foolish_untaint($file);
1850 if (! defined $file || ! length $file ||
1851 file_pruned($file)) {
1852 error(sprintf(gettext("bad file name %s"), $file));
1855 my $type=pagetype($file);
1856 my $page=pagename($file) if defined $type;
1858 if ($change->{action} eq 'add') {
1862 if ($change->{action} eq 'change' ||
1863 $change->{action} eq 'add') {
1864 if (defined $page) {
1865 check_canedit($page, $cgi, $session);
1869 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1870 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1871 check_canedit($file, $cgi, $session);
1876 elsif ($change->{action} eq 'remove') {
1877 # check_canremove tests to see if the file is present
1878 # on disk. This will fail when a single commit adds a
1879 # file and then removes it again. Avoid the problem
1880 # by not testing the removal in such pairs of changes.
1881 # (The add is still tested, just to make sure that
1882 # no data is added to the repo that a web edit
1884 next if $newfiles{$file};
1886 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1887 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1888 check_canedit(defined $page ? $page : $file, $cgi, $session);
1893 error "unknown action ".$change->{action};
1896 error sprintf(gettext("you are not allowed to change %s"), $file);
1904 # Take an exclusive lock on the wiki to prevent multiple concurrent
1905 # run issues. The lock will be dropped on program exit.
1906 if (! -d $config{wikistatedir}) {
1907 mkdir($config{wikistatedir});
1909 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1910 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1911 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1912 debug("failed to get lock; waiting...");
1913 if (! flock($wikilock, LOCK_EX)) {
1914 error("failed to get lock");
1921 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1922 return close($wikilock) if $wikilock;
1928 sub commit_hook_enabled () {
1929 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1930 error("cannot write to $config{wikistatedir}/commitlock: $!");
1931 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1932 close($commitlock) || error("failed closing commitlock: $!");
1935 close($commitlock) || error("failed closing commitlock: $!");
1939 sub disable_commit_hook () {
1940 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1941 error("cannot write to $config{wikistatedir}/commitlock: $!");
1942 if (! flock($commitlock, 2)) { # LOCK_EX
1943 error("failed to get commit lock");
1948 sub enable_commit_hook () {
1949 return close($commitlock) if $commitlock;
1954 %oldrenderedfiles=%pagectime=();
1955 my $rebuild=$config{rebuild};
1957 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1958 %destsources=%renderedfiles=%pagecase=%pagestate=
1959 %depends_simple=%typedlinks=%oldtypedlinks=();
1962 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1963 if (-e "$config{wikistatedir}/index") {
1964 system("ikiwiki-transition", "indexdb", $config{srcdir});
1965 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1968 # gettime on first build
1969 $config{gettime}=1 unless defined $config{gettime};
1974 my $index=Storable::fd_retrieve($in);
1975 if (! defined $index) {
1980 if (exists $index->{version} && ! ref $index->{version}) {
1981 $pages=$index->{page};
1982 %wikistate=%{$index->{state}};
1983 # Handle plugins that got disabled by loading a new setup.
1984 if (exists $config{setupfile}) {
1985 require IkiWiki::Setup;
1986 IkiWiki::Setup::disabled_plugins(
1987 grep { ! $loaded_plugins{$_} } keys %wikistate);
1995 foreach my $src (keys %$pages) {
1996 my $d=$pages->{$src};
1998 if (exists $d->{page} && ! $rebuild) {
2002 $page=pagename($src);
2004 $pagectime{$page}=$d->{ctime};
2005 $pagesources{$page}=$src;
2007 $pagemtime{$page}=$d->{mtime};
2008 $renderedfiles{$page}=$d->{dest};
2009 if (exists $d->{links} && ref $d->{links}) {
2010 $links{$page}=$d->{links};
2011 $oldlinks{$page}=[@{$d->{links}}];
2013 if (ref $d->{depends_simple} eq 'ARRAY') {
2015 $depends_simple{$page}={
2016 map { $_ => 1 } @{$d->{depends_simple}}
2019 elsif (exists $d->{depends_simple}) {
2020 $depends_simple{$page}=$d->{depends_simple};
2022 if (exists $d->{dependslist}) {
2025 map { $_ => $DEPEND_CONTENT }
2026 @{$d->{dependslist}}
2029 elsif (exists $d->{depends} && ! ref $d->{depends}) {
2031 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
2033 elsif (exists $d->{depends}) {
2034 $depends{$page}=$d->{depends};
2036 if (exists $d->{state}) {
2037 $pagestate{$page}=$d->{state};
2039 if (exists $d->{typedlinks}) {
2040 $typedlinks{$page}=$d->{typedlinks};
2042 while (my ($type, $links) = each %{$typedlinks{$page}}) {
2043 next unless %$links;
2044 $oldtypedlinks{$page}{$type} = {%$links};
2048 $oldrenderedfiles{$page}=[@{$d->{dest}}];
2050 foreach my $page (keys %pagesources) {
2051 $pagecase{lc $page}=$page;
2053 foreach my $page (keys %renderedfiles) {
2054 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
2056 $lastrev=$index->{lastrev};
2057 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
2062 run_hooks(savestate => sub { shift->() });
2064 my @plugins=keys %loaded_plugins;
2066 if (! -d $config{wikistatedir}) {
2067 mkdir($config{wikistatedir});
2069 my $newfile="$config{wikistatedir}/indexdb.new";
2070 my $cleanup = sub { unlink($newfile) };
2071 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
2074 foreach my $page (keys %pagemtime) {
2075 next unless $pagemtime{$page};
2076 my $src=$pagesources{$page};
2078 $index{page}{$src}={
2080 ctime => $pagectime{$page},
2081 mtime => $pagemtime{$page},
2082 dest => $renderedfiles{$page},
2083 links => $links{$page},
2086 if (exists $depends{$page}) {
2087 $index{page}{$src}{depends} = $depends{$page};
2090 if (exists $depends_simple{$page}) {
2091 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2094 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2095 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2098 if (exists $pagestate{$page}) {
2099 $index{page}{$src}{state}=$pagestate{$page};
2104 foreach my $id (@plugins) {
2105 $index{state}{$id}={}; # used to detect disabled plugins
2106 foreach my $key (keys %{$wikistate{$id}}) {
2107 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2111 $index{lastrev}=$lastrev;
2112 $index{underlayfiles}=\@underlayfiles;
2114 $index{version}="3";
2115 my $ret=Storable::nstore_fd(\%index, $out);
2116 return if ! defined $ret || ! $ret;
2117 close $out || error("failed saving to $newfile: $!", $cleanup);
2118 rename($newfile, "$config{wikistatedir}/indexdb") ||
2119 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2124 sub template_file ($) {
2127 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2129 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2130 $template=srcfile($pagesources{$tpage}, 1);
2134 $template=srcfile($tpage, 1);
2137 if (defined $template) {
2138 return $template, $tpage, 1 if wantarray;
2142 $name=~s:/::; # avoid path traversal
2143 foreach my $dir ($config{templatedir},
2144 "$installdir/share/ikiwiki/templates") {
2145 if (-e "$dir/$name") {
2146 $template="$dir/$name";
2150 if (defined $template) {
2151 return $template, $tpage if wantarray;
2159 sub template_depends ($$;@) {
2163 my ($filename, $tpage, $untrusted)=template_file($name);
2164 if (! defined $filename) {
2165 error(sprintf(gettext("template %s not found"), $name))
2168 if (defined $page && defined $tpage) {
2169 add_depends($page, $tpage);
2174 my $text_ref = shift;
2175 ${$text_ref} = decode_utf8(${$text_ref});
2176 run_hooks(readtemplate => sub {
2177 ${$text_ref} = shift->(
2180 content => ${$text_ref},
2181 untrusted => $untrusted,
2185 loop_context_vars => 1,
2186 die_on_bad_params => 0,
2187 parent_global_vars => 1,
2188 filename => $filename,
2190 ($untrusted ? (no_includes => 1) : ()),
2192 return @opts if wantarray;
2194 require HTML::Template;
2195 return HTML::Template->new(@opts);
2198 sub template ($;@) {
2199 template_depends(shift, undef, @_);
2202 sub templateactions ($$) {
2208 run_hooks(pageactions => sub {
2209 push @actions, map { { action => $_ } }
2210 grep { defined } shift->(page => $page);
2212 $template->param(actions => \@actions);
2214 if ($config{cgiurl} && exists $hooks{auth}) {
2215 $template->param(prefsurl => cgiurl(do => "prefs"));
2219 if ($have_actions || @actions) {
2220 $template->param(have_actions => 1);
2227 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2228 error 'hook requires type, call, and id parameters';
2231 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2233 $hooks{$param{type}}{$param{id}}=\%param;
2237 sub run_hooks ($$) {
2238 # Calls the given sub for each hook of the given type,
2239 # passing it the hook function to call.
2243 if (exists $hooks{$type}) {
2244 my (@first, @middle, @last);
2245 foreach my $id (keys %{$hooks{$type}}) {
2246 if ($hooks{$type}{$id}{first}) {
2249 elsif ($hooks{$type}{$id}{last}) {
2256 foreach my $id (@first, @middle, @last) {
2257 $sub->($hooks{$type}{$id}{call});
2265 $hooks{rcs}{rcs_update}{call}->(@_);
2268 sub rcs_prepedit ($) {
2269 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2272 sub rcs_commit (@) {
2273 $hooks{rcs}{rcs_commit}{call}->(@_);
2276 sub rcs_commit_staged (@) {
2277 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2281 $hooks{rcs}{rcs_add}{call}->(@_);
2284 sub rcs_remove ($) {
2285 $hooks{rcs}{rcs_remove}{call}->(@_);
2288 sub rcs_rename ($$) {
2289 $hooks{rcs}{rcs_rename}{call}->(@_);
2292 sub rcs_recentchanges ($) {
2293 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2296 sub rcs_diff ($;$) {
2297 $hooks{rcs}{rcs_diff}{call}->(@_);
2300 sub rcs_getctime ($) {
2301 $hooks{rcs}{rcs_getctime}{call}->(@_);
2304 sub rcs_getmtime ($) {
2305 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2308 sub rcs_receive () {
2309 $hooks{rcs}{rcs_receive}{call}->();
2312 sub add_depends ($$;$) {
2315 my $deptype=shift || $DEPEND_CONTENT;
2317 # Is the pagespec a simple page name?
2318 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2319 $pagespec !~ /[\s*?()!]/) {
2320 $depends_simple{$page}{lc $pagespec} |= $deptype;
2324 # Add explicit dependencies for influences.
2325 my $sub=pagespec_translate($pagespec);
2326 return unless defined $sub;
2327 foreach my $p (keys %pagesources) {
2328 my $r=$sub->($p, location => $page);
2329 my $i=$r->influences;
2330 my $static=$r->influences_static;
2331 foreach my $k (keys %$i) {
2332 next unless $r || $static || $k eq $page;
2333 $depends_simple{$page}{lc $k} |= $i->{$k};
2338 $depends{$page}{$pagespec} |= $deptype;
2344 foreach my $type (@_) {
2345 if ($type eq 'presence') {
2346 $deptype |= $DEPEND_PRESENCE;
2348 elsif ($type eq 'links') {
2349 $deptype |= $DEPEND_LINKS;
2351 elsif ($type eq 'content') {
2352 $deptype |= $DEPEND_CONTENT;
2358 my $file_prune_regexp;
2359 sub file_pruned ($) {
2362 if (defined $config{include} && length $config{include}) {
2363 return 0 if $file =~ m/$config{include}/;
2366 if (! defined $file_prune_regexp) {
2367 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2368 $file_prune_regexp=qr/$file_prune_regexp/;
2370 return $file =~ m/$file_prune_regexp/;
2373 sub define_gettext () {
2374 # If translation is needed, redefine the gettext function to do it.
2375 # Otherwise, it becomes a quick no-op.
2378 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2379 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2380 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2382 $gettext_obj=eval q{
2383 use Locale::gettext q{textdomain};
2384 Locale::gettext->domain('ikiwiki')
2389 no warnings 'redefine';
2391 $getobj->() if $getobj;
2393 $gettext_obj->get(shift);
2400 $getobj->() if $getobj;
2402 $gettext_obj->nget(@_);
2405 return ($_[2] == 1 ? $_[0] : $_[1])
2423 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2427 # Injects a new function into the symbol table to replace an
2428 # exported function.
2431 # This is deep ugly perl foo, beware.
2434 if (! defined $params{parent}) {
2435 $params{parent}='::';
2436 $params{old}=\&{$params{name}};
2437 $params{name}=~s/.*:://;
2439 my $parent=$params{parent};
2440 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2441 $ns = $params{parent} . $ns;
2442 inject(%params, parent => $ns) unless $ns eq '::main::';
2443 *{$ns . $params{name}} = $params{call}
2444 if exists ${$ns}{$params{name}} &&
2445 \&{${$ns}{$params{name}}} == $params{old};
2451 sub add_link ($$;$) {
2456 push @{$links{$page}}, $link
2457 unless grep { $_ eq $link } @{$links{$page}};
2459 if (defined $type) {
2460 $typedlinks{$page}{$type}{$link} = 1;
2464 sub add_autofile ($$$) {
2467 my $generator=shift;
2469 $autofiles{$file}{plugin}=$plugin;
2470 $autofiles{$file}{generator}=$generator;
2474 return LWP::UserAgent->new(
2475 cookie_jar => $config{cookiejar},
2476 env_proxy => 1, # respect proxy env vars
2477 agent => $config{useragent},
2481 sub sortspec_translate ($$) {
2483 my $reverse = shift;
2489 (-?) # group 1: perhaps negated
2492 \w+\([^\)]*\) # command(params)
2494 [^\s]+ # or anything else
2502 if ($word =~ m/^(\w+)\((.*)\)$/) {
2503 # command with parameters
2507 elsif ($word !~ m/^\w+$/) {
2508 error(sprintf(gettext("invalid sort type %s"), $word));
2519 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2520 if (defined $params) {
2521 push @data, $params;
2522 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2525 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2529 error(sprintf(gettext("unknown sort type %s"), $word));
2533 if (! length $code) {
2534 # undefined sorting method... sort arbitrarily
2543 return eval 'sub { '.$code.' }';
2546 sub pagespec_translate ($) {
2549 # Convert spec to perl code.
2553 \s* # ignore whitespace
2554 ( # 1: match a single word
2561 \w+\([^\)]*\) # command(params)
2563 [^\s()]+ # any other text
2565 \s* # ignore whitespace
2568 if (lc $word eq 'and') {
2571 elsif (lc $word eq 'or') {
2574 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2577 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2578 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2580 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2583 push @data, qq{unknown function in pagespec "$word"};
2584 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2589 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2593 if (! length $code) {
2594 $code="IkiWiki::FailReason->new('empty pagespec')";
2598 return eval 'sub { my $page=shift; '.$code.' }';
2601 sub pagespec_match ($$;@) {
2606 # Backwards compatability with old calling convention.
2608 unshift @params, 'location';
2611 my $sub=pagespec_translate($spec);
2612 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2614 return $sub->($page, @params);
2617 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2619 # Not exported yet, but could be in future if it is generally useful.
2620 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2621 # which is "more internal".
2622 sub sort_pages ($$;@) {
2626 $sort = sortspec_translate($sort, $params{reverse});
2627 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2630 sub pagespec_match_list ($$;@) {
2635 # Backwards compatability with old calling convention.
2637 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2638 $params{list}=$page;
2639 $page=$params{location}; # ugh!
2642 my $sub=pagespec_translate($pagespec);
2643 error "syntax error in pagespec \"$pagespec\""
2645 my $sort=sortspec_translate($params{sort}, $params{reverse})
2646 if defined $params{sort};
2649 if (exists $params{list}) {
2650 @candidates=exists $params{filter}
2651 ? grep { ! $params{filter}->($_) } @{$params{list}}
2655 @candidates=exists $params{filter}
2656 ? grep { ! $params{filter}->($_) } keys %pagesources
2657 : keys %pagesources;
2660 # clear params, remainder is passed to pagespec
2661 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2662 my $num=$params{num};
2663 delete @params{qw{num deptype reverse sort filter list}};
2665 # when only the top matches will be returned, it's efficient to
2666 # sort before matching to pagespec,
2667 if (defined $num && defined $sort) {
2668 @candidates=IkiWiki::SortSpec::sort_pages(
2669 $sort, @candidates);
2675 my $accum=IkiWiki::SuccessReason->new();
2676 foreach my $p (@candidates) {
2677 my $r=$sub->($p, %params, location => $page);
2678 error(sprintf(gettext("cannot match pages: %s"), $r))
2679 if $r->isa("IkiWiki::ErrorReason");
2680 unless ($r || $r->influences_static) {
2681 $r->remove_influence($p);
2686 last if defined $num && ++$count == $num;
2690 # Add simple dependencies for accumulated influences.
2691 my $i=$accum->influences;
2692 foreach my $k (keys %$i) {
2693 $depends_simple{$page}{lc $k} |= $i->{$k};
2696 # when all matches will be returned, it's efficient to
2697 # sort after matching
2698 if (! defined $num && defined $sort) {
2699 return IkiWiki::SortSpec::sort_pages(
2707 sub pagespec_valid ($) {
2710 return defined pagespec_translate($spec);
2714 my $re=quotemeta(shift);
2720 package IkiWiki::FailReason;
2723 '""' => sub { $_[0][0] },
2725 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2726 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2727 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2731 our @ISA = 'IkiWiki::SuccessReason';
2733 package IkiWiki::SuccessReason;
2735 # A blessed array-ref:
2737 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2739 # - if absent or false, the influences of this evaluation are "static",
2740 # see the influences_static method
2741 # - if true, they are dynamic (not static)
2742 # [1]{any other key}:
2743 # the dependency types of influences, as returned by the influences method
2746 # in string context, it's the human-readable reason
2747 '""' => sub { $_[0][0] },
2748 # in boolean context, SuccessReason is 1 and FailReason is 0
2750 # negating a result gives the opposite result with the same influences
2751 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2752 # A & B = (A ? B : A) with the influences of both
2753 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2754 # A | B = (A ? A : B) with the influences of both
2755 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2759 # SuccessReason->new("human-readable reason", page => deptype, ...)
2764 return bless [$value, {@_}], $class;
2767 # influences(): return a reference to a copy of the hash
2768 # { page => dependency type } describing the pages that indirectly influenced
2769 # this result, but would not cause a dependency through ikiwiki's core
2772 # See [[todo/dependency_types]] for extensive discussion of what this means.
2774 # influences(page => deptype, ...): remove all influences, replace them
2775 # with the arguments, and return a reference to a copy of the new influences.
2779 $this->[1]={@_} if @_;
2780 my %i=%{$this->[1]};
2785 # True if this result has the same influences whichever page it matches,
2786 # For instance, whether bar matches backlink(foo) is influenced only by
2787 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2788 # which does not mention bar anywhere.
2790 # False if this result would have different influences when matching
2791 # different pages. For instance, when testing whether link(foo) matches bar,
2792 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2793 # bar's links could change the outcome; so its influences are not the same
2794 # as when testing whether link(foo) matches baz.
2796 # Static influences are one of the things that make pagespec_match_list
2797 # more efficient than repeated calls to pagespec_match.
2799 sub influences_static {
2800 return ! $_[0][1]->{""};
2803 # Change the influences of $this to be the influences of "$this & $other"
2804 # or "$this | $other".
2806 # If both $this and $other are either successful or have influences,
2807 # or this is an "or" operation, the result has all the influences from
2808 # either of the arguments. It has dynamic influences if either argument
2809 # has dynamic influences.
2811 # If this is an "and" operation, and at least one argument is a
2812 # FailReason with no influences, the result has no influences, and they
2813 # are not dynamic. For instance, link(foo) matching bar is influenced
2814 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2815 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2816 # bar, because it would be false however often you edit bar.
2818 sub merge_influences {
2823 # This "if" is odd because it needs to avoid negating $this
2824 # or $other, which would alter the objects in-place. Be careful.
2825 if (! $anded || (($this || %{$this->[1]}) &&
2826 ($other || %{$other->[1]}))) {
2827 foreach my $influence (keys %{$other->[1]}) {
2828 $this->[1]{$influence} |= $other->[1]{$influence};
2837 # Change $this so it is not considered to be influenced by $torm.
2839 sub remove_influence {
2843 delete $this->[1]{$torm};
2846 package IkiWiki::ErrorReason;
2848 our @ISA = 'IkiWiki::FailReason';
2850 package IkiWiki::PageSpec;
2856 if ($path =~ m!^\.(/|$)!) {
2858 $from=~s#/?[^/]+$## if defined $from;
2860 $path="$from/$path" if defined $from && length $from;
2864 $path = "" unless defined $path;
2873 sub match_glob ($$;@) {
2878 $glob=derel($glob, $params{location});
2880 # Instead of converting the glob to a regex every time,
2881 # cache the compiled regex to save time.
2882 my $re=$glob_cache{$glob};
2883 unless (defined $re) {
2884 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2887 if (! IkiWiki::isinternal($page) || $params{internal}) {
2888 return IkiWiki::SuccessReason->new("$glob matches $page");
2891 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2895 return IkiWiki::FailReason->new("$glob does not match $page");
2899 sub match_internal ($$;@) {
2900 return match_glob(shift, shift, @_, internal => 1)
2903 sub match_page ($$;@) {
2905 my $match=match_glob($page, shift, @_);
2907 my $source=exists $IkiWiki::pagesources{$page} ?
2908 $IkiWiki::pagesources{$page} :
2909 $IkiWiki::delpagesources{$page};
2910 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2911 if (! defined $type) {
2912 return IkiWiki::FailReason->new("$page is not a page");
2918 sub match_link ($$;@) {
2923 $link=derel($link, $params{location});
2924 my $from=exists $params{location} ? $params{location} : '';
2925 my $linktype=$params{linktype};
2927 if (defined $linktype) {
2928 $qualifier=" with type $linktype";
2931 my $links = $IkiWiki::links{$page};
2932 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2933 unless $links && @{$links};
2934 my $bestlink = IkiWiki::bestlink($from, $link);
2935 foreach my $p (@{$links}) {
2936 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2938 if (length $bestlink) {
2939 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2940 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2944 if (match_glob($p, $link, %params)) {
2945 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2947 my ($p_rel)=$p=~/^\/?(.*)/;
2949 if (match_glob($p_rel, $link, %params)) {
2950 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2954 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2957 sub match_backlink ($$;@) {
2961 if ($testpage eq '.') {
2962 $testpage = $params{'location'}
2964 my $ret=match_link($testpage, $page, @_);
2965 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2969 sub match_created_before ($$;@) {
2974 $testpage=derel($testpage, $params{location});
2976 if (exists $IkiWiki::pagectime{$testpage}) {
2977 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2978 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2981 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2985 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2989 sub match_created_after ($$;@) {
2994 $testpage=derel($testpage, $params{location});
2996 if (exists $IkiWiki::pagectime{$testpage}) {
2997 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2998 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3001 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3005 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
3009 sub match_creation_day ($$;@) {
3012 if ($d !~ /^\d+$/) {
3013 return IkiWiki::ErrorReason->new("invalid day $d");
3015 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
3016 return IkiWiki::SuccessReason->new('creation_day matched');
3019 return IkiWiki::FailReason->new('creation_day did not match');
3023 sub match_creation_month ($$;@) {
3026 if ($m !~ /^\d+$/) {
3027 return IkiWiki::ErrorReason->new("invalid month $m");
3029 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
3030 return IkiWiki::SuccessReason->new('creation_month matched');
3033 return IkiWiki::FailReason->new('creation_month did not match');
3037 sub match_creation_year ($$;@) {
3040 if ($y !~ /^\d+$/) {
3041 return IkiWiki::ErrorReason->new("invalid year $y");
3043 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
3044 return IkiWiki::SuccessReason->new('creation_year matched');
3047 return IkiWiki::FailReason->new('creation_year did not match');
3051 sub match_user ($$;@) {
3056 if (! exists $params{user}) {
3057 return IkiWiki::ErrorReason->new("no user specified");
3060 my $regexp=IkiWiki::glob2re($user);
3062 if (defined $params{user} && $params{user}=~$regexp) {
3063 return IkiWiki::SuccessReason->new("user is $user");
3065 elsif (! defined $params{user}) {
3066 return IkiWiki::FailReason->new("not logged in");
3069 return IkiWiki::FailReason->new("user is $params{user}, not $user");
3073 sub match_admin ($$;@) {
3078 if (! exists $params{user}) {
3079 return IkiWiki::ErrorReason->new("no user specified");
3082 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3083 return IkiWiki::SuccessReason->new("user is an admin");
3085 elsif (! defined $params{user}) {
3086 return IkiWiki::FailReason->new("not logged in");
3089 return IkiWiki::FailReason->new("user is not an admin");
3093 sub match_ip ($$;@) {
3098 if (! exists $params{ip}) {
3099 return IkiWiki::ErrorReason->new("no IP specified");
3102 my $regexp=IkiWiki::glob2re(lc $ip);
3104 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3105 return IkiWiki::SuccessReason->new("IP is $ip");
3108 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3112 package IkiWiki::SortSpec;
3114 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3115 # are easily available in this namespace, for cmp functions to use them.
3122 IkiWiki::pagetitle(IkiWiki::basename($a))
3124 IkiWiki::pagetitle(IkiWiki::basename($b))
3127 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3128 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3129 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }