9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %linkbases %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 %linkbases %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/^\/+//) {
1155 foreach my $spec (keys %{$linkbases{pagespec}}) {
1156 if (pagespec_match($page, $spec)) {
1157 unshift @bases, @{$linkbases{pagespec}{$spec}};
1160 if (defined $linkbases{page}{$page}) {
1161 unshift @bases, @{$linkbases{page}{$page}};
1163 unshift @bases, $page;
1167 foreach my $cwd (@bases) {
1170 $l.="/" if length $l;
1173 if (exists $pagesources{$l}) {
1176 elsif (exists $pagecase{lc $l}) {
1177 return $pagecase{lc $l};
1179 } while $cwd=~s{/?[^/]+$}{};
1182 if (length $config{userdir}) {
1183 my $l = "$config{userdir}/".lc($link);
1184 if (exists $pagesources{$l}) {
1187 elsif (exists $pagecase{lc $l}) {
1188 return $pagecase{lc $l};
1192 #print STDERR "warning: page $page, broken link: $link\n";
1196 sub isinlinableimage ($) {
1199 return $config{inlineimages} && $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1202 sub pagetitle ($;$) {
1204 my $unescaped=shift;
1207 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1210 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1218 # support use w/o %config set
1219 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1220 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1226 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1227 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1234 my $cgiurl=$local_cgiurl;
1236 if (exists $params{cgiurl}) {
1237 $cgiurl=$params{cgiurl};
1238 delete $params{cgiurl};
1246 join("&", map $_."=".uri_escape_utf8($params{$_}), sort(keys %params));
1249 sub cgiurl_abs (@) {
1251 URI->new_abs(cgiurl(@_), $config{cgiurl});
1254 # Same as cgiurl_abs, but when the user connected using https,
1255 # will be a https url even if the cgiurl is normally a http url.
1257 # This should be used for anything involving emailing a login link,
1258 # because a https session cookie will not be sent over http.
1259 sub cgiurl_abs_samescheme (@) {
1260 my $u=cgiurl_abs(@_);
1261 if (($ENV{HTTPS} && lc $ENV{HTTPS} ne "off")) {
1262 $u=~s/^http:/https:/i;
1270 return $local_url if ! defined $page;
1272 $page=htmlpage($page);
1274 $page=~s/[^\/]+\//..\//g;
1282 return $url unless defined $urlbase && length $urlbase;
1285 URI->new_abs($url, $urlbase)->as_string;
1289 # Work around very innefficient behavior in File::Spec if abs2rel
1290 # is passed two relative paths. It's much faster if paths are
1291 # absolute! (Debian bug #376658; fixed in debian unstable now)
1296 my $ret=File::Spec->abs2rel($path, $base);
1297 $ret=~s/^// if defined $ret;
1301 sub displaytime ($;$$) {
1302 # Plugins can override this function to mark up the time to
1304 my $time=formattime($_[0], $_[1]);
1305 if ($config{html5}) {
1306 return '<time datetime="'.date_3339($_[0]).'"'.
1307 ($_[2] ? ' pubdate="pubdate"' : '').
1308 '>'.$time.'</time>';
1311 return '<span class="date">'.$time.'</span>';
1315 sub formattime ($;$) {
1316 # Plugins can override this function to format the time.
1319 if (! defined $format) {
1320 $format=$config{timeformat};
1323 return strftime_utf8($format, localtime($time));
1326 my $strftime_encoding;
1328 # strftime didn't know about encodings in older Perl, so make sure
1329 # its output is properly treated as utf8.
1330 # Note that this does not handle utf-8 in the format string.
1331 my $result = POSIX::strftime(@_);
1333 if (Encode::is_utf8($result)) {
1337 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1338 unless defined $strftime_encoding;
1340 ? Encode::decode($strftime_encoding, $result)
1347 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1348 POSIX::setlocale(&POSIX::LC_TIME, "C");
1349 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1350 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1354 sub beautify_urlpath ($) {
1357 # Ensure url is not an empty link, and if necessary,
1358 # add ./ to avoid colon confusion.
1359 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1363 if ($config{usedirs}) {
1364 $url =~ s!/index.$config{htmlext}$!/!;
1379 if (! $destsources{$to}) {
1384 return $config{url}.beautify_urlpath("/".$to);
1387 if (! defined $from) {
1388 my $u = $local_url || '';
1390 return $u.beautify_urlpath("/".$to);
1393 my $link = abs2rel($to, dirname(htmlpage($from)));
1395 return beautify_urlpath($link);
1398 sub isselflink ($$) {
1399 # Plugins can override this function to support special types
1404 return $page eq $link;
1407 sub htmllink ($$$;@) {
1408 my $lpage=shift; # the page doing the linking
1409 my $page=shift; # the page that will contain the link (different for inline)
1416 if (! $opts{forcesubpage}) {
1417 $bestlink=bestlink($lpage, $link);
1420 $bestlink="$lpage/".lc($link);
1424 if (defined $opts{linktext}) {
1425 $linktext=$opts{linktext};
1428 $linktext=pagetitle(basename($link));
1431 return "<span class=\"selflink\">$linktext</span>"
1432 if length $bestlink && isselflink($page, $bestlink) &&
1433 ! defined $opts{anchor};
1435 if (! $destsources{$bestlink}) {
1436 $bestlink=htmlpage($bestlink);
1438 if (! $destsources{$bestlink}) {
1440 if (length $config{cgiurl}) {
1441 $cgilink = "<a href=\"".
1446 )."\" rel=\"nofollow\">?</a>";
1448 return "<span class=\"createlink\">$cgilink$linktext</span>"
1452 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1453 $bestlink=beautify_urlpath($bestlink);
1455 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1456 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1459 if (defined $opts{anchor}) {
1460 $bestlink.="#".$opts{anchor};
1464 foreach my $attr (qw{rel class title}) {
1465 if (defined $opts{$attr}) {
1466 push @attrs, " $attr=\"$opts{$attr}\"";
1470 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1475 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1478 # Username to display for openid accounts.
1479 sub openiduser ($) {
1482 if (defined $user && $user =~ m!^https?://! &&
1483 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1486 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1487 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1490 # backcompat with old version
1491 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1492 $display=$oid->display;
1495 # Convert "user.somehost.com" to "user [somehost.com]"
1496 # (also "user.somehost.co.uk")
1497 if ($display !~ /\[/) {
1498 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1500 # Convert "http://somehost.com/user" to "user [somehost.com]".
1501 # (also "https://somehost.com/user/")
1502 if ($display !~ /\[/) {
1503 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1505 $display=~s!^https?://!!; # make sure this is removed
1506 eval q{use CGI 'escapeHTML'};
1508 return escapeHTML($display);
1513 # Username to display for emailauth accounts.
1516 if (defined $user && $user =~ m/(.+)@/) {
1518 # remove any characters from not allowed in wiki files
1519 # support use w/o %config set
1520 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1521 $nick=~s/[^$chars]/_/g;
1527 # Some user information should not be exposed in commit metadata, etc.
1528 # This generates a cloaked form of such information.
1531 # cloak email address using http://xmlns.com/foaf/spec/#term_mbox_sha1sum
1532 if ($user=~m/(.+)@/) {
1534 eval q{use Digest::SHA};
1536 return $nick.'@'.Digest::SHA::sha1_hex("mailto:$user");
1543 sub htmlize ($$$$) {
1549 my $oneline = $content !~ /\n/;
1551 if (exists $hooks{htmlize}{$type}) {
1552 $content=$hooks{htmlize}{$type}{call}->(
1554 content => $content,
1558 error("htmlization of $type not supported");
1561 run_hooks(sanitize => sub {
1564 destpage => $destpage,
1565 content => $content,
1570 # hack to get rid of enclosing junk added by markdown
1571 # and other htmlizers/sanitizers
1572 $content=~s/^<p>//i;
1573 $content=~s/<\/p>\n*$//i;
1584 run_hooks(linkify => sub {
1587 destpage => $destpage,
1588 content => $content,
1596 our $preprocess_preview=0;
1597 sub preprocess ($$$;$$) {
1598 my $page=shift; # the page the data comes from
1599 my $destpage=shift; # the page the data will appear in (different for inline)
1604 # Using local because it needs to be set within any nested calls
1606 local $preprocess_preview=$preview if defined $preview;
1613 $params="" if ! defined $params;
1615 if (length $escape) {
1616 return "[[$prefix$command $params]]";
1618 elsif (exists $hooks{preprocess}{$command}) {
1619 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1620 # Note: preserve order of params, some plugins may
1621 # consider it significant.
1623 while ($params =~ m{
1624 (?:([-.\w]+)=)? # 1: named parameter key?
1626 """(.*?)""" # 2: triple-quoted value
1628 "([^"]*?)" # 3: single-quoted value
1630 '''(.*?)''' # 4: triple-single-quote
1632 <<([a-zA-Z]+)\n # 5: heredoc start
1633 (.*?)\n\5 # 6: heredoc value
1635 (\S+) # 7: unquoted value
1637 (?:\s+|$) # delimiter to next param
1647 elsif (defined $3) {
1650 elsif (defined $4) {
1653 elsif (defined $7) {
1656 elsif (defined $6) {
1661 push @params, $key, $val;
1664 push @params, $val, '';
1667 if ($preprocessing{$page}++ > 8) {
1668 # Avoid loops of preprocessed pages preprocessing
1669 # other pages that preprocess them, etc.
1670 return "[[!$command <span class=\"error\">".
1671 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1672 $page, $preprocessing{$page}).
1678 $hooks{preprocess}{$command}{call}->(
1681 destpage => $destpage,
1682 preview => $preprocess_preview,
1688 eval q{use HTML::Entities};
1689 # Also encode most ASCII punctuation
1690 # as entities so that error messages
1691 # are not interpreted as Markdown etc.
1692 $error = encode_entities($error, '^-A-Za-z0-9+_,./:;= '."'");
1693 $ret="[[!$command <span class=\"error\">".
1694 gettext("Error").": $error"."</span>]]";
1698 # use void context during scan pass
1700 $hooks{preprocess}{$command}{call}->(
1703 destpage => $destpage,
1704 preview => $preprocess_preview,
1709 $preprocessing{$page}--;
1713 return "[[$prefix$command $params]]";
1718 if ($config{prefix_directives}) {
1721 \[\[(!) # directive open; 2: prefix
1722 ([-\w]+) # 3: command
1723 ( # 4: the parameters..
1724 \s+ # Must have space if parameters present
1726 (?:[-.\w]+=)? # named parameter key?
1728 """.*?""" # triple-quoted value
1730 "[^"]*?" # single-quoted value
1732 '''.*?''' # triple-single-quote
1734 <<([a-zA-Z]+)\n # 5: heredoc start
1735 (?:.*?)\n\5 # heredoc value
1737 [^"\s\]]+ # unquoted value
1739 \s* # whitespace or end
1742 *)? # 0 or more parameters
1743 \]\] # directive closed
1749 \[\[(!?) # directive open; 2: optional prefix
1750 ([-\w]+) # 3: command
1752 ( # 4: the parameters..
1754 (?:[-.\w]+=)? # named parameter key?
1756 """.*?""" # triple-quoted value
1758 "[^"]*?" # single-quoted value
1760 '''.*?''' # triple-single-quote
1762 <<([a-zA-Z]+)\n # 5: heredoc start
1763 (?:.*?)\n\5 # heredoc value
1765 [^"\s\]]+ # unquoted value
1767 \s* # whitespace or end
1770 *) # 0 or more parameters
1771 \]\] # directive closed
1775 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1784 run_hooks(filter => sub {
1785 $content=shift->(page => $page, destpage => $destpage,
1786 content => $content);
1792 sub check_canedit ($$$;$) {
1799 run_hooks(canedit => sub {
1800 return if defined $canedit;
1801 my $ret=shift->($page, $q, $session);
1806 elsif (ref $ret eq 'CODE') {
1807 $ret->() unless $nonfatal;
1810 elsif (defined $ret) {
1811 error($ret) unless $nonfatal;
1816 return defined $canedit ? $canedit : 1;
1819 sub check_content (@) {
1822 return 1 if ! exists $hooks{checkcontent}; # optimisation
1824 if (exists $pagesources{$params{page}}) {
1826 my %old=map { $_ => 1 }
1827 split("\n", readfile(srcfile($pagesources{$params{page}})));
1828 foreach my $line (split("\n", $params{content})) {
1829 push @diff, $line if ! exists $old{$line};
1831 $params{diff}=join("\n", @diff);
1835 run_hooks(checkcontent => sub {
1836 return if defined $ok;
1837 my $ret=shift->(%params);
1842 elsif (ref $ret eq 'CODE') {
1843 $ret->() unless $params{nonfatal};
1846 elsif (defined $ret) {
1847 error($ret) unless $params{nonfatal};
1853 return defined $ok ? $ok : 1;
1856 sub check_canchange (@) {
1858 my $cgi = $params{cgi};
1859 my $session = $params{session};
1860 my @changes = @{$params{changes}};
1863 foreach my $change (@changes) {
1864 # This untaint is safe because we check file_pruned and
1866 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1867 $file=possibly_foolish_untaint($file);
1868 if (! defined $file || ! length $file ||
1869 file_pruned($file)) {
1870 error(sprintf(gettext("bad file name %s"), $file));
1873 my $type=pagetype($file);
1874 my $page=pagename($file) if defined $type;
1876 if ($change->{action} eq 'add') {
1880 if ($change->{action} eq 'change' ||
1881 $change->{action} eq 'add') {
1882 if (defined $page) {
1883 check_canedit($page, $cgi, $session);
1887 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1888 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1889 check_canedit($file, $cgi, $session);
1894 elsif ($change->{action} eq 'remove') {
1895 # check_canremove tests to see if the file is present
1896 # on disk. This will fail when a single commit adds a
1897 # file and then removes it again. Avoid the problem
1898 # by not testing the removal in such pairs of changes.
1899 # (The add is still tested, just to make sure that
1900 # no data is added to the repo that a web edit
1902 next if $newfiles{$file};
1904 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1905 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1906 check_canedit(defined $page ? $page : $file, $cgi, $session);
1911 error "unknown action ".$change->{action};
1914 error sprintf(gettext("you are not allowed to change %s"), $file);
1922 # Take an exclusive lock on the wiki to prevent multiple concurrent
1923 # run issues. The lock will be dropped on program exit.
1924 if (! -d $config{wikistatedir}) {
1925 mkdir($config{wikistatedir});
1927 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1928 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1929 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1930 debug("failed to get lock; waiting...");
1931 if (! flock($wikilock, LOCK_EX)) {
1932 error("failed to get lock");
1939 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1940 return close($wikilock) if $wikilock;
1946 sub commit_hook_enabled () {
1947 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1948 error("cannot write to $config{wikistatedir}/commitlock: $!");
1949 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1950 close($commitlock) || error("failed closing commitlock: $!");
1953 close($commitlock) || error("failed closing commitlock: $!");
1957 sub disable_commit_hook () {
1958 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1959 error("cannot write to $config{wikistatedir}/commitlock: $!");
1960 if (! flock($commitlock, 2)) { # LOCK_EX
1961 error("failed to get commit lock");
1966 sub enable_commit_hook () {
1967 return close($commitlock) if $commitlock;
1972 %oldrenderedfiles=%pagectime=();
1973 my $rebuild=$config{rebuild};
1975 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1976 %destsources=%renderedfiles=%pagecase=%pagestate=
1977 %depends_simple=%typedlinks=%oldtypedlinks=();
1978 %linkbases=(page=>{},pagespec=>{});
1981 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1982 if (-e "$config{wikistatedir}/index") {
1983 system("ikiwiki-transition", "indexdb", $config{srcdir});
1984 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1987 # gettime on first build
1988 $config{gettime}=1 unless defined $config{gettime};
1993 my $index=Storable::fd_retrieve($in);
1994 if (! defined $index) {
1999 if (exists $index->{version} && ! ref $index->{version}) {
2000 $pages=$index->{page};
2001 %wikistate=%{$index->{state}};
2002 # Handle plugins that got disabled by loading a new setup.
2003 if (exists $config{setupfile}) {
2004 require IkiWiki::Setup;
2005 IkiWiki::Setup::disabled_plugins(
2006 grep { ! $loaded_plugins{$_} } keys %wikistate);
2014 foreach my $src (keys %$pages) {
2015 my $d=$pages->{$src};
2017 if (exists $d->{page} && ! $rebuild) {
2021 $page=pagename($src);
2023 $pagectime{$page}=$d->{ctime};
2024 $pagesources{$page}=$src;
2026 $pagemtime{$page}=$d->{mtime};
2027 $renderedfiles{$page}=$d->{dest};
2028 if (exists $d->{links} && ref $d->{links}) {
2029 $links{$page}=$d->{links};
2030 $oldlinks{$page}=[@{$d->{links}}];
2032 if (ref $d->{depends_simple} eq 'ARRAY') {
2034 $depends_simple{$page}={
2035 map { $_ => 1 } @{$d->{depends_simple}}
2038 elsif (exists $d->{depends_simple}) {
2039 $depends_simple{$page}=$d->{depends_simple};
2041 if (exists $d->{dependslist}) {
2044 map { $_ => $DEPEND_CONTENT }
2045 @{$d->{dependslist}}
2048 elsif (exists $d->{depends} && ! ref $d->{depends}) {
2050 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
2052 elsif (exists $d->{depends}) {
2053 $depends{$page}=$d->{depends};
2055 if (exists $d->{state}) {
2056 $pagestate{$page}=$d->{state};
2058 if (exists $d->{typedlinks}) {
2059 $typedlinks{$page}=$d->{typedlinks};
2061 while (my ($type, $links) = each %{$typedlinks{$page}}) {
2062 next unless %$links;
2063 $oldtypedlinks{$page}{$type} = {%$links};
2067 $oldrenderedfiles{$page}=[@{$d->{dest}}];
2069 foreach my $page (keys %pagesources) {
2070 $pagecase{lc $page}=$page;
2072 foreach my $page (keys %renderedfiles) {
2073 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
2075 $lastrev=$index->{lastrev};
2076 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
2081 run_hooks(savestate => sub { shift->() });
2083 my @plugins=keys %loaded_plugins;
2085 if (! -d $config{wikistatedir}) {
2086 mkdir($config{wikistatedir});
2088 my $newfile="$config{wikistatedir}/indexdb.new";
2089 my $cleanup = sub { unlink($newfile) };
2090 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
2093 foreach my $page (keys %pagemtime) {
2094 next unless $pagemtime{$page};
2095 my $src=$pagesources{$page};
2097 $index{page}{$src}={
2099 ctime => $pagectime{$page},
2100 mtime => $pagemtime{$page},
2101 dest => $renderedfiles{$page},
2102 links => $links{$page},
2105 if (exists $depends{$page}) {
2106 $index{page}{$src}{depends} = $depends{$page};
2109 if (exists $depends_simple{$page}) {
2110 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2113 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2114 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2117 if (exists $pagestate{$page}) {
2118 $index{page}{$src}{state}=$pagestate{$page};
2123 foreach my $id (@plugins) {
2124 $index{state}{$id}={}; # used to detect disabled plugins
2125 foreach my $key (keys %{$wikistate{$id}}) {
2126 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2130 $index{lastrev}=$lastrev;
2131 $index{underlayfiles}=\@underlayfiles;
2133 $index{version}="3";
2134 my $ret=Storable::nstore_fd(\%index, $out);
2135 return if ! defined $ret || ! $ret;
2136 close $out || error("failed saving to $newfile: $!", $cleanup);
2137 rename($newfile, "$config{wikistatedir}/indexdb") ||
2138 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2143 sub template_file ($) {
2146 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2148 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2149 $template=srcfile($pagesources{$tpage}, 1);
2153 $template=srcfile($tpage, 1);
2156 if (defined $template) {
2157 return $template, $tpage, 1 if wantarray;
2161 $name=~s:/::; # avoid path traversal
2162 foreach my $dir ($config{templatedir},
2163 "$installdir/share/ikiwiki/templates") {
2164 if (-e "$dir/$name") {
2165 $template="$dir/$name";
2169 if (defined $template) {
2170 return $template, $tpage if wantarray;
2178 sub template_depends ($$;@) {
2182 my ($filename, $tpage, $untrusted)=template_file($name);
2183 if (! defined $filename) {
2184 error(sprintf(gettext("template %s not found"), $name))
2187 if (defined $page && defined $tpage) {
2188 add_depends($page, $tpage);
2193 my $text_ref = shift;
2194 ${$text_ref} = decode_utf8(${$text_ref});
2195 run_hooks(readtemplate => sub {
2196 ${$text_ref} = shift->(
2199 content => ${$text_ref},
2200 untrusted => $untrusted,
2204 loop_context_vars => 1,
2205 die_on_bad_params => 0,
2206 parent_global_vars => 1,
2207 filename => $filename,
2209 ($untrusted ? (no_includes => 1) : ()),
2211 return @opts if wantarray;
2213 require HTML::Template;
2214 return HTML::Template->new(@opts);
2217 sub template ($;@) {
2218 template_depends(shift, undef, @_);
2221 sub templateactions ($$) {
2227 run_hooks(pageactions => sub {
2228 push @actions, map { { action => $_ } }
2229 grep { defined } shift->(page => $page);
2231 $template->param(actions => \@actions);
2233 if ($config{cgiurl} && exists $hooks{auth}) {
2234 $template->param(prefsurl => cgiurl(do => "prefs"));
2238 if ($have_actions || @actions) {
2239 $template->param(have_actions => 1);
2246 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2247 error 'hook requires type, call, and id parameters';
2250 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2252 $hooks{$param{type}}{$param{id}}=\%param;
2256 sub run_hooks ($$) {
2257 # Calls the given sub for each hook of the given type,
2258 # passing it the hook function to call.
2262 if (exists $hooks{$type}) {
2263 my (@first, @middle, @last);
2264 foreach my $id (keys %{$hooks{$type}}) {
2265 if ($hooks{$type}{$id}{first}) {
2268 elsif ($hooks{$type}{$id}{last}) {
2275 foreach my $id (@first, @middle, @last) {
2276 $sub->($hooks{$type}{$id}{call});
2284 $hooks{rcs}{rcs_update}{call}->(@_);
2287 sub rcs_prepedit ($) {
2288 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2291 sub rcs_commit (@) {
2292 $hooks{rcs}{rcs_commit}{call}->(@_);
2295 sub rcs_commit_staged (@) {
2296 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2300 $hooks{rcs}{rcs_add}{call}->(@_);
2303 sub rcs_remove ($) {
2304 $hooks{rcs}{rcs_remove}{call}->(@_);
2307 sub rcs_rename ($$) {
2308 $hooks{rcs}{rcs_rename}{call}->(@_);
2311 sub rcs_recentchanges ($) {
2312 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2315 sub rcs_diff ($;$) {
2316 $hooks{rcs}{rcs_diff}{call}->(@_);
2319 sub rcs_getctime ($) {
2320 $hooks{rcs}{rcs_getctime}{call}->(@_);
2323 sub rcs_getmtime ($) {
2324 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2327 sub rcs_receive () {
2328 $hooks{rcs}{rcs_receive}{call}->();
2331 sub add_depends ($$;$) {
2334 my $deptype=shift || $DEPEND_CONTENT;
2336 # Is the pagespec a simple page name?
2337 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2338 $pagespec !~ /[\s*?()!]/) {
2339 $depends_simple{$page}{lc $pagespec} |= $deptype;
2343 # Add explicit dependencies for influences.
2344 my $sub=pagespec_translate($pagespec);
2345 return unless defined $sub;
2346 foreach my $p (keys %pagesources) {
2347 my $r=$sub->($p, location => $page);
2348 my $i=$r->influences;
2349 my $static=$r->influences_static;
2350 foreach my $k (keys %$i) {
2351 next unless $r || $static || $k eq $page;
2352 $depends_simple{$page}{lc $k} |= $i->{$k};
2357 $depends{$page}{$pagespec} |= $deptype;
2363 foreach my $type (@_) {
2364 if ($type eq 'presence') {
2365 $deptype |= $DEPEND_PRESENCE;
2367 elsif ($type eq 'links') {
2368 $deptype |= $DEPEND_LINKS;
2370 elsif ($type eq 'content') {
2371 $deptype |= $DEPEND_CONTENT;
2377 my $file_prune_regexp;
2378 sub file_pruned ($) {
2381 if (defined $config{include} && length $config{include}) {
2382 return 0 if $file =~ m/$config{include}/;
2385 if (! defined $file_prune_regexp) {
2386 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2387 $file_prune_regexp=qr/$file_prune_regexp/;
2389 return $file =~ m/$file_prune_regexp/;
2392 sub define_gettext () {
2393 # If translation is needed, redefine the gettext function to do it.
2394 # Otherwise, it becomes a quick no-op.
2397 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2398 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2399 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2401 $gettext_obj=eval q{
2402 use Locale::gettext q{textdomain};
2403 Locale::gettext->domain('ikiwiki')
2408 no warnings 'redefine';
2410 $getobj->() if $getobj;
2412 $gettext_obj->get(shift);
2419 $getobj->() if $getobj;
2421 $gettext_obj->nget(@_);
2424 return ($_[2] == 1 ? $_[0] : $_[1])
2442 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2446 # Injects a new function into the symbol table to replace an
2447 # exported function.
2450 # This is deep ugly perl foo, beware.
2453 if (! defined $params{parent}) {
2454 $params{parent}='::';
2455 $params{old}=\&{$params{name}};
2456 $params{name}=~s/.*:://;
2458 my $parent=$params{parent};
2459 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2460 $ns = $params{parent} . $ns;
2461 inject(%params, parent => $ns) unless $ns eq '::main::';
2462 *{$ns . $params{name}} = $params{call}
2463 if exists ${$ns}{$params{name}} &&
2464 \&{${$ns}{$params{name}}} == $params{old};
2470 sub add_link ($$;$) {
2475 push @{$links{$page}}, $link
2476 unless grep { $_ eq $link } @{$links{$page}};
2478 if (defined $type) {
2479 $typedlinks{$page}{$type}{$link} = 1;
2483 sub add_autofile ($$$) {
2486 my $generator=shift;
2488 $autofiles{$file}{plugin}=$plugin;
2489 $autofiles{$file}{generator}=$generator;
2494 my $for_url = delete $params{for_url};
2495 # Fail safe, in case a plugin calling this function is relying on
2496 # a future parameter to make the UA more strict
2497 foreach my $key (keys %params) {
2498 error "Internal error: useragent(\"$key\" => ...) not understood";
2505 agent => $config{useragent},
2506 cookie_jar => $config{cookiejar},
2508 protocols_allowed => [qw(http https)],
2512 if (defined $for_url) {
2513 # We know which URL we're going to fetch, so we can choose
2514 # whether it's going to go through a proxy or not.
2516 # We reimplement http_proxy, https_proxy and no_proxy here, so
2517 # that we are not relying on LWP implementing them exactly the
2524 my $uri = URI->new($for_url);
2526 if ($uri->scheme eq 'http') {
2527 $proxy = $ENV{http_proxy};
2528 # HTTP_PROXY is deliberately not implemented
2529 # because the HTTP_* namespace is also used by CGI
2531 elsif ($uri->scheme eq 'https') {
2532 $proxy = $ENV{https_proxy};
2533 $proxy = $ENV{HTTPS_PROXY} unless defined $proxy;
2539 foreach my $var (qw(no_proxy NO_PROXY)) {
2540 my $no_proxy = $ENV{$var};
2541 if (defined $no_proxy) {
2542 foreach my $domain (split /\s*,\s*/, $no_proxy) {
2543 if ($domain =~ s/^\*?\.//) {
2544 # no_proxy="*.example.com" or
2545 # ".example.com": match suffix
2546 # against .example.com
2547 if ($uri->host =~ m/(^|\.)\Q$domain\E$/i) {
2552 # no_proxy="example.com":
2553 # match exactly example.com
2554 if (lc $uri->host eq lc $domain) {
2562 if (defined $proxy) {
2563 $proxies{$uri->scheme} = $proxy;
2564 # Paranoia: make sure we can't bypass the proxy
2565 $args{protocols_allowed} = [$uri->scheme];
2569 # The plugin doesn't know yet which URL(s) it's going to
2570 # fetch, so we have to make some conservative assumptions.
2571 my $http_proxy = $ENV{http_proxy};
2572 my $https_proxy = $ENV{https_proxy};
2573 $https_proxy = $ENV{HTTPS_PROXY} unless defined $https_proxy;
2575 # We don't respect no_proxy here: if we are not using the
2576 # paranoid user-agent, then we need to give the proxy the
2577 # opportunity to reject undesirable requests.
2579 # If we have one, we need the other: otherwise, neither
2580 # LWPx::ParanoidAgent nor the proxy would have the
2581 # opportunity to filter requests for the other protocol.
2582 if (defined $https_proxy && defined $http_proxy) {
2583 %proxies = (http => $http_proxy, https => $https_proxy);
2585 elsif (defined $https_proxy) {
2586 %proxies = (http => $https_proxy, https => $https_proxy);
2588 elsif (defined $http_proxy) {
2589 %proxies = (http => $http_proxy, https => $http_proxy);
2594 if (scalar keys %proxies) {
2595 # The configured proxy is responsible for deciding which
2596 # URLs are acceptable to fetch and which URLs are not.
2597 my $ua = LWP::UserAgent->new(%args);
2598 foreach my $scheme (@{$ua->protocols_allowed}) {
2599 unless ($proxies{$scheme}) {
2600 error "internal error: $scheme is allowed but has no proxy";
2603 # We can't pass the proxies in %args because that only
2604 # works since LWP 6.24.
2605 foreach my $scheme (keys %proxies) {
2606 $ua->proxy($scheme, $proxies{$scheme});
2611 eval q{use LWPx::ParanoidAgent};
2613 print STDERR "warning: installing LWPx::ParanoidAgent is recommended\n";
2614 return LWP::UserAgent->new(%args);
2616 return LWPx::ParanoidAgent->new(%args);
2619 sub sortspec_translate ($$) {
2621 my $reverse = shift;
2627 (-?) # group 1: perhaps negated
2630 \w+\([^\)]*\) # command(params)
2632 [^\s]+ # or anything else
2640 if ($word =~ m/^(\w+)\((.*)\)$/) {
2641 # command with parameters
2645 elsif ($word !~ m/^\w+$/) {
2646 error(sprintf(gettext("invalid sort type %s"), $word));
2657 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2658 if (defined $params) {
2659 push @data, $params;
2660 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2663 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2667 error(sprintf(gettext("unknown sort type %s"), $word));
2671 if (! length $code) {
2672 # undefined sorting method... sort arbitrarily
2681 return eval 'sub { '.$code.' }';
2684 sub pagespec_translate ($) {
2687 # Convert spec to perl code.
2691 \s* # ignore whitespace
2692 ( # 1: match a single word
2699 \w+\([^\)]*\) # command(params)
2701 [^\s()]+ # any other text
2703 \s* # ignore whitespace
2706 if (lc $word eq 'and') {
2709 elsif (lc $word eq 'or') {
2712 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2715 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2716 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2718 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2721 push @data, qq{unknown function in pagespec "$word"};
2722 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2727 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2731 if (! length $code) {
2732 $code="IkiWiki::FailReason->new('empty pagespec')";
2736 return eval 'sub { my $page=shift; '.$code.' }';
2739 sub pagespec_match ($$;@) {
2744 # Backwards compatability with old calling convention.
2746 unshift @params, 'location';
2749 my $sub=pagespec_translate($spec);
2750 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2752 return $sub->($page, @params);
2755 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2757 # Not exported yet, but could be in future if it is generally useful.
2758 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2759 # which is "more internal".
2760 sub sort_pages ($$;@) {
2764 $sort = sortspec_translate($sort, $params{reverse});
2765 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2768 sub pagespec_match_list ($$;@) {
2773 # Backwards compatability with old calling convention.
2775 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2776 $params{list}=$page;
2777 $page=$params{location}; # ugh!
2780 my $sub=pagespec_translate($pagespec);
2781 error "syntax error in pagespec \"$pagespec\""
2783 my $sort=sortspec_translate($params{sort}, $params{reverse})
2784 if defined $params{sort};
2787 if (exists $params{list}) {
2788 @candidates=exists $params{filter}
2789 ? grep { ! $params{filter}->($_) } @{$params{list}}
2793 @candidates=exists $params{filter}
2794 ? grep { ! $params{filter}->($_) } keys %pagesources
2795 : keys %pagesources;
2798 # clear params, remainder is passed to pagespec
2799 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2800 my $num=$params{num};
2801 delete @params{qw{num deptype reverse sort filter list}};
2803 # when only the top matches will be returned, it's efficient to
2804 # sort before matching to pagespec,
2805 if (defined $num && defined $sort) {
2806 @candidates=IkiWiki::SortSpec::sort_pages(
2807 $sort, @candidates);
2813 my $accum=IkiWiki::SuccessReason->new();
2814 foreach my $p (@candidates) {
2815 my $r=$sub->($p, %params, location => $page);
2816 error(sprintf(gettext("cannot match pages: %s"), $r))
2817 if $r->isa("IkiWiki::ErrorReason");
2818 unless ($r || $r->influences_static) {
2819 $r->remove_influence($p);
2824 last if defined $num && ++$count == $num;
2828 # Add simple dependencies for accumulated influences.
2829 my $i=$accum->influences;
2830 foreach my $k (keys %$i) {
2831 $depends_simple{$page}{lc $k} |= $i->{$k};
2834 # when all matches will be returned, it's efficient to
2835 # sort after matching
2836 if (! defined $num && defined $sort) {
2837 return IkiWiki::SortSpec::sort_pages(
2845 sub pagespec_valid ($) {
2848 return defined pagespec_translate($spec);
2852 my $re=quotemeta(shift);
2858 package IkiWiki::FailReason;
2861 '""' => sub { $_[0][0] },
2863 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2864 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2865 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2869 our @ISA = 'IkiWiki::SuccessReason';
2871 package IkiWiki::SuccessReason;
2873 # A blessed array-ref:
2875 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2877 # - if absent or false, the influences of this evaluation are "static",
2878 # see the influences_static method
2879 # - if true, they are dynamic (not static)
2880 # [1]{any other key}:
2881 # the dependency types of influences, as returned by the influences method
2884 # in string context, it's the human-readable reason
2885 '""' => sub { $_[0][0] },
2886 # in boolean context, SuccessReason is 1 and FailReason is 0
2888 # negating a result gives the opposite result with the same influences
2889 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2890 # A & B = (A ? B : A) with the influences of both
2891 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2892 # A | B = (A ? A : B) with the influences of both
2893 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2897 # SuccessReason->new("human-readable reason", page => deptype, ...)
2902 return bless [$value, {@_}], $class;
2905 # influences(): return a reference to a copy of the hash
2906 # { page => dependency type } describing the pages that indirectly influenced
2907 # this result, but would not cause a dependency through ikiwiki's core
2910 # See [[todo/dependency_types]] for extensive discussion of what this means.
2912 # influences(page => deptype, ...): remove all influences, replace them
2913 # with the arguments, and return a reference to a copy of the new influences.
2917 $this->[1]={@_} if @_;
2918 my %i=%{$this->[1]};
2923 # True if this result has the same influences whichever page it matches,
2924 # For instance, whether bar matches backlink(foo) is influenced only by
2925 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2926 # which does not mention bar anywhere.
2928 # False if this result would have different influences when matching
2929 # different pages. For instance, when testing whether link(foo) matches bar,
2930 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2931 # bar's links could change the outcome; so its influences are not the same
2932 # as when testing whether link(foo) matches baz.
2934 # Static influences are one of the things that make pagespec_match_list
2935 # more efficient than repeated calls to pagespec_match.
2937 sub influences_static {
2938 return ! $_[0][1]->{""};
2941 # Change the influences of $this to be the influences of "$this & $other"
2942 # or "$this | $other".
2944 # If both $this and $other are either successful or have influences,
2945 # or this is an "or" operation, the result has all the influences from
2946 # either of the arguments. It has dynamic influences if either argument
2947 # has dynamic influences.
2949 # If this is an "and" operation, and at least one argument is a
2950 # FailReason with no influences, the result has no influences, and they
2951 # are not dynamic. For instance, link(foo) matching bar is influenced
2952 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2953 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2954 # bar, because it would be false however often you edit bar.
2956 sub merge_influences {
2961 # This "if" is odd because it needs to avoid negating $this
2962 # or $other, which would alter the objects in-place. Be careful.
2963 if (! $anded || (($this || %{$this->[1]}) &&
2964 ($other || %{$other->[1]}))) {
2965 foreach my $influence (keys %{$other->[1]}) {
2966 $this->[1]{$influence} |= $other->[1]{$influence};
2975 # Change $this so it is not considered to be influenced by $torm.
2977 sub remove_influence {
2981 delete $this->[1]{$torm};
2984 package IkiWiki::ErrorReason;
2986 our @ISA = 'IkiWiki::FailReason';
2988 package IkiWiki::PageSpec;
2994 if ($path =~ m!^\.(/|$)!) {
2996 $from=~s#/?[^/]+$## if defined $from;
2998 $path="$from/$path" if defined $from && length $from;
3002 $path = "" unless defined $path;
3011 sub match_glob ($$;@) {
3016 $glob=derel($glob, $params{location});
3018 # Instead of converting the glob to a regex every time,
3019 # cache the compiled regex to save time.
3020 my $re=$glob_cache{$glob};
3021 unless (defined $re) {
3022 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
3025 if (! IkiWiki::isinternal($page) || $params{internal}) {
3026 return IkiWiki::SuccessReason->new("$glob matches $page");
3029 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
3033 return IkiWiki::FailReason->new("$glob does not match $page");
3037 sub match_internal ($$;@) {
3038 return match_glob(shift, shift, @_, internal => 1)
3041 sub match_page ($$;@) {
3043 my $match=match_glob($page, shift, @_);
3045 my $source=exists $IkiWiki::pagesources{$page} ?
3046 $IkiWiki::pagesources{$page} :
3047 $IkiWiki::delpagesources{$page};
3048 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
3049 if (! defined $type) {
3050 return IkiWiki::FailReason->new("$page is not a page");
3056 sub match_link ($$;@) {
3061 $link=derel($link, $params{location});
3062 my $from=exists $params{location} ? $params{location} : '';
3063 my $linktype=$params{linktype};
3065 if (defined $linktype) {
3066 $qualifier=" with type $linktype";
3069 my $links = $IkiWiki::links{$page};
3070 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
3071 unless $links && @{$links};
3072 my $bestlink = IkiWiki::bestlink($from, $link);
3073 foreach my $p (@{$links}) {
3074 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
3076 if (length $bestlink) {
3077 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
3078 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
3082 if (match_glob($p, $link, %params)) {
3083 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
3085 my ($p_rel)=$p=~/^\/?(.*)/;
3087 if (match_glob($p_rel, $link, %params)) {
3088 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
3092 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
3095 sub match_backlink ($$;@) {
3099 if ($testpage eq '.') {
3100 $testpage = $params{'location'}
3102 my $ret=match_link($testpage, $page, @_);
3103 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
3107 sub match_created_before ($$;@) {
3112 $testpage=derel($testpage, $params{location});
3114 if (exists $IkiWiki::pagectime{$testpage}) {
3115 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
3116 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3119 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3123 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
3127 sub match_created_after ($$;@) {
3132 $testpage=derel($testpage, $params{location});
3134 if (exists $IkiWiki::pagectime{$testpage}) {
3135 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
3136 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3139 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
3143 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
3147 sub match_creation_day ($$;@) {
3150 if ($d !~ /^\d+$/) {
3151 return IkiWiki::ErrorReason->new("invalid day $d");
3153 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
3154 return IkiWiki::SuccessReason->new('creation_day matched');
3157 return IkiWiki::FailReason->new('creation_day did not match');
3161 sub match_creation_month ($$;@) {
3164 if ($m !~ /^\d+$/) {
3165 return IkiWiki::ErrorReason->new("invalid month $m");
3167 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
3168 return IkiWiki::SuccessReason->new('creation_month matched');
3171 return IkiWiki::FailReason->new('creation_month did not match');
3175 sub match_creation_year ($$;@) {
3178 if ($y !~ /^\d+$/) {
3179 return IkiWiki::ErrorReason->new("invalid year $y");
3181 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
3182 return IkiWiki::SuccessReason->new('creation_year matched');
3185 return IkiWiki::FailReason->new('creation_year did not match');
3189 sub match_user ($$;@) {
3194 if (! exists $params{user}) {
3195 return IkiWiki::ErrorReason->new("no user specified");
3198 my $regexp=IkiWiki::glob2re($user);
3200 if (defined $params{user} && $params{user}=~$regexp) {
3201 return IkiWiki::SuccessReason->new("user is $user");
3203 elsif (! defined $params{user}) {
3204 return IkiWiki::FailReason->new("not logged in");
3207 return IkiWiki::FailReason->new("user is $params{user}, not $user");
3211 sub match_admin ($$;@) {
3216 if (! exists $params{user}) {
3217 return IkiWiki::ErrorReason->new("no user specified");
3220 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3221 return IkiWiki::SuccessReason->new("user is an admin");
3223 elsif (! defined $params{user}) {
3224 return IkiWiki::FailReason->new("not logged in");
3227 return IkiWiki::FailReason->new("user is not an admin");
3231 sub match_ip ($$;@) {
3236 if (! exists $params{ip}) {
3237 return IkiWiki::ErrorReason->new("no IP specified");
3240 my $regexp=IkiWiki::glob2re(lc $ip);
3242 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3243 return IkiWiki::SuccessReason->new("IP is $ip");
3246 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3250 package IkiWiki::SortSpec;
3252 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3253 # are easily available in this namespace, for cmp functions to use them.
3260 IkiWiki::pagetitle(IkiWiki::basename($a))
3262 IkiWiki::pagetitle(IkiWiki::basename($b))
3265 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3266 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3267 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }