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 @post_scan};
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 (without a final /)",
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",
565 description => "turn links to image files into inline image tags",
569 responsive_layout => {
572 description => "theme has a responsive layout? (mobile-optimized)",
579 description => "try harder to produce deterministic output",
588 if ($config{libdirs}) {
589 @libdirs = @{$config{libdirs}};
591 if (length $config{libdir}) {
592 push @libdirs, $config{libdir};
597 sub defaultconfig () {
600 foreach my $key (keys %s) {
601 push @ret, $key, $s{$key}->{default};
606 # URL to top of wiki as a path starting with /, valid from any wiki page or
607 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
609 # URL to CGI script, similar to $local_url
613 # locale stuff; avoid LC_ALL since it overrides everything
614 if (defined $ENV{LC_ALL}) {
615 $ENV{LANG} = $ENV{LC_ALL};
618 if (defined $config{locale}) {
619 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
620 $ENV{LANG}=$config{locale};
625 if (! defined $config{wiki_file_regexp}) {
626 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
629 if (ref $config{ENV} eq 'HASH') {
630 foreach my $val (keys %{$config{ENV}}) {
631 $ENV{$val}=$config{ENV}{$val};
634 if (defined $config{timezone} && length $config{timezone}) {
635 $ENV{TZ}=$config{timezone};
637 elsif (defined $ENV{TZ} && length $ENV{TZ}) {
638 $config{timezone}=$ENV{TZ};
641 eval q{use Config qw()};
644 if ($Config::Config{d_gnulibc} && -e '/etc/localtime') {
645 $config{timezone}=$ENV{TZ}=':/etc/localtime';
648 $config{timezone}=$ENV{TZ}='GMT';
652 if ($config{w3mmode}) {
653 eval q{use Cwd q{abs_path}};
655 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
656 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
657 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
658 unless $config{cgiurl} =~ m!file:///!;
659 $config{url}="file://".$config{destdir};
662 if ($config{cgi} && ! length $config{url}) {
663 error(gettext("Must specify url to wiki with --url when using --cgi"));
666 if (defined $config{url} && length $config{url}) {
668 my $baseurl = URI->new($config{url});
670 $local_url = $baseurl->path . "/";
671 $local_cgiurl = undef;
673 if (length $config{cgiurl}) {
674 my $cgiurl = URI->new($config{cgiurl});
676 $local_cgiurl = $cgiurl->path;
678 if ($cgiurl->scheme eq 'https' &&
679 $baseurl->scheme eq 'http') {
680 # We assume that the same content is available
681 # over both http and https, because if it
682 # wasn't, accessing the static content
683 # from the CGI would be mixed-content,
684 # which would be a security flaw.
686 if ($cgiurl->authority ne $baseurl->authority) {
687 # use protocol-relative URL for
689 $local_url = "$config{url}/";
690 $local_url =~ s{^http://}{//};
692 # else use host-relative URL for static content
694 # either way, CGI needs to be absolute
695 $local_cgiurl = $config{cgiurl};
697 elsif ($cgiurl->scheme ne $baseurl->scheme) {
698 # too far apart, fall back to absolute URLs
699 $local_url = "$config{url}/";
700 $local_cgiurl = $config{cgiurl};
702 elsif ($cgiurl->authority ne $baseurl->authority) {
703 # slightly too far apart, fall back to
704 # protocol-relative URLs
705 $local_url = "$config{url}/";
706 $local_url =~ s{^https?://}{//};
707 $local_cgiurl = $config{cgiurl};
708 $local_cgiurl =~ s{^https?://}{//};
710 # else keep host-relative URLs
713 $local_url =~ s{//$}{/};
716 $local_cgiurl = $config{cgiurl};
719 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
720 unless exists $config{wikistatedir} && defined $config{wikistatedir};
722 if (defined $config{umask}) {
723 my $u = possibly_foolish_untaint($config{umask});
725 if ($u =~ m/^\d+$/) {
728 elsif ($u eq 'private') {
731 elsif ($u eq 'group') {
734 elsif ($u eq 'public') {
738 error(sprintf(gettext("unsupported umask setting %s"), $u));
742 run_hooks(checkconfig => sub { shift->() });
750 foreach my $dir (@INC, getlibdirs()) {
751 next unless defined $dir && length $dir;
752 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
753 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
757 foreach my $dir (getlibdirs(), "$installdir/lib/ikiwiki") {
758 next unless defined $dir && length $dir;
759 foreach my $file (glob("$dir/plugins/*")) {
760 $ret{basename($file)}=1 if -x $file;
768 foreach my $dir (getlibdirs()) {
769 unshift @INC, possibly_foolish_untaint($dir);
772 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
777 if (exists $hooks{rcs}) {
778 error(gettext("cannot use multiple rcs plugins"));
780 loadplugin($config{rcs});
782 if (! exists $hooks{rcs}) {
786 run_hooks(getopt => sub { shift->() });
787 if (grep /^-/, @ARGV) {
788 print STDERR "Unknown option (or missing parameter): $_\n"
789 foreach grep /^-/, @ARGV;
796 sub loadplugin ($;$) {
800 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
802 foreach my $possiblytainteddir (getlibdirs(), "$installdir/lib/ikiwiki") {
803 my $dir = possibly_foolish_untaint($possiblytainteddir);
804 if (defined $dir && -x "$dir/plugins/$plugin") {
805 eval { require IkiWiki::Plugin::external };
808 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
810 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
811 $loaded_plugins{$plugin}=1;
816 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
819 error("Failed to load plugin $mod: $@");
821 $loaded_plugins{$plugin}=1;
828 log_message('err' => $message) if $config{syslog};
829 if (defined $cleaner) {
836 return unless $config{verbose};
837 return log_message(debug => @_);
842 sub log_message ($$) {
845 if ($config{syslog}) {
848 Sys::Syslog::setlogsock('unix');
849 Sys::Syslog::openlog('ikiwiki', '', 'user');
853 my $message = "[$config{wikiname}] ".join(" ", @_);
854 utf8::encode($message);
855 Sys::Syslog::syslog($type, "%s", $message);
858 print STDERR "failed to syslog: $@" unless $log_failed;
864 elsif (! $config{cgi}) {
868 return print STDERR "@_\n";
872 sub possibly_foolish_untaint ($) {
874 my ($untainted)=$tainted=~/(.*)/s;
894 return exists $pagesources{$page} &&
895 $pagesources{$page} =~ /\._([^.]+)$/;
901 if ($file =~ /\.([^.]+)$/) {
902 return $1 if exists $hooks{htmlize}{$1};
904 my $base=basename($file);
905 if (exists $hooks{htmlize}{$base} &&
906 $hooks{htmlize}{$base}{noextension}) {
917 if (exists $pagename_cache{$file}) {
918 return $pagename_cache{$file};
921 my $type=pagetype($file);
923 $page=~s/\Q.$type\E*$//
924 if defined $type && !$hooks{htmlize}{$type}{keepextension}
925 && !$hooks{htmlize}{$type}{noextension};
926 if ($config{indexpages} && $page=~/(.*)\/index$/) {
930 $pagename_cache{$file} = $page;
934 sub newpagefile ($$) {
938 if (! $config{indexpages} || $page eq 'index') {
939 return $page.".".$type;
942 return $page."/index.".$type;
946 sub targetpage ($$;$) {
951 if (defined $filename) {
952 return $page."/".$filename.".".$ext;
954 elsif (! $config{usedirs} || $page eq 'index') {
955 return $page.".".$ext;
958 return $page."/index.".$ext;
965 return targetpage($page, $config{htmlext});
972 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
973 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
974 return "$dir/$file", stat(_) if -e "$dir/$file";
976 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
981 return (srcfile_stat(@_))[0];
984 sub add_literal_underlay ($) {
987 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
988 unshift @{$config{underlaydirs}}, $dir;
992 sub add_underlay ($) {
996 $dir="$config{underlaydirbase}/$dir";
999 add_literal_underlay($dir);
1000 # why does it return 1? we just don't know
1004 sub readfile ($;$$) {
1010 error("cannot read a symlink ($file)");
1014 open (my $in, "<", $file) || error("failed to read $file: $!");
1015 binmode($in) if ($binary);
1016 return \*$in if $wantfd;
1018 # check for invalid utf-8, and toss it back to avoid crashes
1019 if (! utf8::valid($ret)) {
1020 $ret=encode_utf8($ret);
1022 close $in || error("failed to read $file: $!");
1026 sub prep_writefile ($$) {
1031 while (length $test) {
1032 if (-l "$destdir/$test") {
1033 error("cannot write to a symlink ($test)");
1035 if (-f _ && $test ne $file) {
1036 # Remove conflicting file.
1037 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1038 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1040 unlink("$destdir/$test");
1046 $test=dirname($test);
1049 my $dir=dirname("$destdir/$file");
1052 foreach my $s (split(m!/+!, $dir)) {
1055 mkdir($d) || error("failed to create directory $d: $!");
1063 sub writefile ($$$;$$) {
1064 my $file=shift; # can include subdirs
1065 my $destdir=shift; # directory to put file in
1070 prep_writefile($file, $destdir);
1072 my $newfile="$destdir/$file.ikiwiki-new";
1074 error("cannot write to a symlink ($newfile)");
1077 my $cleanup = sub { unlink($newfile) };
1078 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1079 binmode($out) if ($binary);
1081 $writer->(\*$out, $cleanup);
1084 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1086 close $out || error("failed saving $newfile: $!", $cleanup);
1087 rename($newfile, "$destdir/$file") ||
1088 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1094 sub will_render ($$;$) {
1099 # Important security check for independently created files.
1100 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1101 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1102 my $from_other_page=0;
1103 # Expensive, but rarely runs.
1104 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1107 dirname($_) eq $dest
1108 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1114 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1115 unless $from_other_page;
1118 # If $dest exists as a directory, remove conflicting files in it
1119 # rendered from other pages.
1121 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1122 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1123 if (dirname($f) eq $dest) {
1124 unlink("$config{destdir}/$f");
1125 rmdir(dirname("$config{destdir}/$f"));
1131 if (! $clear || $cleared{$page}) {
1132 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1135 foreach my $old (@{$renderedfiles{$page}}) {
1136 delete $destsources{$old};
1138 $renderedfiles{$page}=[$dest];
1141 $destsources{$dest}=$page;
1151 if ($link=~s/^\/+//) {
1159 $l.="/" if length $l;
1162 if (exists $pagesources{$l}) {
1165 elsif (exists $pagecase{lc $l}) {
1166 return $pagecase{lc $l};
1168 } while $cwd=~s{/?[^/]+$}{};
1170 if (length $config{userdir}) {
1171 my $l = "$config{userdir}/".lc($link);
1172 if (exists $pagesources{$l}) {
1175 elsif (exists $pagecase{lc $l}) {
1176 return $pagecase{lc $l};
1180 #print STDERR "warning: page $page, broken link: $link\n";
1184 sub isinlinableimage ($) {
1187 return $config{inlineimages} && $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1190 sub pagetitle ($;$) {
1192 my $unescaped=shift;
1195 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1198 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1206 # support use w/o %config set
1207 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1208 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1214 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1215 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1222 my $cgiurl=$local_cgiurl;
1224 if (exists $params{cgiurl}) {
1225 $cgiurl=$params{cgiurl};
1226 delete $params{cgiurl};
1234 join("&", map $_."=".uri_escape_utf8($params{$_}), sort(keys %params));
1237 sub cgiurl_abs (@) {
1239 URI->new_abs(cgiurl(@_), $config{cgiurl});
1242 # Same as cgiurl_abs, but when the user connected using https,
1243 # will be a https url even if the cgiurl is normally a http url.
1245 # This should be used for anything involving emailing a login link,
1246 # because a https session cookie will not be sent over http.
1247 sub cgiurl_abs_samescheme (@) {
1248 my $u=cgiurl_abs(@_);
1249 if (($ENV{HTTPS} && lc $ENV{HTTPS} ne "off")) {
1250 $u=~s/^http:/https:/i;
1258 return $local_url if ! defined $page;
1260 $page=htmlpage($page);
1262 $page=~s/[^\/]+\//..\//g;
1270 return $url unless defined $urlbase && length $urlbase;
1273 URI->new_abs($url, $urlbase)->as_string;
1277 # Work around very innefficient behavior in File::Spec if abs2rel
1278 # is passed two relative paths. It's much faster if paths are
1279 # absolute! (Debian bug #376658; fixed in debian unstable now)
1284 my $ret=File::Spec->abs2rel($path, $base);
1285 $ret=~s/^// if defined $ret;
1289 sub displaytime ($;$$) {
1290 # Plugins can override this function to mark up the time to
1292 my $time=formattime($_[0], $_[1]);
1293 if ($config{html5}) {
1294 return '<time datetime="'.date_3339($_[0]).'"'.
1295 ($_[2] ? ' pubdate="pubdate"' : '').
1296 '>'.$time.'</time>';
1299 return '<span class="date">'.$time.'</span>';
1303 sub formattime ($;$) {
1304 # Plugins can override this function to format the time.
1307 if (! defined $format) {
1308 $format=$config{timeformat};
1311 return strftime_utf8($format, localtime($time));
1314 my $strftime_encoding;
1316 # strftime didn't know about encodings in older Perl, so make sure
1317 # its output is properly treated as utf8.
1318 # Note that this does not handle utf-8 in the format string.
1319 my $result = POSIX::strftime(@_);
1321 if (Encode::is_utf8($result)) {
1325 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1326 unless defined $strftime_encoding;
1328 ? Encode::decode($strftime_encoding, $result)
1335 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1336 POSIX::setlocale(&POSIX::LC_TIME, "C");
1337 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1338 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1342 sub beautify_urlpath ($) {
1345 # Ensure url is not an empty link, and if necessary,
1346 # add ./ to avoid colon confusion.
1347 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1351 if ($config{usedirs}) {
1352 $url =~ s!/index.$config{htmlext}$!/!;
1367 if (! $destsources{$to}) {
1372 return $config{url}.beautify_urlpath("/".$to);
1375 if (! defined $from) {
1376 my $u = $local_url || '';
1378 return $u.beautify_urlpath("/".$to);
1381 my $link = abs2rel($to, dirname(htmlpage($from)));
1383 return beautify_urlpath($link);
1386 sub isselflink ($$) {
1387 # Plugins can override this function to support special types
1392 return $page eq $link;
1395 sub htmllink ($$$;@) {
1396 my $lpage=shift; # the page doing the linking
1397 my $page=shift; # the page that will contain the link (different for inline)
1404 if (! $opts{forcesubpage}) {
1405 $bestlink=bestlink($lpage, $link);
1408 $bestlink="$lpage/".lc($link);
1412 if (defined $opts{linktext}) {
1413 $linktext=$opts{linktext};
1416 $linktext=pagetitle(basename($link));
1419 return "<span class=\"selflink\">$linktext</span>"
1420 if length $bestlink && isselflink($page, $bestlink) &&
1421 ! defined $opts{anchor};
1423 if (! $destsources{$bestlink}) {
1424 $bestlink=htmlpage($bestlink);
1426 if (! $destsources{$bestlink}) {
1428 if (length $config{cgiurl}) {
1429 $cgilink = "<a href=\"".
1434 )."\" rel=\"nofollow\">?</a>";
1436 return "<span class=\"createlink\">$cgilink$linktext</span>"
1440 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1441 $bestlink=beautify_urlpath($bestlink);
1443 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1444 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1447 if (defined $opts{anchor}) {
1448 $bestlink.="#".$opts{anchor};
1452 foreach my $attr (qw{rel class title}) {
1453 if (defined $opts{$attr}) {
1454 push @attrs, " $attr=\"$opts{$attr}\"";
1458 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1463 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1466 # Username to display for openid accounts.
1467 sub openiduser ($) {
1470 if (defined $user && $user =~ m!^https?://! &&
1471 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1474 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1475 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1478 # backcompat with old version
1479 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1480 $display=$oid->display;
1483 # Convert "user.somehost.com" to "user [somehost.com]"
1484 # (also "user.somehost.co.uk")
1485 if ($display !~ /\[/) {
1486 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1488 # Convert "http://somehost.com/user" to "user [somehost.com]".
1489 # (also "https://somehost.com/user/")
1490 if ($display !~ /\[/) {
1491 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1493 $display=~s!^https?://!!; # make sure this is removed
1494 eval q{use CGI 'escapeHTML'};
1496 return escapeHTML($display);
1501 # Username to display for emailauth accounts.
1504 if (defined $user && $user =~ m/(.+)@/) {
1506 # remove any characters from not allowed in wiki files
1507 # support use w/o %config set
1508 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1509 $nick=~s/[^$chars]/_/g;
1515 # Some user information should not be exposed in commit metadata, etc.
1516 # This generates a cloaked form of such information.
1519 # cloak email address using http://xmlns.com/foaf/spec/#term_mbox_sha1sum
1520 if ($user=~m/(.+)@/) {
1522 eval q{use Digest::SHA};
1524 return $nick.'@'.Digest::SHA::sha1_hex("mailto:$user");
1531 sub htmlize ($$$$) {
1537 my $oneline = $content !~ /\n/;
1539 if (exists $hooks{htmlize}{$type}) {
1540 $content=$hooks{htmlize}{$type}{call}->(
1542 content => $content,
1546 error("htmlization of $type not supported");
1549 run_hooks(sanitize => sub {
1552 destpage => $destpage,
1553 content => $content,
1558 # hack to get rid of enclosing junk added by markdown
1559 # and other htmlizers/sanitizers
1560 $content=~s/^<p>//i;
1561 $content=~s/<\/p>\n*$//i;
1572 run_hooks(linkify => sub {
1575 destpage => $destpage,
1576 content => $content,
1584 our $preprocess_preview=0;
1585 sub preprocess ($$$;$$) {
1586 my $page=shift; # the page the data comes from
1587 my $destpage=shift; # the page the data will appear in (different for inline)
1592 # Using local because it needs to be set within any nested calls
1594 local $preprocess_preview=$preview if defined $preview;
1601 $params="" if ! defined $params;
1603 if (length $escape) {
1604 return "[[$prefix$command $params]]";
1606 elsif (exists $hooks{preprocess}{$command}) {
1607 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1608 # Note: preserve order of params, some plugins may
1609 # consider it significant.
1611 while ($params =~ m{
1612 (?:([-.\w]+)=)? # 1: named parameter key?
1614 """(.*?)""" # 2: triple-quoted value
1616 "([^"]*?)" # 3: single-quoted value
1618 '''(.*?)''' # 4: triple-single-quote
1620 <<([a-zA-Z]+)\n # 5: heredoc start
1621 (.*?)\n\5 # 6: heredoc value
1623 (\S+) # 7: unquoted value
1625 (?:\s+|$) # delimiter to next param
1635 elsif (defined $3) {
1638 elsif (defined $4) {
1641 elsif (defined $7) {
1644 elsif (defined $6) {
1649 push @params, $key, $val;
1652 push @params, $val, '';
1655 if ($preprocessing{$page}++ > 8) {
1656 # Avoid loops of preprocessed pages preprocessing
1657 # other pages that preprocess them, etc.
1658 return "[[!$command <span class=\"error\">".
1659 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1660 $page, $preprocessing{$page}).
1666 $hooks{preprocess}{$command}{call}->(
1669 destpage => $destpage,
1670 preview => $preprocess_preview,
1676 eval q{use HTML::Entities};
1677 # Also encode most ASCII punctuation
1678 # as entities so that error messages
1679 # are not interpreted as Markdown etc.
1680 $error = encode_entities($error, '^-A-Za-z0-9+_,./:;= '."'");
1681 $ret="[[!$command <span class=\"error\">".
1682 gettext("Error").": $error"."</span>]]";
1686 # use void context during scan pass
1688 $hooks{preprocess}{$command}{call}->(
1691 destpage => $destpage,
1692 preview => $preprocess_preview,
1697 $preprocessing{$page}--;
1701 return "[[$prefix$command $params]]";
1706 if ($config{prefix_directives}) {
1709 \[\[(!) # directive open; 2: prefix
1710 ([-\w]+) # 3: command
1711 ( # 4: the parameters..
1712 \s+ # Must have space if parameters present
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
1737 \[\[(!?) # directive open; 2: optional prefix
1738 ([-\w]+) # 3: command
1740 ( # 4: the parameters..
1742 (?:[-.\w]+=)? # named parameter key?
1744 """.*?""" # triple-quoted value
1746 "[^"]*?" # single-quoted value
1748 '''.*?''' # triple-single-quote
1750 <<([a-zA-Z]+)\n # 5: heredoc start
1751 (?:.*?)\n\5 # heredoc value
1753 [^"\s\]]+ # unquoted value
1755 \s* # whitespace or end
1758 *) # 0 or more parameters
1759 \]\] # directive closed
1763 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1772 run_hooks(filter => sub {
1773 $content=shift->(page => $page, destpage => $destpage,
1774 content => $content);
1780 sub check_canedit ($$$;$) {
1787 run_hooks(canedit => sub {
1788 return if defined $canedit;
1789 my $ret=shift->($page, $q, $session);
1794 elsif (ref $ret eq 'CODE') {
1795 $ret->() unless $nonfatal;
1798 elsif (defined $ret) {
1799 error($ret) unless $nonfatal;
1804 return defined $canedit ? $canedit : 1;
1807 sub check_content (@) {
1810 return 1 if ! exists $hooks{checkcontent}; # optimisation
1812 if (exists $pagesources{$params{page}}) {
1814 my %old=map { $_ => 1 }
1815 split("\n", readfile(srcfile($pagesources{$params{page}})));
1816 foreach my $line (split("\n", $params{content})) {
1817 push @diff, $line if ! exists $old{$line};
1819 $params{diff}=join("\n", @diff);
1823 run_hooks(checkcontent => sub {
1824 return if defined $ok;
1825 my $ret=shift->(%params);
1830 elsif (ref $ret eq 'CODE') {
1831 $ret->() unless $params{nonfatal};
1834 elsif (defined $ret) {
1835 error($ret) unless $params{nonfatal};
1841 return defined $ok ? $ok : 1;
1844 sub check_canchange (@) {
1846 my $cgi = $params{cgi};
1847 my $session = $params{session};
1848 my @changes = @{$params{changes}};
1851 foreach my $change (@changes) {
1852 # This untaint is safe because we check file_pruned and
1854 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1855 $file=possibly_foolish_untaint($file);
1856 if (! defined $file || ! length $file ||
1857 file_pruned($file)) {
1858 error(sprintf(gettext("bad file name %s"), $file));
1861 my $type=pagetype($file);
1862 my $page=pagename($file) if defined $type;
1864 if ($change->{action} eq 'add') {
1868 if ($change->{action} eq 'change' ||
1869 $change->{action} eq 'add') {
1870 if (defined $page) {
1871 check_canedit($page, $cgi, $session);
1875 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1876 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1877 check_canedit($file, $cgi, $session);
1882 elsif ($change->{action} eq 'remove') {
1883 # check_canremove tests to see if the file is present
1884 # on disk. This will fail when a single commit adds a
1885 # file and then removes it again. Avoid the problem
1886 # by not testing the removal in such pairs of changes.
1887 # (The add is still tested, just to make sure that
1888 # no data is added to the repo that a web edit
1890 next if $newfiles{$file};
1892 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1893 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1894 check_canedit(defined $page ? $page : $file, $cgi, $session);
1899 error "unknown action ".$change->{action};
1902 error sprintf(gettext("you are not allowed to change %s"), $file);
1910 # Take an exclusive lock on the wiki to prevent multiple concurrent
1911 # run issues. The lock will be dropped on program exit.
1912 if (! -d $config{wikistatedir}) {
1913 mkdir($config{wikistatedir});
1915 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1916 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1917 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1918 debug("failed to get lock; waiting...");
1919 if (! flock($wikilock, LOCK_EX)) {
1920 error("failed to get lock");
1927 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1928 return close($wikilock) if $wikilock;
1934 sub commit_hook_enabled () {
1935 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1936 error("cannot write to $config{wikistatedir}/commitlock: $!");
1937 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1938 close($commitlock) || error("failed closing commitlock: $!");
1941 close($commitlock) || error("failed closing commitlock: $!");
1945 sub disable_commit_hook () {
1946 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1947 error("cannot write to $config{wikistatedir}/commitlock: $!");
1948 if (! flock($commitlock, 2)) { # LOCK_EX
1949 error("failed to get commit lock");
1954 sub enable_commit_hook () {
1955 return close($commitlock) if $commitlock;
1960 %oldrenderedfiles=%pagectime=();
1961 my $rebuild=$config{rebuild};
1963 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1964 %destsources=%renderedfiles=%pagecase=%pagestate=
1965 %depends_simple=%typedlinks=%oldtypedlinks=();
1968 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1969 if (-e "$config{wikistatedir}/index") {
1970 system("ikiwiki-transition", "indexdb", $config{srcdir});
1971 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1974 # gettime on first build
1975 $config{gettime}=1 unless defined $config{gettime};
1980 my $index=Storable::fd_retrieve($in);
1981 if (! defined $index) {
1986 if (exists $index->{version} && ! ref $index->{version}) {
1987 $pages=$index->{page};
1988 %wikistate=%{$index->{state}};
1989 # Handle plugins that got disabled by loading a new setup.
1990 if (exists $config{setupfile}) {
1991 require IkiWiki::Setup;
1992 IkiWiki::Setup::disabled_plugins(
1993 grep { ! $loaded_plugins{$_} } keys %wikistate);
2001 foreach my $src (keys %$pages) {
2002 my $d=$pages->{$src};
2004 if (exists $d->{page} && ! $rebuild) {
2008 $page=pagename($src);
2010 $pagectime{$page}=$d->{ctime};
2011 $pagesources{$page}=$src;
2013 $pagemtime{$page}=$d->{mtime};
2014 $renderedfiles{$page}=$d->{dest};
2015 if (exists $d->{links} && ref $d->{links}) {
2016 $links{$page}=$d->{links};
2017 $oldlinks{$page}=[@{$d->{links}}];
2019 if (ref $d->{depends_simple} eq 'ARRAY') {
2021 $depends_simple{$page}={
2022 map { $_ => 1 } @{$d->{depends_simple}}
2025 elsif (exists $d->{depends_simple}) {
2026 $depends_simple{$page}=$d->{depends_simple};
2028 if (exists $d->{dependslist}) {
2031 map { $_ => $DEPEND_CONTENT }
2032 @{$d->{dependslist}}
2035 elsif (exists $d->{depends} && ! ref $d->{depends}) {
2037 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
2039 elsif (exists $d->{depends}) {
2040 $depends{$page}=$d->{depends};
2042 if (exists $d->{state}) {
2043 $pagestate{$page}=$d->{state};
2045 if (exists $d->{typedlinks}) {
2046 $typedlinks{$page}=$d->{typedlinks};
2048 while (my ($type, $links) = each %{$typedlinks{$page}}) {
2049 next unless %$links;
2050 $oldtypedlinks{$page}{$type} = {%$links};
2054 $oldrenderedfiles{$page}=[@{$d->{dest}}];
2056 foreach my $page (keys %pagesources) {
2057 $pagecase{lc $page}=$page;
2059 foreach my $page (keys %renderedfiles) {
2060 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
2062 $lastrev=$index->{lastrev};
2063 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
2068 run_hooks(savestate => sub { shift->() });
2070 my @plugins=keys %loaded_plugins;
2072 if (! -d $config{wikistatedir}) {
2073 mkdir($config{wikistatedir});
2075 my $newfile="$config{wikistatedir}/indexdb.new";
2076 my $cleanup = sub { unlink($newfile) };
2077 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
2080 foreach my $page (keys %pagemtime) {
2081 next unless $pagemtime{$page};
2082 my $src=$pagesources{$page};
2084 $index{page}{$src}={
2086 ctime => $pagectime{$page},
2087 mtime => $pagemtime{$page},
2088 dest => $renderedfiles{$page},
2089 links => $links{$page},
2092 if (exists $depends{$page}) {
2093 $index{page}{$src}{depends} = $depends{$page};
2096 if (exists $depends_simple{$page}) {
2097 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2100 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2101 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2104 if (exists $pagestate{$page}) {
2105 $index{page}{$src}{state}=$pagestate{$page};
2110 foreach my $id (@plugins) {
2111 $index{state}{$id}={}; # used to detect disabled plugins
2112 foreach my $key (keys %{$wikistate{$id}}) {
2113 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2117 $index{lastrev}=$lastrev;
2118 $index{underlayfiles}=\@underlayfiles;
2120 $index{version}="3";
2121 my $ret=Storable::nstore_fd(\%index, $out);
2122 return if ! defined $ret || ! $ret;
2123 close $out || error("failed saving to $newfile: $!", $cleanup);
2124 rename($newfile, "$config{wikistatedir}/indexdb") ||
2125 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2130 sub template_file ($) {
2133 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2135 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2136 $template=srcfile($pagesources{$tpage}, 1);
2140 $template=srcfile($tpage, 1);
2143 if (defined $template) {
2144 return $template, $tpage, 1 if wantarray;
2148 $name=~s:/::; # avoid path traversal
2149 foreach my $dir ($config{templatedir},
2150 "$installdir/share/ikiwiki/templates") {
2151 if (-e "$dir/$name") {
2152 $template="$dir/$name";
2156 if (defined $template) {
2157 return $template, $tpage if wantarray;
2165 sub template_depends ($$;@) {
2169 my ($filename, $tpage, $untrusted)=template_file($name);
2170 if (! defined $filename) {
2171 error(sprintf(gettext("template %s not found"), $name))
2174 if (defined $page && defined $tpage) {
2175 add_depends($page, $tpage);
2180 my $text_ref = shift;
2181 ${$text_ref} = decode_utf8(${$text_ref});
2182 run_hooks(readtemplate => sub {
2183 ${$text_ref} = shift->(
2186 content => ${$text_ref},
2187 untrusted => $untrusted,
2191 loop_context_vars => 1,
2192 die_on_bad_params => 0,
2193 parent_global_vars => 1,
2194 filename => $filename,
2196 ($untrusted ? (no_includes => 1) : ()),
2198 return @opts if wantarray;
2200 require HTML::Template;
2201 return HTML::Template->new(@opts);
2204 sub template ($;@) {
2205 template_depends(shift, undef, @_);
2208 sub templateactions ($$) {
2214 run_hooks(pageactions => sub {
2215 push @actions, map { { action => $_ } }
2216 grep { defined } shift->(page => $page);
2218 $template->param(actions => \@actions);
2220 if ($config{cgiurl} && exists $hooks{auth}) {
2221 $template->param(prefsurl => cgiurl(do => "prefs"));
2225 if ($have_actions || @actions) {
2226 $template->param(have_actions => 1);
2233 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2234 error 'hook requires type, call, and id parameters';
2237 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2239 $hooks{$param{type}}{$param{id}}=\%param;
2243 sub run_hooks ($$) {
2244 # Calls the given sub for each hook of the given type,
2245 # passing it the hook function to call.
2249 if (exists $hooks{$type}) {
2250 my (@first, @middle, @last);
2251 foreach my $id (keys %{$hooks{$type}}) {
2252 if ($hooks{$type}{$id}{first}) {
2255 elsif ($hooks{$type}{$id}{last}) {
2262 foreach my $id (@first, @middle, @last) {
2263 $sub->($hooks{$type}{$id}{call});
2271 $hooks{rcs}{rcs_update}{call}->(@_);
2274 sub rcs_prepedit ($) {
2275 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2278 sub rcs_commit (@) {
2279 $hooks{rcs}{rcs_commit}{call}->(@_);
2282 sub rcs_commit_staged (@) {
2283 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2287 $hooks{rcs}{rcs_add}{call}->(@_);
2290 sub rcs_remove ($) {
2291 $hooks{rcs}{rcs_remove}{call}->(@_);
2294 sub rcs_rename ($$) {
2295 $hooks{rcs}{rcs_rename}{call}->(@_);
2298 sub rcs_recentchanges ($) {
2299 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2302 sub rcs_diff ($;$) {
2303 $hooks{rcs}{rcs_diff}{call}->(@_);
2306 sub rcs_getctime ($) {
2307 $hooks{rcs}{rcs_getctime}{call}->(@_);
2310 sub rcs_getmtime ($) {
2311 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2314 sub rcs_receive () {
2315 $hooks{rcs}{rcs_receive}{call}->();
2318 sub add_depends ($$;$) {
2321 my $deptype=shift || $DEPEND_CONTENT;
2323 # Is the pagespec a simple page name?
2324 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2325 $pagespec !~ /[\s*?()!]/) {
2326 $depends_simple{$page}{lc $pagespec} |= $deptype;
2330 # Add explicit dependencies for influences.
2331 my $sub=pagespec_translate($pagespec);
2332 return unless defined $sub;
2333 foreach my $p (keys %pagesources) {
2334 my $r=$sub->($p, location => $page);
2335 my $i=$r->influences;
2336 my $static=$r->influences_static;
2337 foreach my $k (keys %$i) {
2338 next unless $r || $static || $k eq $page;
2339 $depends_simple{$page}{lc $k} |= $i->{$k};
2344 $depends{$page}{$pagespec} |= $deptype;
2350 foreach my $type (@_) {
2351 if ($type eq 'presence') {
2352 $deptype |= $DEPEND_PRESENCE;
2354 elsif ($type eq 'links') {
2355 $deptype |= $DEPEND_LINKS;
2357 elsif ($type eq 'content') {
2358 $deptype |= $DEPEND_CONTENT;
2364 my $file_prune_regexp;
2365 sub file_pruned ($) {
2368 if (defined $config{include} && length $config{include}) {
2369 return 0 if $file =~ m/$config{include}/;
2372 if (! defined $file_prune_regexp) {
2373 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2374 $file_prune_regexp=qr/$file_prune_regexp/;
2376 return $file =~ m/$file_prune_regexp/;
2379 sub define_gettext () {
2380 # If translation is needed, redefine the gettext function to do it.
2381 # Otherwise, it becomes a quick no-op.
2384 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2385 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2386 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2388 $gettext_obj=eval q{
2389 use Locale::gettext q{textdomain};
2390 Locale::gettext->domain('ikiwiki')
2395 no warnings 'redefine';
2397 $getobj->() if $getobj;
2399 $gettext_obj->get(shift);
2406 $getobj->() if $getobj;
2408 $gettext_obj->nget(@_);
2411 return ($_[2] == 1 ? $_[0] : $_[1])
2429 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2433 # Injects a new function into the symbol table to replace an
2434 # exported function.
2437 # This is deep ugly perl foo, beware.
2440 if (! defined $params{parent}) {
2441 $params{parent}='::';
2442 $params{old}=\&{$params{name}};
2443 $params{name}=~s/.*:://;
2445 my $parent=$params{parent};
2446 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2447 $ns = $params{parent} . $ns;
2448 inject(%params, parent => $ns) unless $ns eq '::main::';
2449 *{$ns . $params{name}} = $params{call}
2450 if exists ${$ns}{$params{name}} &&
2451 \&{${$ns}{$params{name}}} == $params{old};
2457 sub add_link ($$;$) {
2462 push @{$links{$page}}, $link
2463 unless grep { $_ eq $link } @{$links{$page}};
2465 if (defined $type) {
2466 $typedlinks{$page}{$type}{$link} = 1;
2470 sub add_autofile ($$$) {
2473 my $generator=shift;
2475 $autofiles{$file}{plugin}=$plugin;
2476 $autofiles{$file}{generator}=$generator;
2481 my $for_url = delete $params{for_url};
2482 # Fail safe, in case a plugin calling this function is relying on
2483 # a future parameter to make the UA more strict
2484 foreach my $key (keys %params) {
2485 error "Internal error: useragent(\"$key\" => ...) not understood";
2492 agent => $config{useragent},
2493 cookie_jar => $config{cookiejar},
2495 protocols_allowed => [qw(http https)],
2499 if (defined $for_url) {
2500 # We know which URL we're going to fetch, so we can choose
2501 # whether it's going to go through a proxy or not.
2503 # We reimplement http_proxy, https_proxy and no_proxy here, so
2504 # that we are not relying on LWP implementing them exactly the
2511 my $uri = URI->new($for_url);
2513 if ($uri->scheme eq 'http') {
2514 $proxy = $ENV{http_proxy};
2515 # HTTP_PROXY is deliberately not implemented
2516 # because the HTTP_* namespace is also used by CGI
2518 elsif ($uri->scheme eq 'https') {
2519 $proxy = $ENV{https_proxy};
2520 $proxy = $ENV{HTTPS_PROXY} unless defined $proxy;
2526 foreach my $var (qw(no_proxy NO_PROXY)) {
2527 my $no_proxy = $ENV{$var};
2528 if (defined $no_proxy) {
2529 foreach my $domain (split /\s*,\s*/, $no_proxy) {
2530 if ($domain =~ s/^\*?\.//) {
2531 # no_proxy="*.example.com" or
2532 # ".example.com": match suffix
2533 # against .example.com
2534 if ($uri->host =~ m/(^|\.)\Q$domain\E$/i) {
2539 # no_proxy="example.com":
2540 # match exactly example.com
2541 if (lc $uri->host eq lc $domain) {
2549 if (defined $proxy) {
2550 $proxies{$uri->scheme} = $proxy;
2551 # Paranoia: make sure we can't bypass the proxy
2552 $args{protocols_allowed} = [$uri->scheme];
2556 # The plugin doesn't know yet which URL(s) it's going to
2557 # fetch, so we have to make some conservative assumptions.
2558 my $http_proxy = $ENV{http_proxy};
2559 my $https_proxy = $ENV{https_proxy};
2560 $https_proxy = $ENV{HTTPS_PROXY} unless defined $https_proxy;
2562 # We don't respect no_proxy here: if we are not using the
2563 # paranoid user-agent, then we need to give the proxy the
2564 # opportunity to reject undesirable requests.
2566 # If we have one, we need the other: otherwise, neither
2567 # LWPx::ParanoidAgent nor the proxy would have the
2568 # opportunity to filter requests for the other protocol.
2569 if (defined $https_proxy && defined $http_proxy) {
2570 %proxies = (http => $http_proxy, https => $https_proxy);
2572 elsif (defined $https_proxy) {
2573 %proxies = (http => $https_proxy, https => $https_proxy);
2575 elsif (defined $http_proxy) {
2576 %proxies = (http => $http_proxy, https => $http_proxy);
2581 if (scalar keys %proxies) {
2582 # The configured proxy is responsible for deciding which
2583 # URLs are acceptable to fetch and which URLs are not.
2584 my $ua = LWP::UserAgent->new(%args);
2585 foreach my $scheme (@{$ua->protocols_allowed}) {
2586 unless ($proxies{$scheme}) {
2587 error "internal error: $scheme is allowed but has no proxy";
2590 # We can't pass the proxies in %args because that only
2591 # works since LWP 6.24.
2592 foreach my $scheme (keys %proxies) {
2593 $ua->proxy($scheme, $proxies{$scheme});
2598 eval q{use LWPx::ParanoidAgent};
2600 print STDERR "warning: installing LWPx::ParanoidAgent is recommended\n";
2601 return LWP::UserAgent->new(%args);
2603 return LWPx::ParanoidAgent->new(%args);
2606 sub sortspec_translate ($$) {
2608 my $reverse = shift;
2614 (-?) # group 1: perhaps negated
2617 \w+\([^\)]*\) # command(params)
2619 [^\s]+ # or anything else
2627 if ($word =~ m/^(\w+)\((.*)\)$/) {
2628 # command with parameters
2632 elsif ($word !~ m/^\w+$/) {
2633 error(sprintf(gettext("invalid sort type %s"), $word));
2644 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2645 if (defined $params) {
2646 push @data, $params;
2647 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2650 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2654 error(sprintf(gettext("unknown sort type %s"), $word));
2658 if (! length $code) {
2659 # undefined sorting method... sort arbitrarily
2668 return eval 'sub { '.$code.' }';
2671 sub pagespec_translate ($) {
2674 # Convert spec to perl code.
2678 \s* # ignore whitespace
2679 ( # 1: match a single word
2686 \w+\([^\)]*\) # command(params)
2688 [^\s()]+ # any other text
2690 \s* # ignore whitespace
2693 if (lc $word eq 'and') {
2696 elsif (lc $word eq 'or') {
2699 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2702 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2703 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2705 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2708 push @data, qq{unknown function in pagespec "$word"};
2709 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2714 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2718 if (! length $code) {
2719 $code="IkiWiki::FailReason->new('empty pagespec')";
2723 return eval 'sub { my $page=shift; '.$code.' }';
2726 sub pagespec_match ($$;@) {
2731 # Backwards compatability with old calling convention.
2733 unshift @params, 'location';
2736 my $sub=pagespec_translate($spec);
2737 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2739 return $sub->($page, @params);
2742 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2744 # Not exported yet, but could be in future if it is generally useful.
2745 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2746 # which is "more internal".
2747 sub sort_pages ($$;@) {
2751 $sort = sortspec_translate($sort, $params{reverse});
2752 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2755 sub pagespec_match_list ($$;@) {
2760 # Backwards compatability with old calling convention.
2762 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2763 $params{list}=$page;
2764 $page=$params{location}; # ugh!
2767 my $sub=pagespec_translate($pagespec);
2768 error "syntax error in pagespec \"$pagespec\""
2770 my $sort=sortspec_translate($params{sort}, $params{reverse})
2771 if defined $params{sort};
2774 if (exists $params{list}) {
2775 @candidates=exists $params{filter}
2776 ? grep { ! $params{filter}->($_) } @{$params{list}}
2780 @candidates=exists $params{filter}
2781 ? grep { ! $params{filter}->($_) } keys %pagesources
2782 : keys %pagesources;
2785 # clear params, remainder is passed to pagespec
2786 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2787 my $num=$params{num};
2788 delete @params{qw{num deptype reverse sort filter list}};
2790 # when only the top matches will be returned, it's efficient to
2791 # sort before matching to pagespec,
2792 if (defined $num && defined $sort) {
2793 @candidates=IkiWiki::SortSpec::sort_pages(
2794 $sort, @candidates);
2800 my $accum=IkiWiki::SuccessReason->new();
2801 foreach my $p (@candidates) {
2802 my $r=$sub->($p, %params, location => $page);
2803 error(sprintf(gettext("cannot match pages: %s"), $r))
2804 if $r->isa("IkiWiki::ErrorReason");
2805 unless ($r || $r->influences_static) {
2806 $r->remove_influence($p);
2811 last if defined $num && ++$count == $num;
2815 # Add simple dependencies for accumulated influences.
2816 my $i=$accum->influences;
2817 foreach my $k (keys %$i) {
2818 $depends_simple{$page}{lc $k} |= $i->{$k};
2821 # when all matches will be returned, it's efficient to
2822 # sort after matching
2823 if (! defined $num && defined $sort) {
2824 return IkiWiki::SortSpec::sort_pages(
2832 sub pagespec_valid ($) {
2835 return defined pagespec_translate($spec);
2839 my $re=quotemeta(shift);
2845 package IkiWiki::FailReason;
2848 '""' => sub { $_[0][0] },
2850 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2851 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2852 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2856 our @ISA = 'IkiWiki::SuccessReason';
2858 package IkiWiki::SuccessReason;
2860 # A blessed array-ref:
2862 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2864 # - if absent or false, the influences of this evaluation are "static",
2865 # see the influences_static method
2866 # - if true, they are dynamic (not static)
2867 # [1]{any other key}:
2868 # the dependency types of influences, as returned by the influences method
2871 # in string context, it's the human-readable reason
2872 '""' => sub { $_[0][0] },
2873 # in boolean context, SuccessReason is 1 and FailReason is 0
2875 # negating a result gives the opposite result with the same influences
2876 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2877 # A & B = (A ? B : A) with the influences of both
2878 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2879 # A | B = (A ? A : B) with the influences of both
2880 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2884 # SuccessReason->new("human-readable reason", page => deptype, ...)
2889 return bless [$value, {@_}], $class;
2892 # influences(): return a reference to a copy of the hash
2893 # { page => dependency type } describing the pages that indirectly influenced
2894 # this result, but would not cause a dependency through ikiwiki's core
2897 # See [[todo/dependency_types]] for extensive discussion of what this means.
2899 # influences(page => deptype, ...): remove all influences, replace them
2900 # with the arguments, and return a reference to a copy of the new influences.
2904 $this->[1]={@_} if @_;
2905 my %i=%{$this->[1]};
2910 # True if this result has the same influences whichever page it matches,
2911 # For instance, whether bar matches backlink(foo) is influenced only by
2912 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2913 # which does not mention bar anywhere.
2915 # False if this result would have different influences when matching
2916 # different pages. For instance, when testing whether link(foo) matches bar,
2917 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2918 # bar's links could change the outcome; so its influences are not the same
2919 # as when testing whether link(foo) matches baz.
2921 # Static influences are one of the things that make pagespec_match_list
2922 # more efficient than repeated calls to pagespec_match.
2924 sub influences_static {
2925 return ! $_[0][1]->{""};
2928 # Change the influences of $this to be the influences of "$this & $other"
2929 # or "$this | $other".
2931 # If both $this and $other are either successful or have influences,
2932 # or this is an "or" operation, the result has all the influences from
2933 # either of the arguments. It has dynamic influences if either argument
2934 # has dynamic influences.
2936 # If this is an "and" operation, and at least one argument is a
2937 # FailReason with no influences, the result has no influences, and they
2938 # are not dynamic. For instance, link(foo) matching bar is influenced
2939 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2940 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2941 # bar, because it would be false however often you edit bar.
2943 sub merge_influences {
2948 # This "if" is odd because it needs to avoid negating $this
2949 # or $other, which would alter the objects in-place. Be careful.
2950 if (! $anded || (($this || %{$this->[1]}) &&
2951 ($other || %{$other->[1]}))) {
2952 foreach my $influence (keys %{$other->[1]}) {
2953 $this->[1]{$influence} |= $other->[1]{$influence};
2962 # Change $this so it is not considered to be influenced by $torm.
2964 sub remove_influence {
2968 delete $this->[1]{$torm};
2971 package IkiWiki::ErrorReason;
2973 our @ISA = 'IkiWiki::FailReason';
2975 package IkiWiki::PageSpec;
2981 if ($path =~ m!^\.(/|$)!) {
2983 $from=~s#/?[^/]+$## if defined $from;
2985 $path="$from/$path" if defined $from && length $from;
2989 $path = "" unless defined $path;
2998 sub match_glob ($$;@) {
3003 $glob=derel($glob, $params{location});
3005 # Instead of converting the glob to a regex every time,
3006 # cache the compiled regex to save time.
3007 my $re=$glob_cache{$glob};
3008 unless (defined $re) {
3009 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
3012 if (! IkiWiki::isinternal($page) || $params{internal}) {
3013 return IkiWiki::SuccessReason->new("$glob matches $page");
3016 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
3020 return IkiWiki::FailReason->new("$glob does not match $page");
3024 sub match_internal ($$;@) {
3025 return match_glob(shift, shift, @_, internal => 1)
3028 sub match_page ($$;@) {
3030 my $match=match_glob($page, shift, @_);
3032 my $source=exists $IkiWiki::pagesources{$page} ?
3033 $IkiWiki::pagesources{$page} :
3034 $IkiWiki::delpagesources{$page};
3035 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
3036 if (! defined $type) {
3037 return IkiWiki::FailReason->new("$page is not a page");
3043 sub match_link ($$;@) {
3048 $link=derel($link, $params{location});
3049 my $from=exists $params{location} ? $params{location} : '';
3050 my $linktype=$params{linktype};
3052 if (defined $linktype) {
3053 $qualifier=" with type $linktype";
3056 my $links = $IkiWiki::links{$page};
3057 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
3058 unless $links && @{$links};
3059 my $bestlink = IkiWiki::bestlink($from, $link);
3060 foreach my $p (@{$links}) {
3061 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
3063 if (length $bestlink) {
3064 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
3065 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
3069 if (match_glob($p, $link, %params)) {
3070 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
3072 my ($p_rel)=$p=~/^\/?(.*)/;
3074 if (match_glob($p_rel, $link, %params)) {
3075 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
3079 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
3082 sub match_backlink ($$;@) {
3086 if ($testpage eq '.') {
3087 $testpage = $params{'location'}
3089 my $ret=match_link($testpage, $page, @_);
3090 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
3094 sub match_created_before ($$;@) {
3099 $testpage=derel($testpage, $params{location});
3101 if (exists $IkiWiki::pagectime{$testpage}) {
3102 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
3103 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3106 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3110 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
3114 sub match_created_after ($$;@) {
3119 $testpage=derel($testpage, $params{location});
3121 if (exists $IkiWiki::pagectime{$testpage}) {
3122 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
3123 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3126 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3130 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
3134 sub match_creation_day ($$;@) {
3137 if ($d !~ /^\d+$/) {
3138 return IkiWiki::ErrorReason->new("invalid day $d");
3140 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
3141 return IkiWiki::SuccessReason->new('creation_day matched');
3144 return IkiWiki::FailReason->new('creation_day did not match');
3148 sub match_creation_month ($$;@) {
3151 if ($m !~ /^\d+$/) {
3152 return IkiWiki::ErrorReason->new("invalid month $m");
3154 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
3155 return IkiWiki::SuccessReason->new('creation_month matched');
3158 return IkiWiki::FailReason->new('creation_month did not match');
3162 sub match_creation_year ($$;@) {
3165 if ($y !~ /^\d+$/) {
3166 return IkiWiki::ErrorReason->new("invalid year $y");
3168 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
3169 return IkiWiki::SuccessReason->new('creation_year matched');
3172 return IkiWiki::FailReason->new('creation_year did not match');
3176 sub match_user ($$;@) {
3181 if (! exists $params{user}) {
3182 return IkiWiki::ErrorReason->new("no user specified");
3185 my $regexp=IkiWiki::glob2re($user);
3187 if (defined $params{user} && $params{user}=~$regexp) {
3188 return IkiWiki::SuccessReason->new("user is $user");
3190 elsif (! defined $params{user}) {
3191 return IkiWiki::FailReason->new("not logged in");
3194 return IkiWiki::FailReason->new("user is $params{user}, not $user");
3198 sub match_admin ($$;@) {
3203 if (! exists $params{user}) {
3204 return IkiWiki::ErrorReason->new("no user specified");
3207 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3208 return IkiWiki::SuccessReason->new("user is an admin");
3210 elsif (! defined $params{user}) {
3211 return IkiWiki::FailReason->new("not logged in");
3214 return IkiWiki::FailReason->new("user is not an admin");
3218 sub match_ip ($$;@) {
3223 if (! exists $params{ip}) {
3224 return IkiWiki::ErrorReason->new("no IP specified");
3227 my $regexp=IkiWiki::glob2re(lc $ip);
3229 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3230 return IkiWiki::SuccessReason->new("IP is $ip");
3233 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3237 package IkiWiki::SortSpec;
3239 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3240 # are easily available in this namespace, for cmp functions to use them.
3247 IkiWiki::pagetitle(IkiWiki::basename($a))
3249 IkiWiki::pagetitle(IkiWiki::basename($b))
3252 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3253 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3254 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }