9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %wikistate %renderedfiles %oldrenderedfiles
16 %pagesources %delpagesources %destsources %depends %depends_simple
17 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
18 %oldtypedlinks %autofiles @underlayfiles $lastrev $phase};
20 use Exporter q{import};
21 our @EXPORT = qw(hook debug error htmlpage template template_depends
22 deptype add_depends pagespec_match pagespec_match_list bestlink
23 htmllink readfile writefile pagetype srcfile pagename
24 displaytime strftime_utf8 will_render gettext ngettext urlto targetpage
25 add_underlay pagetitle titlepage linkpage newpagefile
26 inject add_link add_autofile useragent
27 %config %links %pagestate %wikistate %renderedfiles
28 %pagesources %destsources %typedlinks);
29 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
30 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
31 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
33 # Page dependency types.
34 our $DEPEND_CONTENT=1;
35 our $DEPEND_PRESENCE=2;
38 # Phases of processing.
39 sub PHASE_SCAN () { 0 }
40 sub PHASE_RENDER () { 1 }
46 memoize("sortspec_translate");
47 memoize("pagespec_translate");
48 memoize("template_file");
54 description => "name of the wiki",
61 example => 'me@example.com',
62 description => "contact email for wiki",
69 description => "users who are wiki admins",
76 description => "users who are banned from the wiki",
83 example => "$ENV{HOME}/wiki",
84 description => "where the source of the wiki is located",
91 example => "/var/www/wiki",
92 description => "where to build the wiki",
99 example => "http://example.com/wiki",
100 description => "base url to the wiki",
107 example => "http://example.com/wiki/ikiwiki.cgi",
108 description => "url to the ikiwiki.cgi",
115 description => "do not adjust cgiurl if CGI is accessed via different URL",
118 rebuild => 0, # only affects CGI requests
123 example => "/var/www/wiki/ikiwiki.cgi",
124 description => "filename of cgi wrapper to generate",
131 description => "mode for cgi_wrapper (can safely be made suid)",
135 cgi_overload_delay => {
139 description => "number of seconds to delay CGI requests when overloaded",
143 cgi_overload_message => {
146 example => "Please wait",
147 description => "message to display when overloaded (may contain html)",
151 only_committed_changes => {
154 description => "enable optimization of only refreshing committed changes?",
161 description => "rcs backend to use",
162 safe => 0, # don't allow overriding
167 default => [qw{mdwn link inline meta htmlscrubber passwordauth
168 openid signinedit lockedit conditional
169 recentchanges parentlinks editpage
171 description => "plugins to enable by default",
178 description => "plugins to add to the default configuration",
185 description => "plugins to disable",
191 default => "$installdir/share/ikiwiki/templates",
192 description => "additional directory to search for template files",
199 default => "$installdir/share/ikiwiki/basewiki",
200 description => "base wiki source location",
207 default => "$installdir/share/ikiwiki",
208 description => "parent directory containing additional underlays",
215 description => "wrappers to generate",
222 description => "additional underlays to use",
229 description => "display verbose messages?",
236 description => "log to syslog?",
243 description => "create output files named page/index.html?",
244 safe => 0, # changing requires manual transition
247 prefix_directives => {
250 description => "use '!'-prefixed preprocessor directives?",
251 safe => 0, # changing requires manual transition
257 description => "use page/index.mdwn source files",
264 description => "enable Discussion pages?",
270 default => gettext("Discussion"),
271 description => "name of Discussion pages",
278 description => "use elements new in HTML5 like <section>?",
286 description => "only send cookies over SSL connections?",
294 description => "extension to use for new pages",
295 safe => 0, # not sanitized
301 description => "extension to use for html files",
302 safe => 0, # not sanitized
308 description => "strftime format string to display date",
316 example => "en_US.UTF-8",
317 description => "UTF-8 locale to use",
326 description => "put user pages below specified page",
333 description => "how many backlinks to show before hiding excess (0 to show all)",
340 description => "attempt to hardlink source files? (optimisation for large files)",
342 safe => 0, # paranoia
348 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
350 safe => 0, # paranoia
355 example => "ikiwiki",
356 description => "group for wrappers to run in",
358 safe => 0, # paranoia
364 example => ["$ENV{HOME}/.local/share/ikiwiki"],
365 description => "extra library and plugin directories",
367 safe => 0, # directory
373 example => "$ENV{HOME}/.ikiwiki/",
374 description => "extra library and plugin directory (searched after libdirs)",
376 safe => 0, # directory
382 description => "environment variables",
383 safe => 0, # paranoia
389 example => "US/Eastern",
390 description => "time zone name",
397 example => '^\.htaccess$',
398 description => "regexp of normally excluded files to include",
406 example => '^(*\.private|Makefile)$',
407 description => "regexp of files that should be skipped",
412 wiki_file_prune_regexps => {
414 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
415 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
416 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
417 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
418 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
419 description => "regexps of source files to ignore",
425 description => "specifies the characters that are allowed in source filenames",
426 default => "-[:alnum:]+/.:_",
430 wiki_file_regexp => {
432 description => "regexp of legal source files",
436 web_commit_regexp => {
438 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
439 description => "regexp to parse web commits from logs",
446 description => "run as a cgi",
450 cgi_disable_uploads => {
453 description => "whether CGI should accept file uploads",
460 description => "run as a post-commit hook",
467 description => "running in rebuild mode",
474 description => "running in setup mode",
481 description => "running in clean mode",
488 description => "running in refresh mode",
495 description => "running in receive test mode",
499 wrapper_background_command => {
502 description => "background shell command to run",
508 description => "running in gettime mode",
515 description => "running in w3mmode",
522 description => "path to the .ikiwiki directory holding ikiwiki state",
529 description => "path to setup file",
536 description => "perl class to use to dump setup file",
540 allow_symlinks_before_srcdir => {
543 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
549 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
550 description => "cookie control",
551 safe => 0, # hooks into perl module internals
556 default => "ikiwiki/$version",
557 example => "Wget/1.13.4 (linux-gnu)",
558 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
562 responsive_layout => {
565 description => "theme has a responsive layout? (mobile-optimized)",
572 description => "try harder to produce deterministic output",
581 if ($config{libdirs}) {
582 @libdirs = @{$config{libdirs}};
584 if (length $config{libdir}) {
585 push @libdirs, $config{libdir};
590 sub defaultconfig () {
593 foreach my $key (keys %s) {
594 push @ret, $key, $s{$key}->{default};
599 # URL to top of wiki as a path starting with /, valid from any wiki page or
600 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
602 # URL to CGI script, similar to $local_url
606 # locale stuff; avoid LC_ALL since it overrides everything
607 if (defined $ENV{LC_ALL}) {
608 $ENV{LANG} = $ENV{LC_ALL};
611 if (defined $config{locale}) {
612 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
613 $ENV{LANG}=$config{locale};
618 if (! defined $config{wiki_file_regexp}) {
619 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
622 if (ref $config{ENV} eq 'HASH') {
623 foreach my $val (keys %{$config{ENV}}) {
624 $ENV{$val}=$config{ENV}{$val};
627 if (defined $config{timezone} && length $config{timezone}) {
628 $ENV{TZ}=$config{timezone};
630 elsif (defined $ENV{TZ} && length $ENV{TZ}) {
631 $config{timezone}=$ENV{TZ};
634 eval q{use Config qw()};
637 if ($Config::Config{d_gnulibc} && -e '/etc/localtime') {
638 $config{timezone}=$ENV{TZ}=':/etc/localtime';
641 $config{timezone}=$ENV{TZ}='GMT';
645 if ($config{w3mmode}) {
646 eval q{use Cwd q{abs_path}};
648 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
649 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
650 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
651 unless $config{cgiurl} =~ m!file:///!;
652 $config{url}="file://".$config{destdir};
655 if ($config{cgi} && ! length $config{url}) {
656 error(gettext("Must specify url to wiki with --url when using --cgi"));
659 if (defined $config{url} && length $config{url}) {
661 my $baseurl = URI->new($config{url});
663 $local_url = $baseurl->path . "/";
664 $local_cgiurl = undef;
666 if (length $config{cgiurl}) {
667 my $cgiurl = URI->new($config{cgiurl});
669 $local_cgiurl = $cgiurl->path;
671 if ($cgiurl->scheme eq 'https' &&
672 $baseurl->scheme eq 'http') {
673 # We assume that the same content is available
674 # over both http and https, because if it
675 # wasn't, accessing the static content
676 # from the CGI would be mixed-content,
677 # which would be a security flaw.
679 if ($cgiurl->authority ne $baseurl->authority) {
680 # use protocol-relative URL for
682 $local_url = "$config{url}/";
683 $local_url =~ s{^http://}{//};
685 # else use host-relative URL for static content
687 # either way, CGI needs to be absolute
688 $local_cgiurl = $config{cgiurl};
690 elsif ($cgiurl->scheme ne $baseurl->scheme) {
691 # too far apart, fall back to absolute URLs
692 $local_url = "$config{url}/";
693 $local_cgiurl = $config{cgiurl};
695 elsif ($cgiurl->authority ne $baseurl->authority) {
696 # slightly too far apart, fall back to
697 # protocol-relative URLs
698 $local_url = "$config{url}/";
699 $local_url =~ s{^https?://}{//};
700 $local_cgiurl = $config{cgiurl};
701 $local_cgiurl =~ s{^https?://}{//};
703 # else keep host-relative URLs
706 $local_url =~ s{//$}{/};
709 $local_cgiurl = $config{cgiurl};
712 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
713 unless exists $config{wikistatedir} && defined $config{wikistatedir};
715 if (defined $config{umask}) {
716 my $u = possibly_foolish_untaint($config{umask});
718 if ($u =~ m/^\d+$/) {
721 elsif ($u eq 'private') {
724 elsif ($u eq 'group') {
727 elsif ($u eq 'public') {
731 error(sprintf(gettext("unsupported umask setting %s"), $u));
735 run_hooks(checkconfig => sub { shift->() });
743 foreach my $dir (@INC, getlibdirs()) {
744 next unless defined $dir && length $dir;
745 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
746 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
750 foreach my $dir (getlibdirs(), "$installdir/lib/ikiwiki") {
751 next unless defined $dir && length $dir;
752 foreach my $file (glob("$dir/plugins/*")) {
753 $ret{basename($file)}=1 if -x $file;
761 foreach my $dir (getlibdirs()) {
762 unshift @INC, possibly_foolish_untaint($dir);
765 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
770 if (exists $hooks{rcs}) {
771 error(gettext("cannot use multiple rcs plugins"));
773 loadplugin($config{rcs});
775 if (! exists $hooks{rcs}) {
779 run_hooks(getopt => sub { shift->() });
780 if (grep /^-/, @ARGV) {
781 print STDERR "Unknown option (or missing parameter): $_\n"
782 foreach grep /^-/, @ARGV;
789 sub loadplugin ($;$) {
793 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
795 foreach my $possiblytainteddir (getlibdirs(), "$installdir/lib/ikiwiki") {
796 my $dir = possibly_foolish_untaint($possiblytainteddir);
797 if (defined $dir && -x "$dir/plugins/$plugin") {
798 eval { require IkiWiki::Plugin::external };
801 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
803 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
804 $loaded_plugins{$plugin}=1;
809 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
812 error("Failed to load plugin $mod: $@");
814 $loaded_plugins{$plugin}=1;
821 log_message('err' => $message) if $config{syslog};
822 if (defined $cleaner) {
829 return unless $config{verbose};
830 return log_message(debug => @_);
835 sub log_message ($$) {
838 if ($config{syslog}) {
841 Sys::Syslog::setlogsock('unix');
842 Sys::Syslog::openlog('ikiwiki', '', 'user');
846 # keep a copy to avoid editing the original config repeatedly
847 my $wikiname = $config{wikiname};
848 utf8::encode($wikiname);
849 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
852 print STDERR "failed to syslog: $@" unless $log_failed;
858 elsif (! $config{cgi}) {
862 return print STDERR "@_\n";
866 sub possibly_foolish_untaint ($) {
868 my ($untainted)=$tainted=~/(.*)/s;
888 return exists $pagesources{$page} &&
889 $pagesources{$page} =~ /\._([^.]+)$/;
895 if ($file =~ /\.([^.]+)$/) {
896 return $1 if exists $hooks{htmlize}{$1};
898 my $base=basename($file);
899 if (exists $hooks{htmlize}{$base} &&
900 $hooks{htmlize}{$base}{noextension}) {
911 if (exists $pagename_cache{$file}) {
912 return $pagename_cache{$file};
915 my $type=pagetype($file);
917 $page=~s/\Q.$type\E*$//
918 if defined $type && !$hooks{htmlize}{$type}{keepextension}
919 && !$hooks{htmlize}{$type}{noextension};
920 if ($config{indexpages} && $page=~/(.*)\/index$/) {
924 $pagename_cache{$file} = $page;
928 sub newpagefile ($$) {
932 if (! $config{indexpages} || $page eq 'index') {
933 return $page.".".$type;
936 return $page."/index.".$type;
940 sub targetpage ($$;$) {
945 if (defined $filename) {
946 return $page."/".$filename.".".$ext;
948 elsif (! $config{usedirs} || $page eq 'index') {
949 return $page.".".$ext;
952 return $page."/index.".$ext;
959 return targetpage($page, $config{htmlext});
966 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
967 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
968 return "$dir/$file", stat(_) if -e "$dir/$file";
970 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
975 return (srcfile_stat(@_))[0];
978 sub add_literal_underlay ($) {
981 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
982 unshift @{$config{underlaydirs}}, $dir;
986 sub add_underlay ($) {
990 $dir="$config{underlaydirbase}/$dir";
993 add_literal_underlay($dir);
994 # why does it return 1? we just don't know
998 sub readfile ($;$$) {
1004 error("cannot read a symlink ($file)");
1008 open (my $in, "<", $file) || error("failed to read $file: $!");
1009 binmode($in) if ($binary);
1010 return \*$in if $wantfd;
1012 # check for invalid utf-8, and toss it back to avoid crashes
1013 if (! utf8::valid($ret)) {
1014 $ret=encode_utf8($ret);
1016 close $in || error("failed to read $file: $!");
1020 sub prep_writefile ($$) {
1025 while (length $test) {
1026 if (-l "$destdir/$test") {
1027 error("cannot write to a symlink ($test)");
1029 if (-f _ && $test ne $file) {
1030 # Remove conflicting file.
1031 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1032 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1034 unlink("$destdir/$test");
1040 $test=dirname($test);
1043 my $dir=dirname("$destdir/$file");
1046 foreach my $s (split(m!/+!, $dir)) {
1049 mkdir($d) || error("failed to create directory $d: $!");
1057 sub writefile ($$$;$$) {
1058 my $file=shift; # can include subdirs
1059 my $destdir=shift; # directory to put file in
1064 prep_writefile($file, $destdir);
1066 my $newfile="$destdir/$file.ikiwiki-new";
1068 error("cannot write to a symlink ($newfile)");
1071 my $cleanup = sub { unlink($newfile) };
1072 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1073 binmode($out) if ($binary);
1075 $writer->(\*$out, $cleanup);
1078 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1080 close $out || error("failed saving $newfile: $!", $cleanup);
1081 rename($newfile, "$destdir/$file") ||
1082 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1088 sub will_render ($$;$) {
1093 # Important security check for independently created files.
1094 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1095 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1096 my $from_other_page=0;
1097 # Expensive, but rarely runs.
1098 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1101 dirname($_) eq $dest
1102 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1108 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1109 unless $from_other_page;
1112 # If $dest exists as a directory, remove conflicting files in it
1113 # rendered from other pages.
1115 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1116 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1117 if (dirname($f) eq $dest) {
1118 unlink("$config{destdir}/$f");
1119 rmdir(dirname("$config{destdir}/$f"));
1125 if (! $clear || $cleared{$page}) {
1126 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1129 foreach my $old (@{$renderedfiles{$page}}) {
1130 delete $destsources{$old};
1132 $renderedfiles{$page}=[$dest];
1135 $destsources{$dest}=$page;
1145 if ($link=~s/^\/+//) {
1153 $l.="/" if length $l;
1156 if (exists $pagesources{$l}) {
1159 elsif (exists $pagecase{lc $l}) {
1160 return $pagecase{lc $l};
1162 } while $cwd=~s{/?[^/]+$}{};
1164 if (length $config{userdir}) {
1165 my $l = "$config{userdir}/".lc($link);
1166 if (exists $pagesources{$l}) {
1169 elsif (exists $pagecase{lc $l}) {
1170 return $pagecase{lc $l};
1174 #print STDERR "warning: page $page, broken link: $link\n";
1178 sub isinlinableimage ($) {
1181 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1184 sub pagetitle ($;$) {
1186 my $unescaped=shift;
1189 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1192 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1200 # support use w/o %config set
1201 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1202 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1208 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1209 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1216 my $cgiurl=$local_cgiurl;
1218 if (exists $params{cgiurl}) {
1219 $cgiurl=$params{cgiurl};
1220 delete $params{cgiurl};
1228 join("&", map $_."=".uri_escape_utf8($params{$_}), sort(keys %params));
1231 sub cgiurl_abs (@) {
1233 URI->new_abs(cgiurl(@_), $config{cgiurl});
1239 return $local_url if ! defined $page;
1241 $page=htmlpage($page);
1243 $page=~s/[^\/]+\//..\//g;
1251 return $url unless defined $urlbase && length $urlbase;
1254 URI->new_abs($url, $urlbase)->as_string;
1258 # Work around very innefficient behavior in File::Spec if abs2rel
1259 # is passed two relative paths. It's much faster if paths are
1260 # absolute! (Debian bug #376658; fixed in debian unstable now)
1265 my $ret=File::Spec->abs2rel($path, $base);
1266 $ret=~s/^// if defined $ret;
1270 sub displaytime ($;$$) {
1271 # Plugins can override this function to mark up the time to
1273 my $time=formattime($_[0], $_[1]);
1274 if ($config{html5}) {
1275 return '<time datetime="'.date_3339($_[0]).'"'.
1276 ($_[2] ? ' pubdate="pubdate"' : '').
1277 '>'.$time.'</time>';
1280 return '<span class="date">'.$time.'</span>';
1284 sub formattime ($;$) {
1285 # Plugins can override this function to format the time.
1288 if (! defined $format) {
1289 $format=$config{timeformat};
1292 return strftime_utf8($format, localtime($time));
1295 my $strftime_encoding;
1297 # strftime doesn't know about encodings, so make sure
1298 # its output is properly treated as utf8.
1299 # Note that this does not handle utf-8 in the format string.
1300 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1301 unless defined $strftime_encoding;
1303 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1304 : POSIX::strftime(@_);
1310 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1311 POSIX::setlocale(&POSIX::LC_TIME, "C");
1312 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1313 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1317 sub beautify_urlpath ($) {
1320 # Ensure url is not an empty link, and if necessary,
1321 # add ./ to avoid colon confusion.
1322 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1326 if ($config{usedirs}) {
1327 $url =~ s!/index.$config{htmlext}$!/!;
1342 if (! $destsources{$to}) {
1347 return $config{url}.beautify_urlpath("/".$to);
1350 if (! defined $from) {
1351 my $u = $local_url || '';
1353 return $u.beautify_urlpath("/".$to);
1356 my $link = abs2rel($to, dirname(htmlpage($from)));
1358 return beautify_urlpath($link);
1361 sub isselflink ($$) {
1362 # Plugins can override this function to support special types
1367 return $page eq $link;
1370 sub htmllink ($$$;@) {
1371 my $lpage=shift; # the page doing the linking
1372 my $page=shift; # the page that will contain the link (different for inline)
1379 if (! $opts{forcesubpage}) {
1380 $bestlink=bestlink($lpage, $link);
1383 $bestlink="$lpage/".lc($link);
1387 if (defined $opts{linktext}) {
1388 $linktext=$opts{linktext};
1391 $linktext=pagetitle(basename($link));
1394 return "<span class=\"selflink\">$linktext</span>"
1395 if length $bestlink && isselflink($page, $bestlink) &&
1396 ! defined $opts{anchor};
1398 if (! $destsources{$bestlink}) {
1399 $bestlink=htmlpage($bestlink);
1401 if (! $destsources{$bestlink}) {
1403 if (length $config{cgiurl}) {
1404 $cgilink = "<a href=\"".
1409 )."\" rel=\"nofollow\">?</a>";
1411 return "<span class=\"createlink\">$cgilink$linktext</span>"
1415 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1416 $bestlink=beautify_urlpath($bestlink);
1418 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1419 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1422 if (defined $opts{anchor}) {
1423 $bestlink.="#".$opts{anchor};
1427 foreach my $attr (qw{rel class title}) {
1428 if (defined $opts{$attr}) {
1429 push @attrs, " $attr=\"$opts{$attr}\"";
1433 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1438 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1441 # Username to display for openid accounts.
1442 sub openiduser ($) {
1445 if (defined $user && $user =~ m!^https?://! &&
1446 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1449 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1450 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1453 # backcompat with old version
1454 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1455 $display=$oid->display;
1458 # Convert "user.somehost.com" to "user [somehost.com]"
1459 # (also "user.somehost.co.uk")
1460 if ($display !~ /\[/) {
1461 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1463 # Convert "http://somehost.com/user" to "user [somehost.com]".
1464 # (also "https://somehost.com/user/")
1465 if ($display !~ /\[/) {
1466 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1468 $display=~s!^https?://!!; # make sure this is removed
1469 eval q{use CGI 'escapeHTML'};
1471 return escapeHTML($display);
1476 # Username to display for emailauth accounts.
1479 if (defined $user && $user =~ m/(.+)@/) {
1481 # remove any characters from not allowed in wiki files
1482 # support use w/o %config set
1483 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1484 $nick=~s/[^$chars]/_/g;
1490 # Some user information should not be exposed in commit metadata, etc.
1491 # This generates a cloaked form of such information.
1494 # cloak email address using http://xmlns.com/foaf/spec/#term_mbox_sha1sum
1495 if ($user=~m/(.+)@/) {
1497 eval q{use Digest::SHA};
1499 return $nick.'@'.Digest::SHA::sha1_hex("mailto:$user");
1506 sub htmlize ($$$$) {
1512 my $oneline = $content !~ /\n/;
1514 if (exists $hooks{htmlize}{$type}) {
1515 $content=$hooks{htmlize}{$type}{call}->(
1517 content => $content,
1521 error("htmlization of $type not supported");
1524 run_hooks(sanitize => sub {
1527 destpage => $destpage,
1528 content => $content,
1533 # hack to get rid of enclosing junk added by markdown
1534 # and other htmlizers/sanitizers
1535 $content=~s/^<p>//i;
1536 $content=~s/<\/p>\n*$//i;
1547 run_hooks(linkify => sub {
1550 destpage => $destpage,
1551 content => $content,
1559 our $preprocess_preview=0;
1560 sub preprocess ($$$;$$) {
1561 my $page=shift; # the page the data comes from
1562 my $destpage=shift; # the page the data will appear in (different for inline)
1567 # Using local because it needs to be set within any nested calls
1569 local $preprocess_preview=$preview if defined $preview;
1576 $params="" if ! defined $params;
1578 if (length $escape) {
1579 return "[[$prefix$command $params]]";
1581 elsif (exists $hooks{preprocess}{$command}) {
1582 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1583 # Note: preserve order of params, some plugins may
1584 # consider it significant.
1586 while ($params =~ m{
1587 (?:([-.\w]+)=)? # 1: named parameter key?
1589 """(.*?)""" # 2: triple-quoted value
1591 "([^"]*?)" # 3: single-quoted value
1593 '''(.*?)''' # 4: triple-single-quote
1595 <<([a-zA-Z]+)\n # 5: heredoc start
1596 (.*?)\n\5 # 6: heredoc value
1598 (\S+) # 7: unquoted value
1600 (?:\s+|$) # delimiter to next param
1610 elsif (defined $3) {
1613 elsif (defined $4) {
1616 elsif (defined $7) {
1619 elsif (defined $6) {
1624 push @params, $key, $val;
1627 push @params, $val, '';
1630 if ($preprocessing{$page}++ > 8) {
1631 # Avoid loops of preprocessed pages preprocessing
1632 # other pages that preprocess them, etc.
1633 return "[[!$command <span class=\"error\">".
1634 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1635 $page, $preprocessing{$page}).
1641 $hooks{preprocess}{$command}{call}->(
1644 destpage => $destpage,
1645 preview => $preprocess_preview,
1651 $ret="[[!$command <span class=\"error\">".
1652 gettext("Error").": $error"."</span>]]";
1656 # use void context during scan pass
1658 $hooks{preprocess}{$command}{call}->(
1661 destpage => $destpage,
1662 preview => $preprocess_preview,
1667 $preprocessing{$page}--;
1671 return "[[$prefix$command $params]]";
1676 if ($config{prefix_directives}) {
1679 \[\[(!) # directive open; 2: prefix
1680 ([-\w]+) # 3: command
1681 ( # 4: the parameters..
1682 \s+ # Must have space if parameters present
1684 (?:[-.\w]+=)? # named parameter key?
1686 """.*?""" # triple-quoted value
1688 "[^"]*?" # single-quoted value
1690 '''.*?''' # triple-single-quote
1692 <<([a-zA-Z]+)\n # 5: heredoc start
1693 (?:.*?)\n\5 # heredoc value
1695 [^"\s\]]+ # unquoted value
1697 \s* # whitespace or end
1700 *)? # 0 or more parameters
1701 \]\] # directive closed
1707 \[\[(!?) # directive open; 2: optional prefix
1708 ([-\w]+) # 3: command
1710 ( # 4: the parameters..
1712 (?:[-.\w]+=)? # named parameter key?
1714 """.*?""" # triple-quoted value
1716 "[^"]*?" # single-quoted value
1718 '''.*?''' # triple-single-quote
1720 <<([a-zA-Z]+)\n # 5: heredoc start
1721 (?:.*?)\n\5 # heredoc value
1723 [^"\s\]]+ # unquoted value
1725 \s* # whitespace or end
1728 *) # 0 or more parameters
1729 \]\] # directive closed
1733 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1742 run_hooks(filter => sub {
1743 $content=shift->(page => $page, destpage => $destpage,
1744 content => $content);
1750 sub check_canedit ($$$;$) {
1757 run_hooks(canedit => sub {
1758 return if defined $canedit;
1759 my $ret=shift->($page, $q, $session);
1764 elsif (ref $ret eq 'CODE') {
1765 $ret->() unless $nonfatal;
1768 elsif (defined $ret) {
1769 error($ret) unless $nonfatal;
1774 return defined $canedit ? $canedit : 1;
1777 sub check_content (@) {
1780 return 1 if ! exists $hooks{checkcontent}; # optimisation
1782 if (exists $pagesources{$params{page}}) {
1784 my %old=map { $_ => 1 }
1785 split("\n", readfile(srcfile($pagesources{$params{page}})));
1786 foreach my $line (split("\n", $params{content})) {
1787 push @diff, $line if ! exists $old{$line};
1789 $params{diff}=join("\n", @diff);
1793 run_hooks(checkcontent => sub {
1794 return if defined $ok;
1795 my $ret=shift->(%params);
1800 elsif (ref $ret eq 'CODE') {
1801 $ret->() unless $params{nonfatal};
1804 elsif (defined $ret) {
1805 error($ret) unless $params{nonfatal};
1811 return defined $ok ? $ok : 1;
1814 sub check_canchange (@) {
1816 my $cgi = $params{cgi};
1817 my $session = $params{session};
1818 my @changes = @{$params{changes}};
1821 foreach my $change (@changes) {
1822 # This untaint is safe because we check file_pruned and
1824 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1825 $file=possibly_foolish_untaint($file);
1826 if (! defined $file || ! length $file ||
1827 file_pruned($file)) {
1828 error(gettext("bad file name %s"), $file);
1831 my $type=pagetype($file);
1832 my $page=pagename($file) if defined $type;
1834 if ($change->{action} eq 'add') {
1838 if ($change->{action} eq 'change' ||
1839 $change->{action} eq 'add') {
1840 if (defined $page) {
1841 check_canedit($page, $cgi, $session);
1845 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1846 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1847 check_canedit($file, $cgi, $session);
1852 elsif ($change->{action} eq 'remove') {
1853 # check_canremove tests to see if the file is present
1854 # on disk. This will fail when a single commit adds a
1855 # file and then removes it again. Avoid the problem
1856 # by not testing the removal in such pairs of changes.
1857 # (The add is still tested, just to make sure that
1858 # no data is added to the repo that a web edit
1860 next if $newfiles{$file};
1862 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1863 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1864 check_canedit(defined $page ? $page : $file, $cgi, $session);
1869 error "unknown action ".$change->{action};
1872 error sprintf(gettext("you are not allowed to change %s"), $file);
1880 # Take an exclusive lock on the wiki to prevent multiple concurrent
1881 # run issues. The lock will be dropped on program exit.
1882 if (! -d $config{wikistatedir}) {
1883 mkdir($config{wikistatedir});
1885 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1886 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1887 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1888 debug("failed to get lock; waiting...");
1889 if (! flock($wikilock, LOCK_EX)) {
1890 error("failed to get lock");
1897 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1898 return close($wikilock) if $wikilock;
1904 sub commit_hook_enabled () {
1905 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1906 error("cannot write to $config{wikistatedir}/commitlock: $!");
1907 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1908 close($commitlock) || error("failed closing commitlock: $!");
1911 close($commitlock) || error("failed closing commitlock: $!");
1915 sub disable_commit_hook () {
1916 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1917 error("cannot write to $config{wikistatedir}/commitlock: $!");
1918 if (! flock($commitlock, 2)) { # LOCK_EX
1919 error("failed to get commit lock");
1924 sub enable_commit_hook () {
1925 return close($commitlock) if $commitlock;
1930 %oldrenderedfiles=%pagectime=();
1931 my $rebuild=$config{rebuild};
1933 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1934 %destsources=%renderedfiles=%pagecase=%pagestate=
1935 %depends_simple=%typedlinks=%oldtypedlinks=();
1938 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1939 if (-e "$config{wikistatedir}/index") {
1940 system("ikiwiki-transition", "indexdb", $config{srcdir});
1941 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1944 # gettime on first build
1945 $config{gettime}=1 unless defined $config{gettime};
1950 my $index=Storable::fd_retrieve($in);
1951 if (! defined $index) {
1956 if (exists $index->{version} && ! ref $index->{version}) {
1957 $pages=$index->{page};
1958 %wikistate=%{$index->{state}};
1959 # Handle plugins that got disabled by loading a new setup.
1960 if (exists $config{setupfile}) {
1961 require IkiWiki::Setup;
1962 IkiWiki::Setup::disabled_plugins(
1963 grep { ! $loaded_plugins{$_} } keys %wikistate);
1971 foreach my $src (keys %$pages) {
1972 my $d=$pages->{$src};
1974 if (exists $d->{page} && ! $rebuild) {
1978 $page=pagename($src);
1980 $pagectime{$page}=$d->{ctime};
1981 $pagesources{$page}=$src;
1983 $pagemtime{$page}=$d->{mtime};
1984 $renderedfiles{$page}=$d->{dest};
1985 if (exists $d->{links} && ref $d->{links}) {
1986 $links{$page}=$d->{links};
1987 $oldlinks{$page}=[@{$d->{links}}];
1989 if (ref $d->{depends_simple} eq 'ARRAY') {
1991 $depends_simple{$page}={
1992 map { $_ => 1 } @{$d->{depends_simple}}
1995 elsif (exists $d->{depends_simple}) {
1996 $depends_simple{$page}=$d->{depends_simple};
1998 if (exists $d->{dependslist}) {
2001 map { $_ => $DEPEND_CONTENT }
2002 @{$d->{dependslist}}
2005 elsif (exists $d->{depends} && ! ref $d->{depends}) {
2007 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
2009 elsif (exists $d->{depends}) {
2010 $depends{$page}=$d->{depends};
2012 if (exists $d->{state}) {
2013 $pagestate{$page}=$d->{state};
2015 if (exists $d->{typedlinks}) {
2016 $typedlinks{$page}=$d->{typedlinks};
2018 while (my ($type, $links) = each %{$typedlinks{$page}}) {
2019 next unless %$links;
2020 $oldtypedlinks{$page}{$type} = {%$links};
2024 $oldrenderedfiles{$page}=[@{$d->{dest}}];
2026 foreach my $page (keys %pagesources) {
2027 $pagecase{lc $page}=$page;
2029 foreach my $page (keys %renderedfiles) {
2030 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
2032 $lastrev=$index->{lastrev};
2033 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
2038 run_hooks(savestate => sub { shift->() });
2040 my @plugins=keys %loaded_plugins;
2042 if (! -d $config{wikistatedir}) {
2043 mkdir($config{wikistatedir});
2045 my $newfile="$config{wikistatedir}/indexdb.new";
2046 my $cleanup = sub { unlink($newfile) };
2047 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
2050 foreach my $page (keys %pagemtime) {
2051 next unless $pagemtime{$page};
2052 my $src=$pagesources{$page};
2054 $index{page}{$src}={
2056 ctime => $pagectime{$page},
2057 mtime => $pagemtime{$page},
2058 dest => $renderedfiles{$page},
2059 links => $links{$page},
2062 if (exists $depends{$page}) {
2063 $index{page}{$src}{depends} = $depends{$page};
2066 if (exists $depends_simple{$page}) {
2067 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2070 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2071 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2074 if (exists $pagestate{$page}) {
2075 $index{page}{$src}{state}=$pagestate{$page};
2080 foreach my $id (@plugins) {
2081 $index{state}{$id}={}; # used to detect disabled plugins
2082 foreach my $key (keys %{$wikistate{$id}}) {
2083 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2087 $index{lastrev}=$lastrev;
2088 $index{underlayfiles}=\@underlayfiles;
2090 $index{version}="3";
2091 my $ret=Storable::nstore_fd(\%index, $out);
2092 return if ! defined $ret || ! $ret;
2093 close $out || error("failed saving to $newfile: $!", $cleanup);
2094 rename($newfile, "$config{wikistatedir}/indexdb") ||
2095 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2100 sub template_file ($) {
2103 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2105 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2106 $template=srcfile($pagesources{$tpage}, 1);
2110 $template=srcfile($tpage, 1);
2113 if (defined $template) {
2114 return $template, $tpage, 1 if wantarray;
2118 $name=~s:/::; # avoid path traversal
2119 foreach my $dir ($config{templatedir},
2120 "$installdir/share/ikiwiki/templates") {
2121 if (-e "$dir/$name") {
2122 $template="$dir/$name";
2126 if (defined $template) {
2127 return $template, $tpage if wantarray;
2135 sub template_depends ($$;@) {
2139 my ($filename, $tpage, $untrusted)=template_file($name);
2140 if (! defined $filename) {
2141 error(sprintf(gettext("template %s not found"), $name))
2144 if (defined $page && defined $tpage) {
2145 add_depends($page, $tpage);
2150 my $text_ref = shift;
2151 ${$text_ref} = decode_utf8(${$text_ref});
2152 run_hooks(readtemplate => sub {
2153 ${$text_ref} = shift->(
2156 content => ${$text_ref},
2157 untrusted => $untrusted,
2161 loop_context_vars => 1,
2162 die_on_bad_params => 0,
2163 parent_global_vars => 1,
2164 filename => $filename,
2166 ($untrusted ? (no_includes => 1) : ()),
2168 return @opts if wantarray;
2170 require HTML::Template;
2171 return HTML::Template->new(@opts);
2174 sub template ($;@) {
2175 template_depends(shift, undef, @_);
2178 sub templateactions ($$) {
2184 run_hooks(pageactions => sub {
2185 push @actions, map { { action => $_ } }
2186 grep { defined } shift->(page => $page);
2188 $template->param(actions => \@actions);
2190 if ($config{cgiurl} && exists $hooks{auth}) {
2191 $template->param(prefsurl => cgiurl(do => "prefs"));
2195 if ($have_actions || @actions) {
2196 $template->param(have_actions => 1);
2203 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2204 error 'hook requires type, call, and id parameters';
2207 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2209 $hooks{$param{type}}{$param{id}}=\%param;
2213 sub run_hooks ($$) {
2214 # Calls the given sub for each hook of the given type,
2215 # passing it the hook function to call.
2219 if (exists $hooks{$type}) {
2220 my (@first, @middle, @last);
2221 foreach my $id (keys %{$hooks{$type}}) {
2222 if ($hooks{$type}{$id}{first}) {
2225 elsif ($hooks{$type}{$id}{last}) {
2232 foreach my $id (@first, @middle, @last) {
2233 $sub->($hooks{$type}{$id}{call});
2241 $hooks{rcs}{rcs_update}{call}->(@_);
2244 sub rcs_prepedit ($) {
2245 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2248 sub rcs_commit (@) {
2249 $hooks{rcs}{rcs_commit}{call}->(@_);
2252 sub rcs_commit_staged (@) {
2253 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2257 $hooks{rcs}{rcs_add}{call}->(@_);
2260 sub rcs_remove ($) {
2261 $hooks{rcs}{rcs_remove}{call}->(@_);
2264 sub rcs_rename ($$) {
2265 $hooks{rcs}{rcs_rename}{call}->(@_);
2268 sub rcs_recentchanges ($) {
2269 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2272 sub rcs_diff ($;$) {
2273 $hooks{rcs}{rcs_diff}{call}->(@_);
2276 sub rcs_getctime ($) {
2277 $hooks{rcs}{rcs_getctime}{call}->(@_);
2280 sub rcs_getmtime ($) {
2281 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2284 sub rcs_receive () {
2285 $hooks{rcs}{rcs_receive}{call}->();
2288 sub add_depends ($$;$) {
2291 my $deptype=shift || $DEPEND_CONTENT;
2293 # Is the pagespec a simple page name?
2294 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2295 $pagespec !~ /[\s*?()!]/) {
2296 $depends_simple{$page}{lc $pagespec} |= $deptype;
2300 # Add explicit dependencies for influences.
2301 my $sub=pagespec_translate($pagespec);
2302 return unless defined $sub;
2303 foreach my $p (keys %pagesources) {
2304 my $r=$sub->($p, location => $page);
2305 my $i=$r->influences;
2306 my $static=$r->influences_static;
2307 foreach my $k (keys %$i) {
2308 next unless $r || $static || $k eq $page;
2309 $depends_simple{$page}{lc $k} |= $i->{$k};
2314 $depends{$page}{$pagespec} |= $deptype;
2320 foreach my $type (@_) {
2321 if ($type eq 'presence') {
2322 $deptype |= $DEPEND_PRESENCE;
2324 elsif ($type eq 'links') {
2325 $deptype |= $DEPEND_LINKS;
2327 elsif ($type eq 'content') {
2328 $deptype |= $DEPEND_CONTENT;
2334 my $file_prune_regexp;
2335 sub file_pruned ($) {
2338 if (defined $config{include} && length $config{include}) {
2339 return 0 if $file =~ m/$config{include}/;
2342 if (! defined $file_prune_regexp) {
2343 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2344 $file_prune_regexp=qr/$file_prune_regexp/;
2346 return $file =~ m/$file_prune_regexp/;
2349 sub define_gettext () {
2350 # If translation is needed, redefine the gettext function to do it.
2351 # Otherwise, it becomes a quick no-op.
2354 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2355 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2356 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2358 $gettext_obj=eval q{
2359 use Locale::gettext q{textdomain};
2360 Locale::gettext->domain('ikiwiki')
2365 no warnings 'redefine';
2367 $getobj->() if $getobj;
2369 $gettext_obj->get(shift);
2376 $getobj->() if $getobj;
2378 $gettext_obj->nget(@_);
2381 return ($_[2] == 1 ? $_[0] : $_[1])
2399 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2403 # Injects a new function into the symbol table to replace an
2404 # exported function.
2407 # This is deep ugly perl foo, beware.
2410 if (! defined $params{parent}) {
2411 $params{parent}='::';
2412 $params{old}=\&{$params{name}};
2413 $params{name}=~s/.*:://;
2415 my $parent=$params{parent};
2416 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2417 $ns = $params{parent} . $ns;
2418 inject(%params, parent => $ns) unless $ns eq '::main::';
2419 *{$ns . $params{name}} = $params{call}
2420 if exists ${$ns}{$params{name}} &&
2421 \&{${$ns}{$params{name}}} == $params{old};
2427 sub add_link ($$;$) {
2432 push @{$links{$page}}, $link
2433 unless grep { $_ eq $link } @{$links{$page}};
2435 if (defined $type) {
2436 $typedlinks{$page}{$type}{$link} = 1;
2440 sub add_autofile ($$$) {
2443 my $generator=shift;
2445 $autofiles{$file}{plugin}=$plugin;
2446 $autofiles{$file}{generator}=$generator;
2450 return LWP::UserAgent->new(
2451 cookie_jar => $config{cookiejar},
2452 env_proxy => 1, # respect proxy env vars
2453 agent => $config{useragent},
2457 sub sortspec_translate ($$) {
2459 my $reverse = shift;
2465 (-?) # group 1: perhaps negated
2468 \w+\([^\)]*\) # command(params)
2470 [^\s]+ # or anything else
2478 if ($word =~ m/^(\w+)\((.*)\)$/) {
2479 # command with parameters
2483 elsif ($word !~ m/^\w+$/) {
2484 error(sprintf(gettext("invalid sort type %s"), $word));
2495 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2496 if (defined $params) {
2497 push @data, $params;
2498 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2501 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2505 error(sprintf(gettext("unknown sort type %s"), $word));
2509 if (! length $code) {
2510 # undefined sorting method... sort arbitrarily
2519 return eval 'sub { '.$code.' }';
2522 sub pagespec_translate ($) {
2525 # Convert spec to perl code.
2529 \s* # ignore whitespace
2530 ( # 1: match a single word
2537 \w+\([^\)]*\) # command(params)
2539 [^\s()]+ # any other text
2541 \s* # ignore whitespace
2544 if (lc $word eq 'and') {
2547 elsif (lc $word eq 'or') {
2550 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2553 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2554 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2556 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2559 push @data, qq{unknown function in pagespec "$word"};
2560 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2565 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2569 if (! length $code) {
2570 $code="IkiWiki::FailReason->new('empty pagespec')";
2574 return eval 'sub { my $page=shift; '.$code.' }';
2577 sub pagespec_match ($$;@) {
2582 # Backwards compatability with old calling convention.
2584 unshift @params, 'location';
2587 my $sub=pagespec_translate($spec);
2588 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2590 return $sub->($page, @params);
2593 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2595 # Not exported yet, but could be in future if it is generally useful.
2596 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2597 # which is "more internal".
2598 sub sort_pages ($$;@) {
2602 $sort = sortspec_translate($sort, $params{reverse});
2603 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2606 sub pagespec_match_list ($$;@) {
2611 # Backwards compatability with old calling convention.
2613 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2614 $params{list}=$page;
2615 $page=$params{location}; # ugh!
2618 my $sub=pagespec_translate($pagespec);
2619 error "syntax error in pagespec \"$pagespec\""
2621 my $sort=sortspec_translate($params{sort}, $params{reverse})
2622 if defined $params{sort};
2625 if (exists $params{list}) {
2626 @candidates=exists $params{filter}
2627 ? grep { ! $params{filter}->($_) } @{$params{list}}
2631 @candidates=exists $params{filter}
2632 ? grep { ! $params{filter}->($_) } keys %pagesources
2633 : keys %pagesources;
2636 # clear params, remainder is passed to pagespec
2637 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2638 my $num=$params{num};
2639 delete @params{qw{num deptype reverse sort filter list}};
2641 # when only the top matches will be returned, it's efficient to
2642 # sort before matching to pagespec,
2643 if (defined $num && defined $sort) {
2644 @candidates=IkiWiki::SortSpec::sort_pages(
2645 $sort, @candidates);
2651 my $accum=IkiWiki::SuccessReason->new();
2652 foreach my $p (@candidates) {
2653 my $r=$sub->($p, %params, location => $page);
2654 error(sprintf(gettext("cannot match pages: %s"), $r))
2655 if $r->isa("IkiWiki::ErrorReason");
2656 unless ($r || $r->influences_static) {
2657 $r->remove_influence($p);
2662 last if defined $num && ++$count == $num;
2666 # Add simple dependencies for accumulated influences.
2667 my $i=$accum->influences;
2668 foreach my $k (keys %$i) {
2669 $depends_simple{$page}{lc $k} |= $i->{$k};
2672 # when all matches will be returned, it's efficient to
2673 # sort after matching
2674 if (! defined $num && defined $sort) {
2675 return IkiWiki::SortSpec::sort_pages(
2683 sub pagespec_valid ($) {
2686 return defined pagespec_translate($spec);
2690 my $re=quotemeta(shift);
2696 package IkiWiki::FailReason;
2699 '""' => sub { $_[0][0] },
2701 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2702 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2703 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2707 our @ISA = 'IkiWiki::SuccessReason';
2709 package IkiWiki::SuccessReason;
2711 # A blessed array-ref:
2713 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2715 # - if absent or false, the influences of this evaluation are "static",
2716 # see the influences_static method
2717 # - if true, they are dynamic (not static)
2718 # [1]{any other key}:
2719 # the dependency types of influences, as returned by the influences method
2722 # in string context, it's the human-readable reason
2723 '""' => sub { $_[0][0] },
2724 # in boolean context, SuccessReason is 1 and FailReason is 0
2726 # negating a result gives the opposite result with the same influences
2727 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2728 # A & B = (A ? B : A) with the influences of both
2729 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2730 # A | B = (A ? A : B) with the influences of both
2731 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2735 # SuccessReason->new("human-readable reason", page => deptype, ...)
2740 return bless [$value, {@_}], $class;
2743 # influences(): return a reference to a copy of the hash
2744 # { page => dependency type } describing the pages that indirectly influenced
2745 # this result, but would not cause a dependency through ikiwiki's core
2748 # See [[todo/dependency_types]] for extensive discussion of what this means.
2750 # influences(page => deptype, ...): remove all influences, replace them
2751 # with the arguments, and return a reference to a copy of the new influences.
2755 $this->[1]={@_} if @_;
2756 my %i=%{$this->[1]};
2761 # True if this result has the same influences whichever page it matches,
2762 # For instance, whether bar matches backlink(foo) is influenced only by
2763 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2764 # which does not mention bar anywhere.
2766 # False if this result would have different influences when matching
2767 # different pages. For instance, when testing whether link(foo) matches bar,
2768 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2769 # bar's links could change the outcome; so its influences are not the same
2770 # as when testing whether link(foo) matches baz.
2772 # Static influences are one of the things that make pagespec_match_list
2773 # more efficient than repeated calls to pagespec_match.
2775 sub influences_static {
2776 return ! $_[0][1]->{""};
2779 # Change the influences of $this to be the influences of "$this & $other"
2780 # or "$this | $other".
2782 # If both $this and $other are either successful or have influences,
2783 # or this is an "or" operation, the result has all the influences from
2784 # either of the arguments. It has dynamic influences if either argument
2785 # has dynamic influences.
2787 # If this is an "and" operation, and at least one argument is a
2788 # FailReason with no influences, the result has no influences, and they
2789 # are not dynamic. For instance, link(foo) matching bar is influenced
2790 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2791 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2792 # bar, because it would be false however often you edit bar.
2794 sub merge_influences {
2799 # This "if" is odd because it needs to avoid negating $this
2800 # or $other, which would alter the objects in-place. Be careful.
2801 if (! $anded || (($this || %{$this->[1]}) &&
2802 ($other || %{$other->[1]}))) {
2803 foreach my $influence (keys %{$other->[1]}) {
2804 $this->[1]{$influence} |= $other->[1]{$influence};
2813 # Change $this so it is not considered to be influenced by $torm.
2815 sub remove_influence {
2819 delete $this->[1]{$torm};
2822 package IkiWiki::ErrorReason;
2824 our @ISA = 'IkiWiki::FailReason';
2826 package IkiWiki::PageSpec;
2832 if ($path =~ m!^\.(/|$)!) {
2834 $from=~s#/?[^/]+$## if defined $from;
2836 $path="$from/$path" if defined $from && length $from;
2840 $path = "" unless defined $path;
2849 sub match_glob ($$;@) {
2854 $glob=derel($glob, $params{location});
2856 # Instead of converting the glob to a regex every time,
2857 # cache the compiled regex to save time.
2858 my $re=$glob_cache{$glob};
2859 unless (defined $re) {
2860 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2863 if (! IkiWiki::isinternal($page) || $params{internal}) {
2864 return IkiWiki::SuccessReason->new("$glob matches $page");
2867 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2871 return IkiWiki::FailReason->new("$glob does not match $page");
2875 sub match_internal ($$;@) {
2876 return match_glob(shift, shift, @_, internal => 1)
2879 sub match_page ($$;@) {
2881 my $match=match_glob($page, shift, @_);
2883 my $source=exists $IkiWiki::pagesources{$page} ?
2884 $IkiWiki::pagesources{$page} :
2885 $IkiWiki::delpagesources{$page};
2886 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2887 if (! defined $type) {
2888 return IkiWiki::FailReason->new("$page is not a page");
2894 sub match_link ($$;@) {
2899 $link=derel($link, $params{location});
2900 my $from=exists $params{location} ? $params{location} : '';
2901 my $linktype=$params{linktype};
2903 if (defined $linktype) {
2904 $qualifier=" with type $linktype";
2907 my $links = $IkiWiki::links{$page};
2908 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2909 unless $links && @{$links};
2910 my $bestlink = IkiWiki::bestlink($from, $link);
2911 foreach my $p (@{$links}) {
2912 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2914 if (length $bestlink) {
2915 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2916 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2920 if (match_glob($p, $link, %params)) {
2921 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2923 my ($p_rel)=$p=~/^\/?(.*)/;
2925 if (match_glob($p_rel, $link, %params)) {
2926 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2930 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2933 sub match_backlink ($$;@) {
2937 if ($testpage eq '.') {
2938 $testpage = $params{'location'}
2940 my $ret=match_link($testpage, $page, @_);
2941 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2945 sub match_created_before ($$;@) {
2950 $testpage=derel($testpage, $params{location});
2952 if (exists $IkiWiki::pagectime{$testpage}) {
2953 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2954 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2957 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2961 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2965 sub match_created_after ($$;@) {
2970 $testpage=derel($testpage, $params{location});
2972 if (exists $IkiWiki::pagectime{$testpage}) {
2973 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2974 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2977 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2981 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2985 sub match_creation_day ($$;@) {
2988 if ($d !~ /^\d+$/) {
2989 return IkiWiki::ErrorReason->new("invalid day $d");
2991 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2992 return IkiWiki::SuccessReason->new('creation_day matched');
2995 return IkiWiki::FailReason->new('creation_day did not match');
2999 sub match_creation_month ($$;@) {
3002 if ($m !~ /^\d+$/) {
3003 return IkiWiki::ErrorReason->new("invalid month $m");
3005 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
3006 return IkiWiki::SuccessReason->new('creation_month matched');
3009 return IkiWiki::FailReason->new('creation_month did not match');
3013 sub match_creation_year ($$;@) {
3016 if ($y !~ /^\d+$/) {
3017 return IkiWiki::ErrorReason->new("invalid year $y");
3019 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
3020 return IkiWiki::SuccessReason->new('creation_year matched');
3023 return IkiWiki::FailReason->new('creation_year did not match');
3027 sub match_user ($$;@) {
3032 if (! exists $params{user}) {
3033 return IkiWiki::ErrorReason->new("no user specified");
3036 my $regexp=IkiWiki::glob2re($user);
3038 if (defined $params{user} && $params{user}=~$regexp) {
3039 return IkiWiki::SuccessReason->new("user is $user");
3041 elsif (! defined $params{user}) {
3042 return IkiWiki::FailReason->new("not logged in");
3045 return IkiWiki::FailReason->new("user is $params{user}, not $user");
3049 sub match_admin ($$;@) {
3054 if (! exists $params{user}) {
3055 return IkiWiki::ErrorReason->new("no user specified");
3058 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3059 return IkiWiki::SuccessReason->new("user is an admin");
3061 elsif (! defined $params{user}) {
3062 return IkiWiki::FailReason->new("not logged in");
3065 return IkiWiki::FailReason->new("user is not an admin");
3069 sub match_ip ($$;@) {
3074 if (! exists $params{ip}) {
3075 return IkiWiki::ErrorReason->new("no IP specified");
3078 my $regexp=IkiWiki::glob2re(lc $ip);
3080 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3081 return IkiWiki::SuccessReason->new("IP is $ip");
3084 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3088 package IkiWiki::SortSpec;
3090 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3091 # are easily available in this namespace, for cmp functions to use them.
3098 IkiWiki::pagetitle(IkiWiki::basename($a))
3100 IkiWiki::pagetitle(IkiWiki::basename($b))
3103 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3104 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3105 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }