9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %wikistate %renderedfiles %oldrenderedfiles
16 %pagesources %delpagesources %destsources %depends %depends_simple
17 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
18 %oldtypedlinks %autofiles @underlayfiles $lastrev $phase};
20 use Exporter q{import};
21 our @EXPORT = qw(hook debug error htmlpage template template_depends
22 deptype add_depends pagespec_match pagespec_match_list bestlink
23 htmllink readfile writefile pagetype srcfile pagename
24 displaytime strftime_utf8 will_render gettext ngettext urlto targetpage
25 add_underlay pagetitle titlepage linkpage newpagefile
26 inject add_link add_autofile useragent
27 %config %links %pagestate %wikistate %renderedfiles
28 %pagesources %destsources %typedlinks);
29 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
30 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
31 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
33 # Page dependency types.
34 our $DEPEND_CONTENT=1;
35 our $DEPEND_PRESENCE=2;
38 # Phases of processing.
39 sub PHASE_SCAN () { 0 }
40 sub PHASE_RENDER () { 1 }
46 memoize("sortspec_translate");
47 memoize("pagespec_translate");
48 memoize("template_file");
54 description => "name of the wiki",
61 example => 'me@example.com',
62 description => "contact email for wiki",
69 description => "users who are wiki admins",
76 description => "users who are banned from the wiki",
83 example => "$ENV{HOME}/wiki",
84 description => "where the source of the wiki is located",
91 example => "/var/www/wiki",
92 description => "where to build the wiki",
99 example => "http://example.com/wiki",
100 description => "base url to the wiki",
107 example => "http://example.com/wiki/ikiwiki.cgi",
108 description => "url to the ikiwiki.cgi",
115 description => "do not adjust cgiurl if CGI is accessed via different URL",
118 rebuild => 0, # only affects CGI requests
123 example => "/var/www/wiki/ikiwiki.cgi",
124 description => "filename of cgi wrapper to generate",
131 description => "mode for cgi_wrapper (can safely be made suid)",
135 cgi_overload_delay => {
139 description => "number of seconds to delay CGI requests when overloaded",
143 cgi_overload_message => {
146 example => "Please wait",
147 description => "message to display when overloaded (may contain html)",
151 only_committed_changes => {
154 description => "enable optimization of only refreshing committed changes?",
161 description => "rcs backend to use",
162 safe => 0, # don't allow overriding
167 default => [qw{mdwn link inline meta htmlscrubber passwordauth
168 openid signinedit lockedit conditional
169 recentchanges parentlinks editpage
171 description => "plugins to enable by default",
178 description => "plugins to add to the default configuration",
185 description => "plugins to disable",
191 default => "$installdir/share/ikiwiki/templates",
192 description => "additional directory to search for template files",
199 default => "$installdir/share/ikiwiki/basewiki",
200 description => "base wiki source location",
207 default => "$installdir/share/ikiwiki",
208 description => "parent directory containing additional underlays",
215 description => "wrappers to generate",
222 description => "additional underlays to use",
229 description => "display verbose messages?",
236 description => "log to syslog?",
243 description => "create output files named page/index.html?",
244 safe => 0, # changing requires manual transition
247 prefix_directives => {
250 description => "use '!'-prefixed preprocessor directives?",
251 safe => 0, # changing requires manual transition
257 description => "use page/index.mdwn source files",
264 description => "enable Discussion pages?",
270 default => gettext("Discussion"),
271 description => "name of Discussion pages",
278 description => "use elements new in HTML5 like <section>?",
286 description => "only send cookies over SSL connections?",
294 description => "extension to use for new pages",
295 safe => 0, # not sanitized
301 description => "extension to use for html files",
302 safe => 0, # not sanitized
308 description => "strftime format string to display date",
316 example => "en_US.UTF-8",
317 description => "UTF-8 locale to use",
326 description => "put user pages below specified page",
333 description => "how many backlinks to show before hiding excess (0 to show all)",
340 description => "attempt to hardlink source files? (optimisation for large files)",
342 safe => 0, # paranoia
348 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
350 safe => 0, # paranoia
355 example => "ikiwiki",
356 description => "group for wrappers to run in",
358 safe => 0, # paranoia
364 example => ["$ENV{HOME}/.local/share/ikiwiki"],
365 description => "extra library and plugin directories",
367 safe => 0, # directory
373 example => "$ENV{HOME}/.ikiwiki/",
374 description => "extra library and plugin directory (searched after libdirs)",
376 safe => 0, # directory
382 description => "environment variables",
383 safe => 0, # paranoia
389 example => "US/Eastern",
390 description => "time zone name",
397 example => '^\.htaccess$',
398 description => "regexp of normally excluded files to include",
406 example => '^(*\.private|Makefile)$',
407 description => "regexp of files that should be skipped",
412 wiki_file_prune_regexps => {
414 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
415 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
416 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
417 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
418 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
419 description => "regexps of source files to ignore",
425 description => "specifies the characters that are allowed in source filenames",
426 default => "-[:alnum:]+/.:_",
430 wiki_file_regexp => {
432 description => "regexp of legal source files",
436 web_commit_regexp => {
438 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
439 description => "regexp to parse web commits from logs",
446 description => "run as a cgi",
450 cgi_disable_uploads => {
453 description => "whether CGI should accept file uploads",
460 description => "run as a post-commit hook",
467 description => "running in rebuild mode",
474 description => "running in setup mode",
481 description => "running in clean mode",
488 description => "running in refresh mode",
495 description => "running in receive test mode",
499 wrapper_background_command => {
502 description => "background shell command to run",
508 description => "running in gettime mode",
515 description => "running in w3mmode",
522 description => "path to the .ikiwiki directory holding ikiwiki state",
529 description => "path to setup file",
536 description => "perl class to use to dump setup file",
540 allow_symlinks_before_srcdir => {
543 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
549 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
550 description => "cookie control",
551 safe => 0, # hooks into perl module internals
556 default => "ikiwiki/$version",
557 example => "Wget/1.13.4 (linux-gnu)",
558 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
562 responsive_layout => {
565 description => "theme has a responsive layout? (mobile-optimized)",
573 if ($config{libdirs}) {
574 @libdirs = @{$config{libdirs}};
576 if (length $config{libdir}) {
577 push @libdirs, $config{libdir};
582 sub defaultconfig () {
585 foreach my $key (keys %s) {
586 push @ret, $key, $s{$key}->{default};
591 # URL to top of wiki as a path starting with /, valid from any wiki page or
592 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
594 # URL to CGI script, similar to $local_url
598 # locale stuff; avoid LC_ALL since it overrides everything
599 if (defined $ENV{LC_ALL}) {
600 $ENV{LANG} = $ENV{LC_ALL};
603 if (defined $config{locale}) {
604 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
605 $ENV{LANG}=$config{locale};
610 if (! defined $config{wiki_file_regexp}) {
611 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
614 if (ref $config{ENV} eq 'HASH') {
615 foreach my $val (keys %{$config{ENV}}) {
616 $ENV{$val}=$config{ENV}{$val};
619 if (defined $config{timezone} && length $config{timezone}) {
620 $ENV{TZ}=$config{timezone};
622 elsif (defined $ENV{TZ} && length $ENV{TZ}) {
623 $config{timezone}=$ENV{TZ};
626 eval q{use Config qw()};
629 if ($Config::Config{d_gnulibc} && -e '/etc/localtime') {
630 $config{timezone}=$ENV{TZ}=':/etc/localtime';
633 $config{timezone}=$ENV{TZ}='GMT';
637 if ($config{w3mmode}) {
638 eval q{use Cwd q{abs_path}};
640 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
641 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
642 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
643 unless $config{cgiurl} =~ m!file:///!;
644 $config{url}="file://".$config{destdir};
647 if ($config{cgi} && ! length $config{url}) {
648 error(gettext("Must specify url to wiki with --url when using --cgi"));
651 if (defined $config{url} && length $config{url}) {
653 my $baseurl = URI->new($config{url});
655 $local_url = $baseurl->path . "/";
656 $local_cgiurl = undef;
658 if (length $config{cgiurl}) {
659 my $cgiurl = URI->new($config{cgiurl});
661 $local_cgiurl = $cgiurl->path;
663 if ($cgiurl->scheme eq 'https' &&
664 $baseurl->scheme eq 'http') {
665 # We assume that the same content is available
666 # over both http and https, because if it
667 # wasn't, accessing the static content
668 # from the CGI would be mixed-content,
669 # which would be a security flaw.
671 if ($cgiurl->authority ne $baseurl->authority) {
672 # use protocol-relative URL for
674 $local_url = "$config{url}/";
675 $local_url =~ s{^http://}{//};
677 # else use host-relative URL for static content
679 # either way, CGI needs to be absolute
680 $local_cgiurl = $config{cgiurl};
682 elsif ($cgiurl->scheme ne $baseurl->scheme) {
683 # too far apart, fall back to absolute URLs
684 $local_url = "$config{url}/";
685 $local_cgiurl = $config{cgiurl};
687 elsif ($cgiurl->authority ne $baseurl->authority) {
688 # slightly too far apart, fall back to
689 # protocol-relative URLs
690 $local_url = "$config{url}/";
691 $local_url =~ s{^https?://}{//};
692 $local_cgiurl = $config{cgiurl};
693 $local_cgiurl =~ s{^https?://}{//};
695 # else keep host-relative URLs
698 $local_url =~ s{//$}{/};
701 $local_cgiurl = $config{cgiurl};
704 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
705 unless exists $config{wikistatedir} && defined $config{wikistatedir};
707 if (defined $config{umask}) {
708 my $u = possibly_foolish_untaint($config{umask});
710 if ($u =~ m/^\d+$/) {
713 elsif ($u eq 'private') {
716 elsif ($u eq 'group') {
719 elsif ($u eq 'public') {
723 error(sprintf(gettext("unsupported umask setting %s"), $u));
727 run_hooks(checkconfig => sub { shift->() });
735 foreach my $dir (@INC, getlibdirs()) {
736 next unless defined $dir && length $dir;
737 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
738 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
742 foreach my $dir (getlibdirs(), "$installdir/lib/ikiwiki") {
743 next unless defined $dir && length $dir;
744 foreach my $file (glob("$dir/plugins/*")) {
745 $ret{basename($file)}=1 if -x $file;
753 foreach my $dir (getlibdirs()) {
754 unshift @INC, possibly_foolish_untaint($dir);
757 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
762 if (exists $hooks{rcs}) {
763 error(gettext("cannot use multiple rcs plugins"));
765 loadplugin($config{rcs});
767 if (! exists $hooks{rcs}) {
771 run_hooks(getopt => sub { shift->() });
772 if (grep /^-/, @ARGV) {
773 print STDERR "Unknown option (or missing parameter): $_\n"
774 foreach grep /^-/, @ARGV;
781 sub loadplugin ($;$) {
785 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
787 foreach my $possiblytainteddir (getlibdirs(), "$installdir/lib/ikiwiki") {
788 my $dir = possibly_foolish_untaint($possiblytainteddir);
789 if (defined $dir && -x "$dir/plugins/$plugin") {
790 eval { require IkiWiki::Plugin::external };
793 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
795 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
796 $loaded_plugins{$plugin}=1;
801 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
804 error("Failed to load plugin $mod: $@");
806 $loaded_plugins{$plugin}=1;
813 log_message('err' => $message) if $config{syslog};
814 if (defined $cleaner) {
821 return unless $config{verbose};
822 return log_message(debug => @_);
827 sub log_message ($$) {
830 if ($config{syslog}) {
833 Sys::Syslog::setlogsock('unix');
834 Sys::Syslog::openlog('ikiwiki', '', 'user');
838 # keep a copy to avoid editing the original config repeatedly
839 my $wikiname = $config{wikiname};
840 utf8::encode($wikiname);
841 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
844 print STDERR "failed to syslog: $@" unless $log_failed;
850 elsif (! $config{cgi}) {
854 return print STDERR "@_\n";
858 sub possibly_foolish_untaint ($) {
860 my ($untainted)=$tainted=~/(.*)/s;
880 return exists $pagesources{$page} &&
881 $pagesources{$page} =~ /\._([^.]+)$/;
887 if ($file =~ /\.([^.]+)$/) {
888 return $1 if exists $hooks{htmlize}{$1};
890 my $base=basename($file);
891 if (exists $hooks{htmlize}{$base} &&
892 $hooks{htmlize}{$base}{noextension}) {
903 if (exists $pagename_cache{$file}) {
904 return $pagename_cache{$file};
907 my $type=pagetype($file);
909 $page=~s/\Q.$type\E*$//
910 if defined $type && !$hooks{htmlize}{$type}{keepextension}
911 && !$hooks{htmlize}{$type}{noextension};
912 if ($config{indexpages} && $page=~/(.*)\/index$/) {
916 $pagename_cache{$file} = $page;
920 sub newpagefile ($$) {
924 if (! $config{indexpages} || $page eq 'index') {
925 return $page.".".$type;
928 return $page."/index.".$type;
932 sub targetpage ($$;$) {
937 if (defined $filename) {
938 return $page."/".$filename.".".$ext;
940 elsif (! $config{usedirs} || $page eq 'index') {
941 return $page.".".$ext;
944 return $page."/index.".$ext;
951 return targetpage($page, $config{htmlext});
958 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
959 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
960 return "$dir/$file", stat(_) if -e "$dir/$file";
962 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
967 return (srcfile_stat(@_))[0];
970 sub add_literal_underlay ($) {
973 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
974 unshift @{$config{underlaydirs}}, $dir;
978 sub add_underlay ($) {
982 $dir="$config{underlaydirbase}/$dir";
985 add_literal_underlay($dir);
986 # why does it return 1? we just don't know
990 sub readfile ($;$$) {
996 error("cannot read a symlink ($file)");
1000 open (my $in, "<", $file) || error("failed to read $file: $!");
1001 binmode($in) if ($binary);
1002 return \*$in if $wantfd;
1004 # check for invalid utf-8, and toss it back to avoid crashes
1005 if (! utf8::valid($ret)) {
1006 $ret=encode_utf8($ret);
1008 close $in || error("failed to read $file: $!");
1012 sub prep_writefile ($$) {
1017 while (length $test) {
1018 if (-l "$destdir/$test") {
1019 error("cannot write to a symlink ($test)");
1021 if (-f _ && $test ne $file) {
1022 # Remove conflicting file.
1023 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1024 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1026 unlink("$destdir/$test");
1032 $test=dirname($test);
1035 my $dir=dirname("$destdir/$file");
1038 foreach my $s (split(m!/+!, $dir)) {
1041 mkdir($d) || error("failed to create directory $d: $!");
1049 sub writefile ($$$;$$) {
1050 my $file=shift; # can include subdirs
1051 my $destdir=shift; # directory to put file in
1056 prep_writefile($file, $destdir);
1058 my $newfile="$destdir/$file.ikiwiki-new";
1060 error("cannot write to a symlink ($newfile)");
1063 my $cleanup = sub { unlink($newfile) };
1064 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1065 binmode($out) if ($binary);
1067 $writer->(\*$out, $cleanup);
1070 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1072 close $out || error("failed saving $newfile: $!", $cleanup);
1073 rename($newfile, "$destdir/$file") ||
1074 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1080 sub will_render ($$;$) {
1085 # Important security check for independently created files.
1086 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1087 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1088 my $from_other_page=0;
1089 # Expensive, but rarely runs.
1090 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1093 dirname($_) eq $dest
1094 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1100 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1101 unless $from_other_page;
1104 # If $dest exists as a directory, remove conflicting files in it
1105 # rendered from other pages.
1107 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1108 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1109 if (dirname($f) eq $dest) {
1110 unlink("$config{destdir}/$f");
1111 rmdir(dirname("$config{destdir}/$f"));
1117 if (! $clear || $cleared{$page}) {
1118 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1121 foreach my $old (@{$renderedfiles{$page}}) {
1122 delete $destsources{$old};
1124 $renderedfiles{$page}=[$dest];
1127 $destsources{$dest}=$page;
1137 if ($link=~s/^\/+//) {
1145 $l.="/" if length $l;
1148 if (exists $pagesources{$l}) {
1151 elsif (exists $pagecase{lc $l}) {
1152 return $pagecase{lc $l};
1154 } while $cwd=~s{/?[^/]+$}{};
1156 if (length $config{userdir}) {
1157 my $l = "$config{userdir}/".lc($link);
1158 if (exists $pagesources{$l}) {
1161 elsif (exists $pagecase{lc $l}) {
1162 return $pagecase{lc $l};
1166 #print STDERR "warning: page $page, broken link: $link\n";
1170 sub isinlinableimage ($) {
1173 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1176 sub pagetitle ($;$) {
1178 my $unescaped=shift;
1181 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1184 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1192 # support use w/o %config set
1193 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1194 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1200 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1201 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1208 my $cgiurl=$local_cgiurl;
1210 if (exists $params{cgiurl}) {
1211 $cgiurl=$params{cgiurl};
1212 delete $params{cgiurl};
1220 join("&", map $_."=".uri_escape_utf8($params{$_}), sort(keys %params));
1223 sub cgiurl_abs (@) {
1225 URI->new_abs(cgiurl(@_), $config{cgiurl});
1231 return $local_url if ! defined $page;
1233 $page=htmlpage($page);
1235 $page=~s/[^\/]+\//..\//g;
1243 return $url unless defined $urlbase && length $urlbase;
1246 URI->new_abs($url, $urlbase)->as_string;
1250 # Work around very innefficient behavior in File::Spec if abs2rel
1251 # is passed two relative paths. It's much faster if paths are
1252 # absolute! (Debian bug #376658; fixed in debian unstable now)
1257 my $ret=File::Spec->abs2rel($path, $base);
1258 $ret=~s/^// if defined $ret;
1262 sub displaytime ($;$$) {
1263 # Plugins can override this function to mark up the time to
1265 my $time=formattime($_[0], $_[1]);
1266 if ($config{html5}) {
1267 return '<time datetime="'.date_3339($_[0]).'"'.
1268 ($_[2] ? ' pubdate="pubdate"' : '').
1269 '>'.$time.'</time>';
1272 return '<span class="date">'.$time.'</span>';
1276 sub formattime ($;$) {
1277 # Plugins can override this function to format the time.
1280 if (! defined $format) {
1281 $format=$config{timeformat};
1284 return strftime_utf8($format, localtime($time));
1287 my $strftime_encoding;
1289 # strftime doesn't know about encodings, so make sure
1290 # its output is properly treated as utf8.
1291 # Note that this does not handle utf-8 in the format string.
1292 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1293 unless defined $strftime_encoding;
1295 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1296 : POSIX::strftime(@_);
1302 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1303 POSIX::setlocale(&POSIX::LC_TIME, "C");
1304 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1305 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1309 sub beautify_urlpath ($) {
1312 # Ensure url is not an empty link, and if necessary,
1313 # add ./ to avoid colon confusion.
1314 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1318 if ($config{usedirs}) {
1319 $url =~ s!/index.$config{htmlext}$!/!;
1334 if (! $destsources{$to}) {
1339 return $config{url}.beautify_urlpath("/".$to);
1342 if (! defined $from) {
1343 my $u = $local_url || '';
1345 return $u.beautify_urlpath("/".$to);
1348 my $link = abs2rel($to, dirname(htmlpage($from)));
1350 return beautify_urlpath($link);
1353 sub isselflink ($$) {
1354 # Plugins can override this function to support special types
1359 return $page eq $link;
1362 sub htmllink ($$$;@) {
1363 my $lpage=shift; # the page doing the linking
1364 my $page=shift; # the page that will contain the link (different for inline)
1371 if (! $opts{forcesubpage}) {
1372 $bestlink=bestlink($lpage, $link);
1375 $bestlink="$lpage/".lc($link);
1379 if (defined $opts{linktext}) {
1380 $linktext=$opts{linktext};
1383 $linktext=pagetitle(basename($link));
1386 return "<span class=\"selflink\">$linktext</span>"
1387 if length $bestlink && isselflink($page, $bestlink) &&
1388 ! defined $opts{anchor};
1390 if (! $destsources{$bestlink}) {
1391 $bestlink=htmlpage($bestlink);
1393 if (! $destsources{$bestlink}) {
1395 if (length $config{cgiurl}) {
1396 $cgilink = "<a href=\"".
1401 )."\" rel=\"nofollow\">?</a>";
1403 return "<span class=\"createlink\">$cgilink$linktext</span>"
1407 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1408 $bestlink=beautify_urlpath($bestlink);
1410 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1411 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1414 if (defined $opts{anchor}) {
1415 $bestlink.="#".$opts{anchor};
1419 foreach my $attr (qw{rel class title}) {
1420 if (defined $opts{$attr}) {
1421 push @attrs, " $attr=\"$opts{$attr}\"";
1425 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1430 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1433 # Username to display for openid accounts.
1434 sub openiduser ($) {
1437 if (defined $user && $user =~ m!^https?://! &&
1438 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1441 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1442 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1445 # backcompat with old version
1446 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1447 $display=$oid->display;
1450 # Convert "user.somehost.com" to "user [somehost.com]"
1451 # (also "user.somehost.co.uk")
1452 if ($display !~ /\[/) {
1453 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1455 # Convert "http://somehost.com/user" to "user [somehost.com]".
1456 # (also "https://somehost.com/user/")
1457 if ($display !~ /\[/) {
1458 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1460 $display=~s!^https?://!!; # make sure this is removed
1461 eval q{use CGI 'escapeHTML'};
1463 return escapeHTML($display);
1468 # Username to display for emailauth accounts.
1471 if (defined $user && $user =~ m/(.+)@/) {
1473 # remove any characters from not allowed in wiki files
1474 # support use w/o %config set
1475 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1476 $nick=~s/[^$chars]/_/g;
1482 # Some user information should not be exposed in commit metadata, etc.
1483 # This generates a cloaked form of such information.
1486 # cloak email address using http://xmlns.com/foaf/spec/#term_mbox_sha1sum
1487 if ($user=~m/(.+)@/) {
1489 eval q{use Digest::SHA};
1491 return $nick.'@'.Digest::SHA::sha1_hex("mailto:$user");
1498 sub htmlize ($$$$) {
1504 my $oneline = $content !~ /\n/;
1506 if (exists $hooks{htmlize}{$type}) {
1507 $content=$hooks{htmlize}{$type}{call}->(
1509 content => $content,
1513 error("htmlization of $type not supported");
1516 run_hooks(sanitize => sub {
1519 destpage => $destpage,
1520 content => $content,
1525 # hack to get rid of enclosing junk added by markdown
1526 # and other htmlizers/sanitizers
1527 $content=~s/^<p>//i;
1528 $content=~s/<\/p>\n*$//i;
1539 run_hooks(linkify => sub {
1542 destpage => $destpage,
1543 content => $content,
1551 our $preprocess_preview=0;
1552 sub preprocess ($$$;$$) {
1553 my $page=shift; # the page the data comes from
1554 my $destpage=shift; # the page the data will appear in (different for inline)
1559 # Using local because it needs to be set within any nested calls
1561 local $preprocess_preview=$preview if defined $preview;
1568 $params="" if ! defined $params;
1570 if (length $escape) {
1571 return "[[$prefix$command $params]]";
1573 elsif (exists $hooks{preprocess}{$command}) {
1574 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1575 # Note: preserve order of params, some plugins may
1576 # consider it significant.
1578 while ($params =~ m{
1579 (?:([-.\w]+)=)? # 1: named parameter key?
1581 """(.*?)""" # 2: triple-quoted value
1583 "([^"]*?)" # 3: single-quoted value
1585 '''(.*?)''' # 4: triple-single-quote
1587 <<([a-zA-Z]+)\n # 5: heredoc start
1588 (.*?)\n\5 # 6: heredoc value
1590 (\S+) # 7: unquoted value
1592 (?:\s+|$) # delimiter to next param
1602 elsif (defined $3) {
1605 elsif (defined $4) {
1608 elsif (defined $7) {
1611 elsif (defined $6) {
1616 push @params, $key, $val;
1619 push @params, $val, '';
1622 if ($preprocessing{$page}++ > 8) {
1623 # Avoid loops of preprocessed pages preprocessing
1624 # other pages that preprocess them, etc.
1625 return "[[!$command <span class=\"error\">".
1626 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1627 $page, $preprocessing{$page}).
1633 $hooks{preprocess}{$command}{call}->(
1636 destpage => $destpage,
1637 preview => $preprocess_preview,
1643 $ret="[[!$command <span class=\"error\">".
1644 gettext("Error").": $error"."</span>]]";
1648 # use void context during scan pass
1650 $hooks{preprocess}{$command}{call}->(
1653 destpage => $destpage,
1654 preview => $preprocess_preview,
1659 $preprocessing{$page}--;
1663 return "[[$prefix$command $params]]";
1668 if ($config{prefix_directives}) {
1671 \[\[(!) # directive open; 2: prefix
1672 ([-\w]+) # 3: command
1673 ( # 4: the parameters..
1674 \s+ # Must have space if parameters present
1676 (?:[-.\w]+=)? # named parameter key?
1678 """.*?""" # triple-quoted value
1680 "[^"]*?" # single-quoted value
1682 '''.*?''' # triple-single-quote
1684 <<([a-zA-Z]+)\n # 5: heredoc start
1685 (?:.*?)\n\5 # heredoc value
1687 [^"\s\]]+ # unquoted value
1689 \s* # whitespace or end
1692 *)? # 0 or more parameters
1693 \]\] # directive closed
1699 \[\[(!?) # directive open; 2: optional prefix
1700 ([-\w]+) # 3: command
1702 ( # 4: the parameters..
1704 (?:[-.\w]+=)? # named parameter key?
1706 """.*?""" # triple-quoted value
1708 "[^"]*?" # single-quoted value
1710 '''.*?''' # triple-single-quote
1712 <<([a-zA-Z]+)\n # 5: heredoc start
1713 (?:.*?)\n\5 # heredoc value
1715 [^"\s\]]+ # unquoted value
1717 \s* # whitespace or end
1720 *) # 0 or more parameters
1721 \]\] # directive closed
1725 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1734 run_hooks(filter => sub {
1735 $content=shift->(page => $page, destpage => $destpage,
1736 content => $content);
1742 sub check_canedit ($$$;$) {
1749 run_hooks(canedit => sub {
1750 return if defined $canedit;
1751 my $ret=shift->($page, $q, $session);
1756 elsif (ref $ret eq 'CODE') {
1757 $ret->() unless $nonfatal;
1760 elsif (defined $ret) {
1761 error($ret) unless $nonfatal;
1766 return defined $canedit ? $canedit : 1;
1769 sub check_content (@) {
1772 return 1 if ! exists $hooks{checkcontent}; # optimisation
1774 if (exists $pagesources{$params{page}}) {
1776 my %old=map { $_ => 1 }
1777 split("\n", readfile(srcfile($pagesources{$params{page}})));
1778 foreach my $line (split("\n", $params{content})) {
1779 push @diff, $line if ! exists $old{$line};
1781 $params{diff}=join("\n", @diff);
1785 run_hooks(checkcontent => sub {
1786 return if defined $ok;
1787 my $ret=shift->(%params);
1792 elsif (ref $ret eq 'CODE') {
1793 $ret->() unless $params{nonfatal};
1796 elsif (defined $ret) {
1797 error($ret) unless $params{nonfatal};
1803 return defined $ok ? $ok : 1;
1806 sub check_canchange (@) {
1808 my $cgi = $params{cgi};
1809 my $session = $params{session};
1810 my @changes = @{$params{changes}};
1813 foreach my $change (@changes) {
1814 # This untaint is safe because we check file_pruned and
1816 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1817 $file=possibly_foolish_untaint($file);
1818 if (! defined $file || ! length $file ||
1819 file_pruned($file)) {
1820 error(gettext("bad file name %s"), $file);
1823 my $type=pagetype($file);
1824 my $page=pagename($file) if defined $type;
1826 if ($change->{action} eq 'add') {
1830 if ($change->{action} eq 'change' ||
1831 $change->{action} eq 'add') {
1832 if (defined $page) {
1833 check_canedit($page, $cgi, $session);
1837 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1838 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1839 check_canedit($file, $cgi, $session);
1844 elsif ($change->{action} eq 'remove') {
1845 # check_canremove tests to see if the file is present
1846 # on disk. This will fail when a single commit adds a
1847 # file and then removes it again. Avoid the problem
1848 # by not testing the removal in such pairs of changes.
1849 # (The add is still tested, just to make sure that
1850 # no data is added to the repo that a web edit
1852 next if $newfiles{$file};
1854 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1855 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1856 check_canedit(defined $page ? $page : $file, $cgi, $session);
1861 error "unknown action ".$change->{action};
1864 error sprintf(gettext("you are not allowed to change %s"), $file);
1872 # Take an exclusive lock on the wiki to prevent multiple concurrent
1873 # run issues. The lock will be dropped on program exit.
1874 if (! -d $config{wikistatedir}) {
1875 mkdir($config{wikistatedir});
1877 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1878 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1879 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1880 debug("failed to get lock; waiting...");
1881 if (! flock($wikilock, LOCK_EX)) {
1882 error("failed to get lock");
1889 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1890 return close($wikilock) if $wikilock;
1896 sub commit_hook_enabled () {
1897 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1898 error("cannot write to $config{wikistatedir}/commitlock: $!");
1899 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1900 close($commitlock) || error("failed closing commitlock: $!");
1903 close($commitlock) || error("failed closing commitlock: $!");
1907 sub disable_commit_hook () {
1908 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1909 error("cannot write to $config{wikistatedir}/commitlock: $!");
1910 if (! flock($commitlock, 2)) { # LOCK_EX
1911 error("failed to get commit lock");
1916 sub enable_commit_hook () {
1917 return close($commitlock) if $commitlock;
1922 %oldrenderedfiles=%pagectime=();
1923 my $rebuild=$config{rebuild};
1925 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1926 %destsources=%renderedfiles=%pagecase=%pagestate=
1927 %depends_simple=%typedlinks=%oldtypedlinks=();
1930 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1931 if (-e "$config{wikistatedir}/index") {
1932 system("ikiwiki-transition", "indexdb", $config{srcdir});
1933 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1936 # gettime on first build
1937 $config{gettime}=1 unless defined $config{gettime};
1942 my $index=Storable::fd_retrieve($in);
1943 if (! defined $index) {
1948 if (exists $index->{version} && ! ref $index->{version}) {
1949 $pages=$index->{page};
1950 %wikistate=%{$index->{state}};
1951 # Handle plugins that got disabled by loading a new setup.
1952 if (exists $config{setupfile}) {
1953 require IkiWiki::Setup;
1954 IkiWiki::Setup::disabled_plugins(
1955 grep { ! $loaded_plugins{$_} } keys %wikistate);
1963 foreach my $src (keys %$pages) {
1964 my $d=$pages->{$src};
1966 if (exists $d->{page} && ! $rebuild) {
1970 $page=pagename($src);
1972 $pagectime{$page}=$d->{ctime};
1973 $pagesources{$page}=$src;
1975 $pagemtime{$page}=$d->{mtime};
1976 $renderedfiles{$page}=$d->{dest};
1977 if (exists $d->{links} && ref $d->{links}) {
1978 $links{$page}=$d->{links};
1979 $oldlinks{$page}=[@{$d->{links}}];
1981 if (ref $d->{depends_simple} eq 'ARRAY') {
1983 $depends_simple{$page}={
1984 map { $_ => 1 } @{$d->{depends_simple}}
1987 elsif (exists $d->{depends_simple}) {
1988 $depends_simple{$page}=$d->{depends_simple};
1990 if (exists $d->{dependslist}) {
1993 map { $_ => $DEPEND_CONTENT }
1994 @{$d->{dependslist}}
1997 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1999 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
2001 elsif (exists $d->{depends}) {
2002 $depends{$page}=$d->{depends};
2004 if (exists $d->{state}) {
2005 $pagestate{$page}=$d->{state};
2007 if (exists $d->{typedlinks}) {
2008 $typedlinks{$page}=$d->{typedlinks};
2010 while (my ($type, $links) = each %{$typedlinks{$page}}) {
2011 next unless %$links;
2012 $oldtypedlinks{$page}{$type} = {%$links};
2016 $oldrenderedfiles{$page}=[@{$d->{dest}}];
2018 foreach my $page (keys %pagesources) {
2019 $pagecase{lc $page}=$page;
2021 foreach my $page (keys %renderedfiles) {
2022 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
2024 $lastrev=$index->{lastrev};
2025 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
2030 run_hooks(savestate => sub { shift->() });
2032 my @plugins=keys %loaded_plugins;
2034 if (! -d $config{wikistatedir}) {
2035 mkdir($config{wikistatedir});
2037 my $newfile="$config{wikistatedir}/indexdb.new";
2038 my $cleanup = sub { unlink($newfile) };
2039 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
2042 foreach my $page (keys %pagemtime) {
2043 next unless $pagemtime{$page};
2044 my $src=$pagesources{$page};
2046 $index{page}{$src}={
2048 ctime => $pagectime{$page},
2049 mtime => $pagemtime{$page},
2050 dest => $renderedfiles{$page},
2051 links => $links{$page},
2054 if (exists $depends{$page}) {
2055 $index{page}{$src}{depends} = $depends{$page};
2058 if (exists $depends_simple{$page}) {
2059 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2062 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2063 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2066 if (exists $pagestate{$page}) {
2067 $index{page}{$src}{state}=$pagestate{$page};
2072 foreach my $id (@plugins) {
2073 $index{state}{$id}={}; # used to detect disabled plugins
2074 foreach my $key (keys %{$wikistate{$id}}) {
2075 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2079 $index{lastrev}=$lastrev;
2080 $index{underlayfiles}=\@underlayfiles;
2082 $index{version}="3";
2083 my $ret=Storable::nstore_fd(\%index, $out);
2084 return if ! defined $ret || ! $ret;
2085 close $out || error("failed saving to $newfile: $!", $cleanup);
2086 rename($newfile, "$config{wikistatedir}/indexdb") ||
2087 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2092 sub template_file ($) {
2095 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2097 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2098 $template=srcfile($pagesources{$tpage}, 1);
2102 $template=srcfile($tpage, 1);
2105 if (defined $template) {
2106 return $template, $tpage, 1 if wantarray;
2110 $name=~s:/::; # avoid path traversal
2111 foreach my $dir ($config{templatedir},
2112 "$installdir/share/ikiwiki/templates") {
2113 if (-e "$dir/$name") {
2114 $template="$dir/$name";
2118 if (defined $template) {
2119 return $template, $tpage if wantarray;
2127 sub template_depends ($$;@) {
2131 my ($filename, $tpage, $untrusted)=template_file($name);
2132 if (! defined $filename) {
2133 error(sprintf(gettext("template %s not found"), $name))
2136 if (defined $page && defined $tpage) {
2137 add_depends($page, $tpage);
2142 my $text_ref = shift;
2143 ${$text_ref} = decode_utf8(${$text_ref});
2144 run_hooks(readtemplate => sub {
2145 ${$text_ref} = shift->(
2148 content => ${$text_ref},
2149 untrusted => $untrusted,
2153 loop_context_vars => 1,
2154 die_on_bad_params => 0,
2155 parent_global_vars => 1,
2156 filename => $filename,
2158 ($untrusted ? (no_includes => 1) : ()),
2160 return @opts if wantarray;
2162 require HTML::Template;
2163 return HTML::Template->new(@opts);
2166 sub template ($;@) {
2167 template_depends(shift, undef, @_);
2170 sub templateactions ($$) {
2176 run_hooks(pageactions => sub {
2177 push @actions, map { { action => $_ } }
2178 grep { defined } shift->(page => $page);
2180 $template->param(actions => \@actions);
2182 if ($config{cgiurl} && exists $hooks{auth}) {
2183 $template->param(prefsurl => cgiurl(do => "prefs"));
2187 if ($have_actions || @actions) {
2188 $template->param(have_actions => 1);
2195 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2196 error 'hook requires type, call, and id parameters';
2199 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2201 $hooks{$param{type}}{$param{id}}=\%param;
2205 sub run_hooks ($$) {
2206 # Calls the given sub for each hook of the given type,
2207 # passing it the hook function to call.
2211 if (exists $hooks{$type}) {
2212 my (@first, @middle, @last);
2213 foreach my $id (keys %{$hooks{$type}}) {
2214 if ($hooks{$type}{$id}{first}) {
2217 elsif ($hooks{$type}{$id}{last}) {
2224 foreach my $id (@first, @middle, @last) {
2225 $sub->($hooks{$type}{$id}{call});
2233 $hooks{rcs}{rcs_update}{call}->(@_);
2236 sub rcs_prepedit ($) {
2237 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2240 sub rcs_commit (@) {
2241 $hooks{rcs}{rcs_commit}{call}->(@_);
2244 sub rcs_commit_staged (@) {
2245 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2249 $hooks{rcs}{rcs_add}{call}->(@_);
2252 sub rcs_remove ($) {
2253 $hooks{rcs}{rcs_remove}{call}->(@_);
2256 sub rcs_rename ($$) {
2257 $hooks{rcs}{rcs_rename}{call}->(@_);
2260 sub rcs_recentchanges ($) {
2261 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2264 sub rcs_diff ($;$) {
2265 $hooks{rcs}{rcs_diff}{call}->(@_);
2268 sub rcs_getctime ($) {
2269 $hooks{rcs}{rcs_getctime}{call}->(@_);
2272 sub rcs_getmtime ($) {
2273 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2276 sub rcs_receive () {
2277 $hooks{rcs}{rcs_receive}{call}->();
2280 sub add_depends ($$;$) {
2283 my $deptype=shift || $DEPEND_CONTENT;
2285 # Is the pagespec a simple page name?
2286 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2287 $pagespec !~ /[\s*?()!]/) {
2288 $depends_simple{$page}{lc $pagespec} |= $deptype;
2292 # Add explicit dependencies for influences.
2293 my $sub=pagespec_translate($pagespec);
2294 return unless defined $sub;
2295 foreach my $p (keys %pagesources) {
2296 my $r=$sub->($p, location => $page);
2297 my $i=$r->influences;
2298 my $static=$r->influences_static;
2299 foreach my $k (keys %$i) {
2300 next unless $r || $static || $k eq $page;
2301 $depends_simple{$page}{lc $k} |= $i->{$k};
2306 $depends{$page}{$pagespec} |= $deptype;
2312 foreach my $type (@_) {
2313 if ($type eq 'presence') {
2314 $deptype |= $DEPEND_PRESENCE;
2316 elsif ($type eq 'links') {
2317 $deptype |= $DEPEND_LINKS;
2319 elsif ($type eq 'content') {
2320 $deptype |= $DEPEND_CONTENT;
2326 my $file_prune_regexp;
2327 sub file_pruned ($) {
2330 if (defined $config{include} && length $config{include}) {
2331 return 0 if $file =~ m/$config{include}/;
2334 if (! defined $file_prune_regexp) {
2335 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2336 $file_prune_regexp=qr/$file_prune_regexp/;
2338 return $file =~ m/$file_prune_regexp/;
2341 sub define_gettext () {
2342 # If translation is needed, redefine the gettext function to do it.
2343 # Otherwise, it becomes a quick no-op.
2346 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2347 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2348 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2350 $gettext_obj=eval q{
2351 use Locale::gettext q{textdomain};
2352 Locale::gettext->domain('ikiwiki')
2357 no warnings 'redefine';
2359 $getobj->() if $getobj;
2361 $gettext_obj->get(shift);
2368 $getobj->() if $getobj;
2370 $gettext_obj->nget(@_);
2373 return ($_[2] == 1 ? $_[0] : $_[1])
2391 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2395 # Injects a new function into the symbol table to replace an
2396 # exported function.
2399 # This is deep ugly perl foo, beware.
2402 if (! defined $params{parent}) {
2403 $params{parent}='::';
2404 $params{old}=\&{$params{name}};
2405 $params{name}=~s/.*:://;
2407 my $parent=$params{parent};
2408 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2409 $ns = $params{parent} . $ns;
2410 inject(%params, parent => $ns) unless $ns eq '::main::';
2411 *{$ns . $params{name}} = $params{call}
2412 if exists ${$ns}{$params{name}} &&
2413 \&{${$ns}{$params{name}}} == $params{old};
2419 sub add_link ($$;$) {
2424 push @{$links{$page}}, $link
2425 unless grep { $_ eq $link } @{$links{$page}};
2427 if (defined $type) {
2428 $typedlinks{$page}{$type}{$link} = 1;
2432 sub add_autofile ($$$) {
2435 my $generator=shift;
2437 $autofiles{$file}{plugin}=$plugin;
2438 $autofiles{$file}{generator}=$generator;
2442 return LWP::UserAgent->new(
2443 cookie_jar => $config{cookiejar},
2444 env_proxy => 1, # respect proxy env vars
2445 agent => $config{useragent},
2449 sub sortspec_translate ($$) {
2451 my $reverse = shift;
2457 (-?) # group 1: perhaps negated
2460 \w+\([^\)]*\) # command(params)
2462 [^\s]+ # or anything else
2470 if ($word =~ m/^(\w+)\((.*)\)$/) {
2471 # command with parameters
2475 elsif ($word !~ m/^\w+$/) {
2476 error(sprintf(gettext("invalid sort type %s"), $word));
2487 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2488 if (defined $params) {
2489 push @data, $params;
2490 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2493 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2497 error(sprintf(gettext("unknown sort type %s"), $word));
2501 if (! length $code) {
2502 # undefined sorting method... sort arbitrarily
2511 return eval 'sub { '.$code.' }';
2514 sub pagespec_translate ($) {
2517 # Convert spec to perl code.
2521 \s* # ignore whitespace
2522 ( # 1: match a single word
2529 \w+\([^\)]*\) # command(params)
2531 [^\s()]+ # any other text
2533 \s* # ignore whitespace
2536 if (lc $word eq 'and') {
2539 elsif (lc $word eq 'or') {
2542 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2545 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2546 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2548 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2551 push @data, qq{unknown function in pagespec "$word"};
2552 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2557 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2561 if (! length $code) {
2562 $code="IkiWiki::FailReason->new('empty pagespec')";
2566 return eval 'sub { my $page=shift; '.$code.' }';
2569 sub pagespec_match ($$;@) {
2574 # Backwards compatability with old calling convention.
2576 unshift @params, 'location';
2579 my $sub=pagespec_translate($spec);
2580 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2582 return $sub->($page, @params);
2585 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2587 # Not exported yet, but could be in future if it is generally useful.
2588 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2589 # which is "more internal".
2590 sub sort_pages ($$;@) {
2594 $sort = sortspec_translate($sort, $params{reverse});
2595 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2598 sub pagespec_match_list ($$;@) {
2603 # Backwards compatability with old calling convention.
2605 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2606 $params{list}=$page;
2607 $page=$params{location}; # ugh!
2610 my $sub=pagespec_translate($pagespec);
2611 error "syntax error in pagespec \"$pagespec\""
2613 my $sort=sortspec_translate($params{sort}, $params{reverse})
2614 if defined $params{sort};
2617 if (exists $params{list}) {
2618 @candidates=exists $params{filter}
2619 ? grep { ! $params{filter}->($_) } @{$params{list}}
2623 @candidates=exists $params{filter}
2624 ? grep { ! $params{filter}->($_) } keys %pagesources
2625 : keys %pagesources;
2628 # clear params, remainder is passed to pagespec
2629 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2630 my $num=$params{num};
2631 delete @params{qw{num deptype reverse sort filter list}};
2633 # when only the top matches will be returned, it's efficient to
2634 # sort before matching to pagespec,
2635 if (defined $num && defined $sort) {
2636 @candidates=IkiWiki::SortSpec::sort_pages(
2637 $sort, @candidates);
2643 my $accum=IkiWiki::SuccessReason->new();
2644 foreach my $p (@candidates) {
2645 my $r=$sub->($p, %params, location => $page);
2646 error(sprintf(gettext("cannot match pages: %s"), $r))
2647 if $r->isa("IkiWiki::ErrorReason");
2648 unless ($r || $r->influences_static) {
2649 $r->remove_influence($p);
2654 last if defined $num && ++$count == $num;
2658 # Add simple dependencies for accumulated influences.
2659 my $i=$accum->influences;
2660 foreach my $k (keys %$i) {
2661 $depends_simple{$page}{lc $k} |= $i->{$k};
2664 # when all matches will be returned, it's efficient to
2665 # sort after matching
2666 if (! defined $num && defined $sort) {
2667 return IkiWiki::SortSpec::sort_pages(
2675 sub pagespec_valid ($) {
2678 return defined pagespec_translate($spec);
2682 my $re=quotemeta(shift);
2688 package IkiWiki::FailReason;
2691 '""' => sub { $_[0][0] },
2693 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2694 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2695 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2699 our @ISA = 'IkiWiki::SuccessReason';
2701 package IkiWiki::SuccessReason;
2703 # A blessed array-ref:
2705 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2707 # - if absent or false, the influences of this evaluation are "static",
2708 # see the influences_static method
2709 # - if true, they are dynamic (not static)
2710 # [1]{any other key}:
2711 # the dependency types of influences, as returned by the influences method
2714 # in string context, it's the human-readable reason
2715 '""' => sub { $_[0][0] },
2716 # in boolean context, SuccessReason is 1 and FailReason is 0
2718 # negating a result gives the opposite result with the same influences
2719 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2720 # A & B = (A ? B : A) with the influences of both
2721 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2722 # A | B = (A ? A : B) with the influences of both
2723 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2727 # SuccessReason->new("human-readable reason", page => deptype, ...)
2732 return bless [$value, {@_}], $class;
2735 # influences(): return a reference to a copy of the hash
2736 # { page => dependency type } describing the pages that indirectly influenced
2737 # this result, but would not cause a dependency through ikiwiki's core
2740 # See [[todo/dependency_types]] for extensive discussion of what this means.
2742 # influences(page => deptype, ...): remove all influences, replace them
2743 # with the arguments, and return a reference to a copy of the new influences.
2747 $this->[1]={@_} if @_;
2748 my %i=%{$this->[1]};
2753 # True if this result has the same influences whichever page it matches,
2754 # For instance, whether bar matches backlink(foo) is influenced only by
2755 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2756 # which does not mention bar anywhere.
2758 # False if this result would have different influences when matching
2759 # different pages. For instance, when testing whether link(foo) matches bar,
2760 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2761 # bar's links could change the outcome; so its influences are not the same
2762 # as when testing whether link(foo) matches baz.
2764 # Static influences are one of the things that make pagespec_match_list
2765 # more efficient than repeated calls to pagespec_match.
2767 sub influences_static {
2768 return ! $_[0][1]->{""};
2771 # Change the influences of $this to be the influences of "$this & $other"
2772 # or "$this | $other".
2774 # If both $this and $other are either successful or have influences,
2775 # or this is an "or" operation, the result has all the influences from
2776 # either of the arguments. It has dynamic influences if either argument
2777 # has dynamic influences.
2779 # If this is an "and" operation, and at least one argument is a
2780 # FailReason with no influences, the result has no influences, and they
2781 # are not dynamic. For instance, link(foo) matching bar is influenced
2782 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2783 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2784 # bar, because it would be false however often you edit bar.
2786 sub merge_influences {
2791 # This "if" is odd because it needs to avoid negating $this
2792 # or $other, which would alter the objects in-place. Be careful.
2793 if (! $anded || (($this || %{$this->[1]}) &&
2794 ($other || %{$other->[1]}))) {
2795 foreach my $influence (keys %{$other->[1]}) {
2796 $this->[1]{$influence} |= $other->[1]{$influence};
2805 # Change $this so it is not considered to be influenced by $torm.
2807 sub remove_influence {
2811 delete $this->[1]{$torm};
2814 package IkiWiki::ErrorReason;
2816 our @ISA = 'IkiWiki::FailReason';
2818 package IkiWiki::PageSpec;
2824 if ($path =~ m!^\.(/|$)!) {
2826 $from=~s#/?[^/]+$## if defined $from;
2828 $path="$from/$path" if defined $from && length $from;
2832 $path = "" unless defined $path;
2841 sub match_glob ($$;@) {
2846 $glob=derel($glob, $params{location});
2848 # Instead of converting the glob to a regex every time,
2849 # cache the compiled regex to save time.
2850 my $re=$glob_cache{$glob};
2851 unless (defined $re) {
2852 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2855 if (! IkiWiki::isinternal($page) || $params{internal}) {
2856 return IkiWiki::SuccessReason->new("$glob matches $page");
2859 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2863 return IkiWiki::FailReason->new("$glob does not match $page");
2867 sub match_internal ($$;@) {
2868 return match_glob(shift, shift, @_, internal => 1)
2871 sub match_page ($$;@) {
2873 my $match=match_glob($page, shift, @_);
2875 my $source=exists $IkiWiki::pagesources{$page} ?
2876 $IkiWiki::pagesources{$page} :
2877 $IkiWiki::delpagesources{$page};
2878 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2879 if (! defined $type) {
2880 return IkiWiki::FailReason->new("$page is not a page");
2886 sub match_link ($$;@) {
2891 $link=derel($link, $params{location});
2892 my $from=exists $params{location} ? $params{location} : '';
2893 my $linktype=$params{linktype};
2895 if (defined $linktype) {
2896 $qualifier=" with type $linktype";
2899 my $links = $IkiWiki::links{$page};
2900 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2901 unless $links && @{$links};
2902 my $bestlink = IkiWiki::bestlink($from, $link);
2903 foreach my $p (@{$links}) {
2904 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2906 if (length $bestlink) {
2907 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2908 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2912 if (match_glob($p, $link, %params)) {
2913 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2915 my ($p_rel)=$p=~/^\/?(.*)/;
2917 if (match_glob($p_rel, $link, %params)) {
2918 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2922 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2925 sub match_backlink ($$;@) {
2929 if ($testpage eq '.') {
2930 $testpage = $params{'location'}
2932 my $ret=match_link($testpage, $page, @_);
2933 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2937 sub match_created_before ($$;@) {
2942 $testpage=derel($testpage, $params{location});
2944 if (exists $IkiWiki::pagectime{$testpage}) {
2945 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2946 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2949 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2953 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2957 sub match_created_after ($$;@) {
2962 $testpage=derel($testpage, $params{location});
2964 if (exists $IkiWiki::pagectime{$testpage}) {
2965 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2966 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2969 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2973 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2977 sub match_creation_day ($$;@) {
2980 if ($d !~ /^\d+$/) {
2981 return IkiWiki::ErrorReason->new("invalid day $d");
2983 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2984 return IkiWiki::SuccessReason->new('creation_day matched');
2987 return IkiWiki::FailReason->new('creation_day did not match');
2991 sub match_creation_month ($$;@) {
2994 if ($m !~ /^\d+$/) {
2995 return IkiWiki::ErrorReason->new("invalid month $m");
2997 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2998 return IkiWiki::SuccessReason->new('creation_month matched');
3001 return IkiWiki::FailReason->new('creation_month did not match');
3005 sub match_creation_year ($$;@) {
3008 if ($y !~ /^\d+$/) {
3009 return IkiWiki::ErrorReason->new("invalid year $y");
3011 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
3012 return IkiWiki::SuccessReason->new('creation_year matched');
3015 return IkiWiki::FailReason->new('creation_year did not match');
3019 sub match_user ($$;@) {
3024 if (! exists $params{user}) {
3025 return IkiWiki::ErrorReason->new("no user specified");
3028 my $regexp=IkiWiki::glob2re($user);
3030 if (defined $params{user} && $params{user}=~$regexp) {
3031 return IkiWiki::SuccessReason->new("user is $user");
3033 elsif (! defined $params{user}) {
3034 return IkiWiki::FailReason->new("not logged in");
3037 return IkiWiki::FailReason->new("user is $params{user}, not $user");
3041 sub match_admin ($$;@) {
3046 if (! exists $params{user}) {
3047 return IkiWiki::ErrorReason->new("no user specified");
3050 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3051 return IkiWiki::SuccessReason->new("user is an admin");
3053 elsif (! defined $params{user}) {
3054 return IkiWiki::FailReason->new("not logged in");
3057 return IkiWiki::FailReason->new("user is not an admin");
3061 sub match_ip ($$;@) {
3066 if (! exists $params{ip}) {
3067 return IkiWiki::ErrorReason->new("no IP specified");
3070 my $regexp=IkiWiki::glob2re(lc $ip);
3072 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3073 return IkiWiki::SuccessReason->new("IP is $ip");
3076 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3080 package IkiWiki::SortSpec;
3082 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3083 # are easily available in this namespace, for cmp functions to use them.
3090 IkiWiki::pagetitle(IkiWiki::basename($a))
3092 IkiWiki::pagetitle(IkiWiki::basename($b))
3095 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3096 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3097 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }