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}/.ikiwiki/",
365 description => "extra library and plugin directory",
367 safe => 0, # directory
373 description => "environment variables",
374 safe => 0, # paranoia
380 example => "US/Eastern",
381 description => "time zone name",
388 example => '^\.htaccess$',
389 description => "regexp of normally excluded files to include",
397 example => '^(*\.private|Makefile)$',
398 description => "regexp of files that should be skipped",
403 wiki_file_prune_regexps => {
405 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
406 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
407 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
408 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
409 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
410 description => "regexps of source files to ignore",
416 description => "specifies the characters that are allowed in source filenames",
417 default => "-[:alnum:]+/.:_",
421 wiki_file_regexp => {
423 description => "regexp of legal source files",
427 web_commit_regexp => {
429 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
430 description => "regexp to parse web commits from logs",
437 description => "run as a cgi",
441 cgi_disable_uploads => {
444 description => "whether CGI should accept file uploads",
451 description => "run as a post-commit hook",
458 description => "running in rebuild mode",
465 description => "running in setup mode",
472 description => "running in clean mode",
479 description => "running in refresh mode",
486 description => "running in receive test mode",
490 wrapper_background_command => {
493 description => "background shell command to run",
499 description => "running in gettime mode",
506 description => "running in w3mmode",
513 description => "path to the .ikiwiki directory holding ikiwiki state",
520 description => "path to setup file",
527 description => "perl class to use to dump setup file",
531 allow_symlinks_before_srcdir => {
534 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
540 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
541 description => "cookie control",
542 safe => 0, # hooks into perl module internals
547 default => "ikiwiki/$version",
548 example => "Wget/1.13.4 (linux-gnu)",
549 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
553 responsive_layout => {
556 description => "theme has a responsive layout? (mobile-optimized)",
562 sub defaultconfig () {
565 foreach my $key (keys %s) {
566 push @ret, $key, $s{$key}->{default};
571 # URL to top of wiki as a path starting with /, valid from any wiki page or
572 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
574 # URL to CGI script, similar to $local_url
578 # locale stuff; avoid LC_ALL since it overrides everything
579 if (defined $ENV{LC_ALL}) {
580 $ENV{LANG} = $ENV{LC_ALL};
583 if (defined $config{locale}) {
584 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
585 $ENV{LANG}=$config{locale};
590 if (! defined $config{wiki_file_regexp}) {
591 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
594 if (ref $config{ENV} eq 'HASH') {
595 foreach my $val (keys %{$config{ENV}}) {
596 $ENV{$val}=$config{ENV}{$val};
599 if (defined $config{timezone} && length $config{timezone}) {
600 $ENV{TZ}=$config{timezone};
603 $config{timezone}=$ENV{TZ};
606 if ($config{w3mmode}) {
607 eval q{use Cwd q{abs_path}};
609 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
610 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
611 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
612 unless $config{cgiurl} =~ m!file:///!;
613 $config{url}="file://".$config{destdir};
616 if ($config{cgi} && ! length $config{url}) {
617 error(gettext("Must specify url to wiki with --url when using --cgi"));
620 if (defined $config{url} && length $config{url}) {
622 my $baseurl = URI->new($config{url});
624 $local_url = $baseurl->path . "/";
625 $local_cgiurl = undef;
627 if (length $config{cgiurl}) {
628 my $cgiurl = URI->new($config{cgiurl});
630 $local_cgiurl = $cgiurl->path;
632 if ($cgiurl->scheme eq 'https' &&
633 $baseurl->scheme eq 'http') {
634 # We assume that the same content is available
635 # over both http and https, because if it
636 # wasn't, accessing the static content
637 # from the CGI would be mixed-content,
638 # which would be a security flaw.
640 if ($cgiurl->authority ne $baseurl->authority) {
641 # use protocol-relative URL for
643 $local_url = "$config{url}/";
644 $local_url =~ s{^http://}{//};
646 # else use host-relative URL for static content
648 # either way, CGI needs to be absolute
649 $local_cgiurl = $config{cgiurl};
651 elsif ($cgiurl->scheme ne $baseurl->scheme) {
652 # too far apart, fall back to absolute URLs
653 $local_url = "$config{url}/";
654 $local_cgiurl = $config{cgiurl};
656 elsif ($cgiurl->authority ne $baseurl->authority) {
657 # slightly too far apart, fall back to
658 # protocol-relative URLs
659 $local_url = "$config{url}/";
660 $local_url =~ s{^https?://}{//};
661 $local_cgiurl = $config{cgiurl};
662 $local_cgiurl =~ s{^https?://}{//};
664 # else keep host-relative URLs
667 $local_url =~ s{//$}{/};
670 $local_cgiurl = $config{cgiurl};
673 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
674 unless exists $config{wikistatedir} && defined $config{wikistatedir};
676 if (defined $config{umask}) {
677 my $u = possibly_foolish_untaint($config{umask});
679 if ($u =~ m/^\d+$/) {
682 elsif ($u eq 'private') {
685 elsif ($u eq 'group') {
688 elsif ($u eq 'public') {
692 error(sprintf(gettext("unsupported umask setting %s"), $u));
696 run_hooks(checkconfig => sub { shift->() });
704 foreach my $dir (@INC, $config{libdir}) {
705 next unless defined $dir && length $dir;
706 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
707 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
711 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
712 next unless defined $dir && length $dir;
713 foreach my $file (glob("$dir/plugins/*")) {
714 $ret{basename($file)}=1 if -x $file;
722 if (defined $config{libdir} && length $config{libdir}) {
723 unshift @INC, possibly_foolish_untaint($config{libdir});
726 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
731 if (exists $hooks{rcs}) {
732 error(gettext("cannot use multiple rcs plugins"));
734 loadplugin($config{rcs});
736 if (! exists $hooks{rcs}) {
740 run_hooks(getopt => sub { shift->() });
741 if (grep /^-/, @ARGV) {
742 print STDERR "Unknown option (or missing parameter): $_\n"
743 foreach grep /^-/, @ARGV;
750 sub loadplugin ($;$) {
754 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
756 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
757 "$installdir/lib/ikiwiki") {
758 if (defined $dir && -x "$dir/plugins/$plugin") {
759 eval { require IkiWiki::Plugin::external };
762 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
764 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
765 $loaded_plugins{$plugin}=1;
770 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
773 error("Failed to load plugin $mod: $@");
775 $loaded_plugins{$plugin}=1;
782 log_message('err' => $message) if $config{syslog};
783 if (defined $cleaner) {
790 return unless $config{verbose};
791 return log_message(debug => @_);
796 sub log_message ($$) {
799 if ($config{syslog}) {
802 Sys::Syslog::setlogsock('unix');
803 Sys::Syslog::openlog('ikiwiki', '', 'user');
807 # keep a copy to avoid editing the original config repeatedly
808 my $wikiname = $config{wikiname};
809 utf8::encode($wikiname);
810 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
813 print STDERR "failed to syslog: $@" unless $log_failed;
819 elsif (! $config{cgi}) {
823 return print STDERR "@_\n";
827 sub possibly_foolish_untaint ($) {
829 my ($untainted)=$tainted=~/(.*)/s;
849 return exists $pagesources{$page} &&
850 $pagesources{$page} =~ /\._([^.]+)$/;
856 if ($file =~ /\.([^.]+)$/) {
857 return $1 if exists $hooks{htmlize}{$1};
859 my $base=basename($file);
860 if (exists $hooks{htmlize}{$base} &&
861 $hooks{htmlize}{$base}{noextension}) {
872 if (exists $pagename_cache{$file}) {
873 return $pagename_cache{$file};
876 my $type=pagetype($file);
878 $page=~s/\Q.$type\E*$//
879 if defined $type && !$hooks{htmlize}{$type}{keepextension}
880 && !$hooks{htmlize}{$type}{noextension};
881 if ($config{indexpages} && $page=~/(.*)\/index$/) {
885 $pagename_cache{$file} = $page;
889 sub newpagefile ($$) {
893 if (! $config{indexpages} || $page eq 'index') {
894 return $page.".".$type;
897 return $page."/index.".$type;
901 sub targetpage ($$;$) {
906 if (defined $filename) {
907 return $page."/".$filename.".".$ext;
909 elsif (! $config{usedirs} || $page eq 'index') {
910 return $page.".".$ext;
913 return $page."/index.".$ext;
920 return targetpage($page, $config{htmlext});
927 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
928 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
929 return "$dir/$file", stat(_) if -e "$dir/$file";
931 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
936 return (srcfile_stat(@_))[0];
939 sub add_literal_underlay ($) {
942 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
943 unshift @{$config{underlaydirs}}, $dir;
947 sub add_underlay ($) {
951 $dir="$config{underlaydirbase}/$dir";
954 add_literal_underlay($dir);
955 # why does it return 1? we just don't know
959 sub readfile ($;$$) {
965 error("cannot read a symlink ($file)");
969 open (my $in, "<", $file) || error("failed to read $file: $!");
970 binmode($in) if ($binary);
971 return \*$in if $wantfd;
973 # check for invalid utf-8, and toss it back to avoid crashes
974 if (! utf8::valid($ret)) {
975 $ret=encode_utf8($ret);
977 close $in || error("failed to read $file: $!");
981 sub prep_writefile ($$) {
986 while (length $test) {
987 if (-l "$destdir/$test") {
988 error("cannot write to a symlink ($test)");
990 if (-f _ && $test ne $file) {
991 # Remove conflicting file.
992 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
993 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
995 unlink("$destdir/$test");
1001 $test=dirname($test);
1004 my $dir=dirname("$destdir/$file");
1007 foreach my $s (split(m!/+!, $dir)) {
1010 mkdir($d) || error("failed to create directory $d: $!");
1018 sub writefile ($$$;$$) {
1019 my $file=shift; # can include subdirs
1020 my $destdir=shift; # directory to put file in
1025 prep_writefile($file, $destdir);
1027 my $newfile="$destdir/$file.ikiwiki-new";
1029 error("cannot write to a symlink ($newfile)");
1032 my $cleanup = sub { unlink($newfile) };
1033 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1034 binmode($out) if ($binary);
1036 $writer->(\*$out, $cleanup);
1039 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1041 close $out || error("failed saving $newfile: $!", $cleanup);
1042 rename($newfile, "$destdir/$file") ||
1043 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1049 sub will_render ($$;$) {
1054 # Important security check for independently created files.
1055 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1056 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1057 my $from_other_page=0;
1058 # Expensive, but rarely runs.
1059 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1062 dirname($_) eq $dest
1063 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1069 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1070 unless $from_other_page;
1073 # If $dest exists as a directory, remove conflicting files in it
1074 # rendered from other pages.
1076 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1077 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1078 if (dirname($f) eq $dest) {
1079 unlink("$config{destdir}/$f");
1080 rmdir(dirname("$config{destdir}/$f"));
1086 if (! $clear || $cleared{$page}) {
1087 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1090 foreach my $old (@{$renderedfiles{$page}}) {
1091 delete $destsources{$old};
1093 $renderedfiles{$page}=[$dest];
1096 $destsources{$dest}=$page;
1106 if ($link=~s/^\/+//) {
1114 $l.="/" if length $l;
1117 if (exists $pagesources{$l}) {
1120 elsif (exists $pagecase{lc $l}) {
1121 return $pagecase{lc $l};
1123 } while $cwd=~s{/?[^/]+$}{};
1125 if (length $config{userdir}) {
1126 my $l = "$config{userdir}/".lc($link);
1127 if (exists $pagesources{$l}) {
1130 elsif (exists $pagecase{lc $l}) {
1131 return $pagecase{lc $l};
1135 #print STDERR "warning: page $page, broken link: $link\n";
1139 sub isinlinableimage ($) {
1142 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1145 sub pagetitle ($;$) {
1147 my $unescaped=shift;
1150 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1153 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1161 # support use w/o %config set
1162 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1163 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1169 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1170 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1177 my $cgiurl=$local_cgiurl;
1179 if (exists $params{cgiurl}) {
1180 $cgiurl=$params{cgiurl};
1181 delete $params{cgiurl};
1189 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1192 sub cgiurl_abs (@) {
1194 URI->new_abs(cgiurl(@_), $config{cgiurl});
1200 return $local_url if ! defined $page;
1202 $page=htmlpage($page);
1204 $page=~s/[^\/]+\//..\//g;
1212 return $url unless defined $urlbase && length $urlbase;
1215 URI->new_abs($url, $urlbase)->as_string;
1219 # Work around very innefficient behavior in File::Spec if abs2rel
1220 # is passed two relative paths. It's much faster if paths are
1221 # absolute! (Debian bug #376658; fixed in debian unstable now)
1226 my $ret=File::Spec->abs2rel($path, $base);
1227 $ret=~s/^// if defined $ret;
1231 sub displaytime ($;$$) {
1232 # Plugins can override this function to mark up the time to
1234 my $time=formattime($_[0], $_[1]);
1235 if ($config{html5}) {
1236 return '<time datetime="'.date_3339($_[0]).'"'.
1237 ($_[2] ? ' pubdate="pubdate"' : '').
1238 '>'.$time.'</time>';
1241 return '<span class="date">'.$time.'</span>';
1245 sub formattime ($;$) {
1246 # Plugins can override this function to format the time.
1249 if (! defined $format) {
1250 $format=$config{timeformat};
1253 return strftime_utf8($format, localtime($time));
1256 my $strftime_encoding;
1258 # strftime doesn't know about encodings, so make sure
1259 # its output is properly treated as utf8.
1260 # Note that this does not handle utf-8 in the format string.
1261 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1262 unless defined $strftime_encoding;
1264 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1265 : POSIX::strftime(@_);
1271 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1272 POSIX::setlocale(&POSIX::LC_TIME, "C");
1273 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1274 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1278 sub beautify_urlpath ($) {
1281 # Ensure url is not an empty link, and if necessary,
1282 # add ./ to avoid colon confusion.
1283 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1287 if ($config{usedirs}) {
1288 $url =~ s!/index.$config{htmlext}$!/!;
1303 if (! $destsources{$to}) {
1308 return $config{url}.beautify_urlpath("/".$to);
1311 if (! defined $from) {
1312 my $u = $local_url || '';
1314 return $u.beautify_urlpath("/".$to);
1317 my $link = abs2rel($to, dirname(htmlpage($from)));
1319 return beautify_urlpath($link);
1322 sub isselflink ($$) {
1323 # Plugins can override this function to support special types
1328 return $page eq $link;
1331 sub htmllink ($$$;@) {
1332 my $lpage=shift; # the page doing the linking
1333 my $page=shift; # the page that will contain the link (different for inline)
1340 if (! $opts{forcesubpage}) {
1341 $bestlink=bestlink($lpage, $link);
1344 $bestlink="$lpage/".lc($link);
1348 if (defined $opts{linktext}) {
1349 $linktext=$opts{linktext};
1352 $linktext=pagetitle(basename($link));
1355 return "<span class=\"selflink\">$linktext</span>"
1356 if length $bestlink && isselflink($page, $bestlink) &&
1357 ! defined $opts{anchor};
1359 if (! $destsources{$bestlink}) {
1360 $bestlink=htmlpage($bestlink);
1362 if (! $destsources{$bestlink}) {
1364 if (length $config{cgiurl}) {
1365 $cgilink = "<a href=\"".
1370 )."\" rel=\"nofollow\">?</a>";
1372 return "<span class=\"createlink\">$cgilink$linktext</span>"
1376 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1377 $bestlink=beautify_urlpath($bestlink);
1379 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1380 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1383 if (defined $opts{anchor}) {
1384 $bestlink.="#".$opts{anchor};
1388 foreach my $attr (qw{rel class title}) {
1389 if (defined $opts{$attr}) {
1390 push @attrs, " $attr=\"$opts{$attr}\"";
1394 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1399 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1402 sub openiduser ($) {
1405 if (defined $user && $user =~ m!^https?://! &&
1406 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1409 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1410 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1413 # backcompat with old version
1414 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1415 $display=$oid->display;
1418 # Convert "user.somehost.com" to "user [somehost.com]"
1419 # (also "user.somehost.co.uk")
1420 if ($display !~ /\[/) {
1421 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1423 # Convert "http://somehost.com/user" to "user [somehost.com]".
1424 # (also "https://somehost.com/user/")
1425 if ($display !~ /\[/) {
1426 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1428 $display=~s!^https?://!!; # make sure this is removed
1429 eval q{use CGI 'escapeHTML'};
1431 return escapeHTML($display);
1436 sub htmlize ($$$$) {
1442 my $oneline = $content !~ /\n/;
1444 if (exists $hooks{htmlize}{$type}) {
1445 $content=$hooks{htmlize}{$type}{call}->(
1447 content => $content,
1451 error("htmlization of $type not supported");
1454 run_hooks(sanitize => sub {
1457 destpage => $destpage,
1458 content => $content,
1463 # hack to get rid of enclosing junk added by markdown
1464 # and other htmlizers/sanitizers
1465 $content=~s/^<p>//i;
1466 $content=~s/<\/p>\n*$//i;
1477 run_hooks(linkify => sub {
1480 destpage => $destpage,
1481 content => $content,
1489 our $preprocess_preview=0;
1490 sub preprocess ($$$;$$) {
1491 my $page=shift; # the page the data comes from
1492 my $destpage=shift; # the page the data will appear in (different for inline)
1497 # Using local because it needs to be set within any nested calls
1499 local $preprocess_preview=$preview if defined $preview;
1506 $params="" if ! defined $params;
1508 if (length $escape) {
1509 return "[[$prefix$command $params]]";
1511 elsif (exists $hooks{preprocess}{$command}) {
1512 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1513 # Note: preserve order of params, some plugins may
1514 # consider it significant.
1516 while ($params =~ m{
1517 (?:([-.\w]+)=)? # 1: named parameter key?
1519 """(.*?)""" # 2: triple-quoted value
1521 "([^"]*?)" # 3: single-quoted value
1523 '''(.*?)''' # 4: triple-single-quote
1525 <<([a-zA-Z]+)\n # 5: heredoc start
1526 (.*?)\n\5 # 6: heredoc value
1528 (\S+) # 7: unquoted value
1530 (?:\s+|$) # delimiter to next param
1540 elsif (defined $3) {
1543 elsif (defined $4) {
1546 elsif (defined $7) {
1549 elsif (defined $6) {
1554 push @params, $key, $val;
1557 push @params, $val, '';
1560 if ($preprocessing{$page}++ > 8) {
1561 # Avoid loops of preprocessed pages preprocessing
1562 # other pages that preprocess them, etc.
1563 return "[[!$command <span class=\"error\">".
1564 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1565 $page, $preprocessing{$page}).
1571 $hooks{preprocess}{$command}{call}->(
1574 destpage => $destpage,
1575 preview => $preprocess_preview,
1581 $ret="[[!$command <span class=\"error\">".
1582 gettext("Error").": $error"."</span>]]";
1586 # use void context during scan pass
1588 $hooks{preprocess}{$command}{call}->(
1591 destpage => $destpage,
1592 preview => $preprocess_preview,
1597 $preprocessing{$page}--;
1601 return "[[$prefix$command $params]]";
1606 if ($config{prefix_directives}) {
1609 \[\[(!) # directive open; 2: prefix
1610 ([-\w]+) # 3: command
1611 ( # 4: the parameters..
1612 \s+ # Must have space if parameters present
1614 (?:[-.\w]+=)? # named parameter key?
1616 """.*?""" # triple-quoted value
1618 "[^"]*?" # single-quoted value
1620 '''.*?''' # triple-single-quote
1622 <<([a-zA-Z]+)\n # 5: heredoc start
1623 (?:.*?)\n\5 # heredoc value
1625 [^"\s\]]+ # unquoted value
1627 \s* # whitespace or end
1630 *)? # 0 or more parameters
1631 \]\] # directive closed
1637 \[\[(!?) # directive open; 2: optional prefix
1638 ([-\w]+) # 3: command
1640 ( # 4: the parameters..
1642 (?:[-.\w]+=)? # named parameter key?
1644 """.*?""" # triple-quoted value
1646 "[^"]*?" # single-quoted value
1648 '''.*?''' # triple-single-quote
1650 <<([a-zA-Z]+)\n # 5: heredoc start
1651 (?:.*?)\n\5 # heredoc value
1653 [^"\s\]]+ # unquoted value
1655 \s* # whitespace or end
1658 *) # 0 or more parameters
1659 \]\] # directive closed
1663 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1672 run_hooks(filter => sub {
1673 $content=shift->(page => $page, destpage => $destpage,
1674 content => $content);
1680 sub check_canedit ($$$;$) {
1687 run_hooks(canedit => sub {
1688 return if defined $canedit;
1689 my $ret=shift->($page, $q, $session);
1694 elsif (ref $ret eq 'CODE') {
1695 $ret->() unless $nonfatal;
1698 elsif (defined $ret) {
1699 error($ret) unless $nonfatal;
1704 return defined $canedit ? $canedit : 1;
1707 sub check_content (@) {
1710 return 1 if ! exists $hooks{checkcontent}; # optimisation
1712 if (exists $pagesources{$params{page}}) {
1714 my %old=map { $_ => 1 }
1715 split("\n", readfile(srcfile($pagesources{$params{page}})));
1716 foreach my $line (split("\n", $params{content})) {
1717 push @diff, $line if ! exists $old{$line};
1719 $params{diff}=join("\n", @diff);
1723 run_hooks(checkcontent => sub {
1724 return if defined $ok;
1725 my $ret=shift->(%params);
1730 elsif (ref $ret eq 'CODE') {
1731 $ret->() unless $params{nonfatal};
1734 elsif (defined $ret) {
1735 error($ret) unless $params{nonfatal};
1741 return defined $ok ? $ok : 1;
1744 sub check_canchange (@) {
1746 my $cgi = $params{cgi};
1747 my $session = $params{session};
1748 my @changes = @{$params{changes}};
1751 foreach my $change (@changes) {
1752 # This untaint is safe because we check file_pruned and
1754 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1755 $file=possibly_foolish_untaint($file);
1756 if (! defined $file || ! length $file ||
1757 file_pruned($file)) {
1758 error(gettext("bad file name %s"), $file);
1761 my $type=pagetype($file);
1762 my $page=pagename($file) if defined $type;
1764 if ($change->{action} eq 'add') {
1768 if ($change->{action} eq 'change' ||
1769 $change->{action} eq 'add') {
1770 if (defined $page) {
1771 check_canedit($page, $cgi, $session);
1775 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1776 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1777 check_canedit($file, $cgi, $session);
1782 elsif ($change->{action} eq 'remove') {
1783 # check_canremove tests to see if the file is present
1784 # on disk. This will fail when a single commit adds a
1785 # file and then removes it again. Avoid the problem
1786 # by not testing the removal in such pairs of changes.
1787 # (The add is still tested, just to make sure that
1788 # no data is added to the repo that a web edit
1790 next if $newfiles{$file};
1792 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1793 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1794 check_canedit(defined $page ? $page : $file, $cgi, $session);
1799 error "unknown action ".$change->{action};
1802 error sprintf(gettext("you are not allowed to change %s"), $file);
1810 # Take an exclusive lock on the wiki to prevent multiple concurrent
1811 # run issues. The lock will be dropped on program exit.
1812 if (! -d $config{wikistatedir}) {
1813 mkdir($config{wikistatedir});
1815 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1816 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1817 if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1818 debug("failed to get lock; waiting...");
1819 if (! flock($wikilock, LOCK_EX)) {
1820 error("failed to get lock");
1827 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1828 return close($wikilock) if $wikilock;
1834 sub commit_hook_enabled () {
1835 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1836 error("cannot write to $config{wikistatedir}/commitlock: $!");
1837 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1838 close($commitlock) || error("failed closing commitlock: $!");
1841 close($commitlock) || error("failed closing commitlock: $!");
1845 sub disable_commit_hook () {
1846 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1847 error("cannot write to $config{wikistatedir}/commitlock: $!");
1848 if (! flock($commitlock, 2)) { # LOCK_EX
1849 error("failed to get commit lock");
1854 sub enable_commit_hook () {
1855 return close($commitlock) if $commitlock;
1860 %oldrenderedfiles=%pagectime=();
1861 my $rebuild=$config{rebuild};
1863 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1864 %destsources=%renderedfiles=%pagecase=%pagestate=
1865 %depends_simple=%typedlinks=%oldtypedlinks=();
1868 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1869 if (-e "$config{wikistatedir}/index") {
1870 system("ikiwiki-transition", "indexdb", $config{srcdir});
1871 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1874 # gettime on first build
1875 $config{gettime}=1 unless defined $config{gettime};
1880 my $index=Storable::fd_retrieve($in);
1881 if (! defined $index) {
1886 if (exists $index->{version} && ! ref $index->{version}) {
1887 $pages=$index->{page};
1888 %wikistate=%{$index->{state}};
1889 # Handle plugins that got disabled by loading a new setup.
1890 if (exists $config{setupfile}) {
1891 require IkiWiki::Setup;
1892 IkiWiki::Setup::disabled_plugins(
1893 grep { ! $loaded_plugins{$_} } keys %wikistate);
1901 foreach my $src (keys %$pages) {
1902 my $d=$pages->{$src};
1904 if (exists $d->{page} && ! $rebuild) {
1908 $page=pagename($src);
1910 $pagectime{$page}=$d->{ctime};
1911 $pagesources{$page}=$src;
1913 $pagemtime{$page}=$d->{mtime};
1914 $renderedfiles{$page}=$d->{dest};
1915 if (exists $d->{links} && ref $d->{links}) {
1916 $links{$page}=$d->{links};
1917 $oldlinks{$page}=[@{$d->{links}}];
1919 if (ref $d->{depends_simple} eq 'ARRAY') {
1921 $depends_simple{$page}={
1922 map { $_ => 1 } @{$d->{depends_simple}}
1925 elsif (exists $d->{depends_simple}) {
1926 $depends_simple{$page}=$d->{depends_simple};
1928 if (exists $d->{dependslist}) {
1931 map { $_ => $DEPEND_CONTENT }
1932 @{$d->{dependslist}}
1935 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1937 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1939 elsif (exists $d->{depends}) {
1940 $depends{$page}=$d->{depends};
1942 if (exists $d->{state}) {
1943 $pagestate{$page}=$d->{state};
1945 if (exists $d->{typedlinks}) {
1946 $typedlinks{$page}=$d->{typedlinks};
1948 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1949 next unless %$links;
1950 $oldtypedlinks{$page}{$type} = {%$links};
1954 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1956 foreach my $page (keys %pagesources) {
1957 $pagecase{lc $page}=$page;
1959 foreach my $page (keys %renderedfiles) {
1960 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1962 $lastrev=$index->{lastrev};
1963 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1968 run_hooks(savestate => sub { shift->() });
1970 my @plugins=keys %loaded_plugins;
1972 if (! -d $config{wikistatedir}) {
1973 mkdir($config{wikistatedir});
1975 my $newfile="$config{wikistatedir}/indexdb.new";
1976 my $cleanup = sub { unlink($newfile) };
1977 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1980 foreach my $page (keys %pagemtime) {
1981 next unless $pagemtime{$page};
1982 my $src=$pagesources{$page};
1984 $index{page}{$src}={
1986 ctime => $pagectime{$page},
1987 mtime => $pagemtime{$page},
1988 dest => $renderedfiles{$page},
1989 links => $links{$page},
1992 if (exists $depends{$page}) {
1993 $index{page}{$src}{depends} = $depends{$page};
1996 if (exists $depends_simple{$page}) {
1997 $index{page}{$src}{depends_simple} = $depends_simple{$page};
2000 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2001 $index{page}{$src}{typedlinks} = $typedlinks{$page};
2004 if (exists $pagestate{$page}) {
2005 $index{page}{$src}{state}=$pagestate{$page};
2010 foreach my $id (@plugins) {
2011 $index{state}{$id}={}; # used to detect disabled plugins
2012 foreach my $key (keys %{$wikistate{$id}}) {
2013 $index{state}{$id}{$key}=$wikistate{$id}{$key};
2017 $index{lastrev}=$lastrev;
2018 $index{underlayfiles}=\@underlayfiles;
2020 $index{version}="3";
2021 my $ret=Storable::nstore_fd(\%index, $out);
2022 return if ! defined $ret || ! $ret;
2023 close $out || error("failed saving to $newfile: $!", $cleanup);
2024 rename($newfile, "$config{wikistatedir}/indexdb") ||
2025 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2030 sub template_file ($) {
2033 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2035 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2036 $template=srcfile($pagesources{$tpage}, 1);
2040 $template=srcfile($tpage, 1);
2043 if (defined $template) {
2044 return $template, $tpage, 1 if wantarray;
2048 $name=~s:/::; # avoid path traversal
2049 foreach my $dir ($config{templatedir},
2050 "$installdir/share/ikiwiki/templates") {
2051 if (-e "$dir/$name") {
2052 $template="$dir/$name";
2056 if (defined $template) {
2057 return $template, $tpage if wantarray;
2065 sub template_depends ($$;@) {
2069 my ($filename, $tpage, $untrusted)=template_file($name);
2070 if (! defined $filename) {
2071 error(sprintf(gettext("template %s not found"), $name))
2074 if (defined $page && defined $tpage) {
2075 add_depends($page, $tpage);
2080 my $text_ref = shift;
2081 ${$text_ref} = decode_utf8(${$text_ref});
2082 run_hooks(readtemplate => sub {
2083 ${$text_ref} = shift->(
2086 content => ${$text_ref},
2087 untrusted => $untrusted,
2091 loop_context_vars => 1,
2092 die_on_bad_params => 0,
2093 parent_global_vars => 1,
2094 filename => $filename,
2096 ($untrusted ? (no_includes => 1) : ()),
2098 return @opts if wantarray;
2100 require HTML::Template;
2101 return HTML::Template->new(@opts);
2104 sub template ($;@) {
2105 template_depends(shift, undef, @_);
2108 sub templateactions ($$) {
2114 run_hooks(pageactions => sub {
2115 push @actions, map { { action => $_ } }
2116 grep { defined } shift->(page => $page);
2118 $template->param(actions => \@actions);
2120 if ($config{cgiurl} && exists $hooks{auth}) {
2121 $template->param(prefsurl => cgiurl(do => "prefs"));
2125 if ($have_actions || @actions) {
2126 $template->param(have_actions => 1);
2133 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2134 error 'hook requires type, call, and id parameters';
2137 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2139 $hooks{$param{type}}{$param{id}}=\%param;
2143 sub run_hooks ($$) {
2144 # Calls the given sub for each hook of the given type,
2145 # passing it the hook function to call.
2149 if (exists $hooks{$type}) {
2150 my (@first, @middle, @last);
2151 foreach my $id (keys %{$hooks{$type}}) {
2152 if ($hooks{$type}{$id}{first}) {
2155 elsif ($hooks{$type}{$id}{last}) {
2162 foreach my $id (@first, @middle, @last) {
2163 $sub->($hooks{$type}{$id}{call});
2171 $hooks{rcs}{rcs_update}{call}->(@_);
2174 sub rcs_prepedit ($) {
2175 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2178 sub rcs_commit (@) {
2179 $hooks{rcs}{rcs_commit}{call}->(@_);
2182 sub rcs_commit_staged (@) {
2183 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2187 $hooks{rcs}{rcs_add}{call}->(@_);
2190 sub rcs_remove ($) {
2191 $hooks{rcs}{rcs_remove}{call}->(@_);
2194 sub rcs_rename ($$) {
2195 $hooks{rcs}{rcs_rename}{call}->(@_);
2198 sub rcs_recentchanges ($) {
2199 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2202 sub rcs_diff ($;$) {
2203 $hooks{rcs}{rcs_diff}{call}->(@_);
2206 sub rcs_getctime ($) {
2207 $hooks{rcs}{rcs_getctime}{call}->(@_);
2210 sub rcs_getmtime ($) {
2211 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2214 sub rcs_receive () {
2215 $hooks{rcs}{rcs_receive}{call}->();
2218 sub add_depends ($$;$) {
2221 my $deptype=shift || $DEPEND_CONTENT;
2223 # Is the pagespec a simple page name?
2224 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2225 $pagespec !~ /[\s*?()!]/) {
2226 $depends_simple{$page}{lc $pagespec} |= $deptype;
2230 # Add explicit dependencies for influences.
2231 my $sub=pagespec_translate($pagespec);
2232 return unless defined $sub;
2233 foreach my $p (keys %pagesources) {
2234 my $r=$sub->($p, location => $page);
2235 my $i=$r->influences;
2236 my $static=$r->influences_static;
2237 foreach my $k (keys %$i) {
2238 next unless $r || $static || $k eq $page;
2239 $depends_simple{$page}{lc $k} |= $i->{$k};
2244 $depends{$page}{$pagespec} |= $deptype;
2250 foreach my $type (@_) {
2251 if ($type eq 'presence') {
2252 $deptype |= $DEPEND_PRESENCE;
2254 elsif ($type eq 'links') {
2255 $deptype |= $DEPEND_LINKS;
2257 elsif ($type eq 'content') {
2258 $deptype |= $DEPEND_CONTENT;
2264 my $file_prune_regexp;
2265 sub file_pruned ($) {
2268 if (defined $config{include} && length $config{include}) {
2269 return 0 if $file =~ m/$config{include}/;
2272 if (! defined $file_prune_regexp) {
2273 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2274 $file_prune_regexp=qr/$file_prune_regexp/;
2276 return $file =~ m/$file_prune_regexp/;
2279 sub define_gettext () {
2280 # If translation is needed, redefine the gettext function to do it.
2281 # Otherwise, it becomes a quick no-op.
2284 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2285 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2286 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2288 $gettext_obj=eval q{
2289 use Locale::gettext q{textdomain};
2290 Locale::gettext->domain('ikiwiki')
2295 no warnings 'redefine';
2297 $getobj->() if $getobj;
2299 $gettext_obj->get(shift);
2306 $getobj->() if $getobj;
2308 $gettext_obj->nget(@_);
2311 return ($_[2] == 1 ? $_[0] : $_[1])
2329 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2333 # Injects a new function into the symbol table to replace an
2334 # exported function.
2337 # This is deep ugly perl foo, beware.
2340 if (! defined $params{parent}) {
2341 $params{parent}='::';
2342 $params{old}=\&{$params{name}};
2343 $params{name}=~s/.*:://;
2345 my $parent=$params{parent};
2346 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2347 $ns = $params{parent} . $ns;
2348 inject(%params, parent => $ns) unless $ns eq '::main::';
2349 *{$ns . $params{name}} = $params{call}
2350 if exists ${$ns}{$params{name}} &&
2351 \&{${$ns}{$params{name}}} == $params{old};
2357 sub add_link ($$;$) {
2362 push @{$links{$page}}, $link
2363 unless grep { $_ eq $link } @{$links{$page}};
2365 if (defined $type) {
2366 $typedlinks{$page}{$type}{$link} = 1;
2370 sub add_autofile ($$$) {
2373 my $generator=shift;
2375 $autofiles{$file}{plugin}=$plugin;
2376 $autofiles{$file}{generator}=$generator;
2380 return LWP::UserAgent->new(
2381 cookie_jar => $config{cookiejar},
2382 env_proxy => 1, # respect proxy env vars
2383 agent => $config{useragent},
2387 sub sortspec_translate ($$) {
2389 my $reverse = shift;
2395 (-?) # group 1: perhaps negated
2398 \w+\([^\)]*\) # command(params)
2400 [^\s]+ # or anything else
2408 if ($word =~ m/^(\w+)\((.*)\)$/) {
2409 # command with parameters
2413 elsif ($word !~ m/^\w+$/) {
2414 error(sprintf(gettext("invalid sort type %s"), $word));
2425 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2426 if (defined $params) {
2427 push @data, $params;
2428 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2431 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2435 error(sprintf(gettext("unknown sort type %s"), $word));
2439 if (! length $code) {
2440 # undefined sorting method... sort arbitrarily
2449 return eval 'sub { '.$code.' }';
2452 sub pagespec_translate ($) {
2455 # Convert spec to perl code.
2459 \s* # ignore whitespace
2460 ( # 1: match a single word
2467 \w+\([^\)]*\) # command(params)
2469 [^\s()]+ # any other text
2471 \s* # ignore whitespace
2474 if (lc $word eq 'and') {
2477 elsif (lc $word eq 'or') {
2480 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2483 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2484 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2486 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2489 push @data, qq{unknown function in pagespec "$word"};
2490 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2495 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2499 if (! length $code) {
2500 $code="IkiWiki::FailReason->new('empty pagespec')";
2504 return eval 'sub { my $page=shift; '.$code.' }';
2507 sub pagespec_match ($$;@) {
2512 # Backwards compatability with old calling convention.
2514 unshift @params, 'location';
2517 my $sub=pagespec_translate($spec);
2518 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2520 return $sub->($page, @params);
2523 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2525 # Not exported yet, but could be in future if it is generally useful.
2526 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2527 # which is "more internal".
2528 sub sort_pages ($$;@) {
2532 $sort = sortspec_translate($sort, $params{reverse});
2533 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2536 sub pagespec_match_list ($$;@) {
2541 # Backwards compatability with old calling convention.
2543 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2544 $params{list}=$page;
2545 $page=$params{location}; # ugh!
2548 my $sub=pagespec_translate($pagespec);
2549 error "syntax error in pagespec \"$pagespec\""
2551 my $sort=sortspec_translate($params{sort}, $params{reverse})
2552 if defined $params{sort};
2555 if (exists $params{list}) {
2556 @candidates=exists $params{filter}
2557 ? grep { ! $params{filter}->($_) } @{$params{list}}
2561 @candidates=exists $params{filter}
2562 ? grep { ! $params{filter}->($_) } keys %pagesources
2563 : keys %pagesources;
2566 # clear params, remainder is passed to pagespec
2567 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2568 my $num=$params{num};
2569 delete @params{qw{num deptype reverse sort filter list}};
2571 # when only the top matches will be returned, it's efficient to
2572 # sort before matching to pagespec,
2573 if (defined $num && defined $sort) {
2574 @candidates=IkiWiki::SortSpec::sort_pages(
2575 $sort, @candidates);
2581 my $accum=IkiWiki::SuccessReason->new();
2582 foreach my $p (@candidates) {
2583 my $r=$sub->($p, %params, location => $page);
2584 error(sprintf(gettext("cannot match pages: %s"), $r))
2585 if $r->isa("IkiWiki::ErrorReason");
2586 unless ($r || $r->influences_static) {
2587 $r->remove_influence($p);
2592 last if defined $num && ++$count == $num;
2596 # Add simple dependencies for accumulated influences.
2597 my $i=$accum->influences;
2598 foreach my $k (keys %$i) {
2599 $depends_simple{$page}{lc $k} |= $i->{$k};
2602 # when all matches will be returned, it's efficient to
2603 # sort after matching
2604 if (! defined $num && defined $sort) {
2605 return IkiWiki::SortSpec::sort_pages(
2613 sub pagespec_valid ($) {
2616 return defined pagespec_translate($spec);
2620 my $re=quotemeta(shift);
2626 package IkiWiki::FailReason;
2629 '""' => sub { $_[0][0] },
2631 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2632 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2633 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2637 our @ISA = 'IkiWiki::SuccessReason';
2639 package IkiWiki::SuccessReason;
2641 # A blessed array-ref:
2643 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2645 # - if absent or false, the influences of this evaluation are "static",
2646 # see the influences_static method
2647 # - if true, they are dynamic (not static)
2648 # [1]{any other key}:
2649 # the dependency types of influences, as returned by the influences method
2652 # in string context, it's the human-readable reason
2653 '""' => sub { $_[0][0] },
2654 # in boolean context, SuccessReason is 1 and FailReason is 0
2656 # negating a result gives the opposite result with the same influences
2657 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2658 # A & B = (A ? B : A) with the influences of both
2659 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2660 # A | B = (A ? A : B) with the influences of both
2661 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2665 # SuccessReason->new("human-readable reason", page => deptype, ...)
2670 return bless [$value, {@_}], $class;
2673 # influences(): return a reference to a copy of the hash
2674 # { page => dependency type } describing the pages that indirectly influenced
2675 # this result, but would not cause a dependency through ikiwiki's core
2678 # See [[todo/dependency_types]] for extensive discussion of what this means.
2680 # influences(page => deptype, ...): remove all influences, replace them
2681 # with the arguments, and return a reference to a copy of the new influences.
2685 $this->[1]={@_} if @_;
2686 my %i=%{$this->[1]};
2691 # True if this result has the same influences whichever page it matches,
2692 # For instance, whether bar matches backlink(foo) is influenced only by
2693 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2694 # which does not mention bar anywhere.
2696 # False if this result would have different influences when matching
2697 # different pages. For instance, when testing whether link(foo) matches bar,
2698 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2699 # bar's links could change the outcome; so its influences are not the same
2700 # as when testing whether link(foo) matches baz.
2702 # Static influences are one of the things that make pagespec_match_list
2703 # more efficient than repeated calls to pagespec_match.
2705 sub influences_static {
2706 return ! $_[0][1]->{""};
2709 # Change the influences of $this to be the influences of "$this & $other"
2710 # or "$this | $other".
2712 # If both $this and $other are either successful or have influences,
2713 # or this is an "or" operation, the result has all the influences from
2714 # either of the arguments. It has dynamic influences if either argument
2715 # has dynamic influences.
2717 # If this is an "and" operation, and at least one argument is a
2718 # FailReason with no influences, the result has no influences, and they
2719 # are not dynamic. For instance, link(foo) matching bar is influenced
2720 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2721 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2722 # bar, because it would be false however often you edit bar.
2724 sub merge_influences {
2729 # This "if" is odd because it needs to avoid negating $this
2730 # or $other, which would alter the objects in-place. Be careful.
2731 if (! $anded || (($this || %{$this->[1]}) &&
2732 ($other || %{$other->[1]}))) {
2733 foreach my $influence (keys %{$other->[1]}) {
2734 $this->[1]{$influence} |= $other->[1]{$influence};
2743 # Change $this so it is not considered to be influenced by $torm.
2745 sub remove_influence {
2749 delete $this->[1]{$torm};
2752 package IkiWiki::ErrorReason;
2754 our @ISA = 'IkiWiki::FailReason';
2756 package IkiWiki::PageSpec;
2762 if ($path =~ m!^\.(/|$)!) {
2764 $from=~s#/?[^/]+$## if defined $from;
2766 $path="$from/$path" if defined $from && length $from;
2770 $path = "" unless defined $path;
2779 sub match_glob ($$;@) {
2784 $glob=derel($glob, $params{location});
2786 # Instead of converting the glob to a regex every time,
2787 # cache the compiled regex to save time.
2788 my $re=$glob_cache{$glob};
2789 unless (defined $re) {
2790 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2793 if (! IkiWiki::isinternal($page) || $params{internal}) {
2794 return IkiWiki::SuccessReason->new("$glob matches $page");
2797 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2801 return IkiWiki::FailReason->new("$glob does not match $page");
2805 sub match_internal ($$;@) {
2806 return match_glob(shift, shift, @_, internal => 1)
2809 sub match_page ($$;@) {
2811 my $match=match_glob($page, shift, @_);
2813 my $source=exists $IkiWiki::pagesources{$page} ?
2814 $IkiWiki::pagesources{$page} :
2815 $IkiWiki::delpagesources{$page};
2816 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2817 if (! defined $type) {
2818 return IkiWiki::FailReason->new("$page is not a page");
2824 sub match_link ($$;@) {
2829 $link=derel($link, $params{location});
2830 my $from=exists $params{location} ? $params{location} : '';
2831 my $linktype=$params{linktype};
2833 if (defined $linktype) {
2834 $qualifier=" with type $linktype";
2837 my $links = $IkiWiki::links{$page};
2838 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2839 unless $links && @{$links};
2840 my $bestlink = IkiWiki::bestlink($from, $link);
2841 foreach my $p (@{$links}) {
2842 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2844 if (length $bestlink) {
2845 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2846 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2850 if (match_glob($p, $link, %params)) {
2851 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2853 my ($p_rel)=$p=~/^\/?(.*)/;
2855 if (match_glob($p_rel, $link, %params)) {
2856 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2860 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2863 sub match_backlink ($$;@) {
2867 if ($testpage eq '.') {
2868 $testpage = $params{'location'}
2870 my $ret=match_link($testpage, $page, @_);
2871 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2875 sub match_created_before ($$;@) {
2880 $testpage=derel($testpage, $params{location});
2882 if (exists $IkiWiki::pagectime{$testpage}) {
2883 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2884 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2887 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2891 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2895 sub match_created_after ($$;@) {
2900 $testpage=derel($testpage, $params{location});
2902 if (exists $IkiWiki::pagectime{$testpage}) {
2903 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2904 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2907 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2911 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2915 sub match_creation_day ($$;@) {
2918 if ($d !~ /^\d+$/) {
2919 return IkiWiki::ErrorReason->new("invalid day $d");
2921 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2922 return IkiWiki::SuccessReason->new('creation_day matched');
2925 return IkiWiki::FailReason->new('creation_day did not match');
2929 sub match_creation_month ($$;@) {
2932 if ($m !~ /^\d+$/) {
2933 return IkiWiki::ErrorReason->new("invalid month $m");
2935 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2936 return IkiWiki::SuccessReason->new('creation_month matched');
2939 return IkiWiki::FailReason->new('creation_month did not match');
2943 sub match_creation_year ($$;@) {
2946 if ($y !~ /^\d+$/) {
2947 return IkiWiki::ErrorReason->new("invalid year $y");
2949 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2950 return IkiWiki::SuccessReason->new('creation_year matched');
2953 return IkiWiki::FailReason->new('creation_year did not match');
2957 sub match_user ($$;@) {
2962 if (! exists $params{user}) {
2963 return IkiWiki::ErrorReason->new("no user specified");
2966 my $regexp=IkiWiki::glob2re($user);
2968 if (defined $params{user} && $params{user}=~$regexp) {
2969 return IkiWiki::SuccessReason->new("user is $user");
2971 elsif (! defined $params{user}) {
2972 return IkiWiki::FailReason->new("not logged in");
2975 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2979 sub match_admin ($$;@) {
2984 if (! exists $params{user}) {
2985 return IkiWiki::ErrorReason->new("no user specified");
2988 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2989 return IkiWiki::SuccessReason->new("user is an admin");
2991 elsif (! defined $params{user}) {
2992 return IkiWiki::FailReason->new("not logged in");
2995 return IkiWiki::FailReason->new("user is not an admin");
2999 sub match_ip ($$;@) {
3004 if (! exists $params{ip}) {
3005 return IkiWiki::ErrorReason->new("no IP specified");
3008 my $regexp=IkiWiki::glob2re(lc $ip);
3010 if (defined $params{ip} && lc $params{ip}=~$regexp) {
3011 return IkiWiki::SuccessReason->new("IP is $ip");
3014 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3018 package IkiWiki::SortSpec;
3020 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3021 # are easily available in this namespace, for cmp functions to use them.
3028 IkiWiki::pagetitle(IkiWiki::basename($a))
3030 IkiWiki::pagetitle(IkiWiki::basename($b))
3033 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3034 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3035 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }