8 use URI::Escape q{uri_escape_utf8};
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14 %pagestate %wikistate %renderedfiles %oldrenderedfiles
15 %pagesources %delpagesources %destsources %depends %depends_simple
16 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17 %oldtypedlinks %autofiles @underlayfiles $lastrev $phase};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21 deptype add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime strftime_utf8 will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link add_autofile useragent
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
37 # Phases of processing.
38 sub PHASE_SCAN () { 0 }
39 sub PHASE_RENDER () { 1 }
45 memoize("sortspec_translate");
46 memoize("pagespec_translate");
47 memoize("template_file");
53 description => "name of the wiki",
60 example => 'me@example.com',
61 description => "contact email for wiki",
68 description => "users who are wiki admins",
75 description => "users who are banned from the wiki",
82 example => "$ENV{HOME}/wiki",
83 description => "where the source of the wiki is located",
90 example => "/var/www/wiki",
91 description => "where to build the wiki",
98 example => "http://example.com/wiki",
99 description => "base url to the wiki",
106 example => "http://example.com/wiki/ikiwiki.cgi",
107 description => "url to the ikiwiki.cgi",
114 example => "/var/www/wiki/ikiwiki.cgi",
115 description => "filename of cgi wrapper to generate",
122 description => "mode for cgi_wrapper (can safely be made suid)",
126 cgi_overload_delay => {
130 description => "number of seconds to delay CGI requests when overloaded",
134 cgi_overload_message => {
137 example => "Please wait",
138 description => "message to display when overloaded (may contain html)",
142 only_committed_changes => {
145 description => "enable optimization of only refreshing committed changes?",
152 description => "rcs backend to use",
153 safe => 0, # don't allow overriding
158 default => [qw{mdwn link inline meta htmlscrubber passwordauth
159 openid signinedit lockedit conditional
160 recentchanges parentlinks editpage
162 description => "plugins to enable by default",
169 description => "plugins to add to the default configuration",
176 description => "plugins to disable",
182 default => "$installdir/share/ikiwiki/templates",
183 description => "additional directory to search for template files",
190 default => "$installdir/share/ikiwiki/basewiki",
191 description => "base wiki source location",
198 default => "$installdir/share/ikiwiki",
199 description => "parent directory containing additional underlays",
206 description => "wrappers to generate",
213 description => "additional underlays to use",
220 description => "display verbose messages?",
227 description => "log to syslog?",
234 description => "create output files named page/index.html?",
235 safe => 0, # changing requires manual transition
238 prefix_directives => {
241 description => "use '!'-prefixed preprocessor directives?",
242 safe => 0, # changing requires manual transition
248 description => "use page/index.mdwn source files",
255 description => "enable Discussion pages?",
261 default => gettext("Discussion"),
262 description => "name of Discussion pages",
269 description => "generate HTML5?",
277 description => "only send cookies over SSL connections?",
285 description => "extension to use for new pages",
286 safe => 0, # not sanitized
292 description => "extension to use for html files",
293 safe => 0, # not sanitized
299 description => "strftime format string to display date",
307 example => "en_US.UTF-8",
308 description => "UTF-8 locale to use",
317 description => "put user pages below specified page",
324 description => "how many backlinks to show before hiding excess (0 to show all)",
331 description => "attempt to hardlink source files? (optimisation for large files)",
333 safe => 0, # paranoia
339 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
341 safe => 0, # paranoia
346 example => "ikiwiki",
347 description => "group for wrappers to run in",
349 safe => 0, # paranoia
355 example => "$ENV{HOME}/.ikiwiki/",
356 description => "extra library and plugin directory",
358 safe => 0, # directory
364 description => "environment variables",
365 safe => 0, # paranoia
371 example => "US/Eastern",
372 description => "time zone name",
379 example => '^\.htaccess$',
380 description => "regexp of normally excluded files to include",
388 example => '^(*\.private|Makefile)$',
389 description => "regexp of files that should be skipped",
394 wiki_file_prune_regexps => {
396 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
397 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
398 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
399 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
400 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
401 description => "regexps of source files to ignore",
407 description => "specifies the characters that are allowed in source filenames",
408 default => "-[:alnum:]+/.:_",
412 wiki_file_regexp => {
414 description => "regexp of legal source files",
418 web_commit_regexp => {
420 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
421 description => "regexp to parse web commits from logs",
428 description => "run as a cgi",
432 cgi_disable_uploads => {
435 description => "whether CGI should accept file uploads",
442 description => "run as a post-commit hook",
449 description => "running in rebuild mode",
456 description => "running in setup mode",
463 description => "running in clean mode",
470 description => "running in refresh mode",
477 description => "running in receive test mode",
481 wrapper_background_command => {
484 description => "background shell command to run",
490 description => "running in gettime mode",
497 description => "running in w3mmode",
504 description => "path to the .ikiwiki directory holding ikiwiki state",
511 description => "path to setup file",
518 description => "perl class to use to dump setup file",
522 allow_symlinks_before_srcdir => {
525 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
531 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
532 description => "cookie control",
533 safe => 0, # hooks into perl module internals
539 example => "Wget/1.13.4 (linux-gnu)",
540 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
546 sub defaultconfig () {
549 foreach my $key (keys %s) {
550 push @ret, $key, $s{$key}->{default};
555 # URL to top of wiki as a path starting with /, valid from any wiki page or
556 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
558 # URL to CGI script, similar to $local_url
562 # locale stuff; avoid LC_ALL since it overrides everything
563 if (defined $ENV{LC_ALL}) {
564 $ENV{LANG} = $ENV{LC_ALL};
567 if (defined $config{locale}) {
568 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
569 $ENV{LANG}=$config{locale};
574 if (! defined $config{wiki_file_regexp}) {
575 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
578 if (ref $config{ENV} eq 'HASH') {
579 foreach my $val (keys %{$config{ENV}}) {
580 $ENV{$val}=$config{ENV}{$val};
583 if (defined $config{timezone} && length $config{timezone}) {
584 $ENV{TZ}=$config{timezone};
587 $config{timezone}=$ENV{TZ};
590 if ($config{w3mmode}) {
591 eval q{use Cwd q{abs_path}};
593 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
594 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
595 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
596 unless $config{cgiurl} =~ m!file:///!;
597 $config{url}="file://".$config{destdir};
600 if ($config{cgi} && ! length $config{url}) {
601 error(gettext("Must specify url to wiki with --url when using --cgi"));
604 if (defined $config{url} && length $config{url}) {
606 my $baseurl = URI->new($config{url});
608 $local_url = $baseurl->path . "/";
609 $local_cgiurl = undef;
611 if (length $config{cgiurl}) {
612 my $cgiurl = URI->new($config{cgiurl});
614 $local_cgiurl = $cgiurl->path;
616 if ($cgiurl->scheme ne $baseurl->scheme or
617 $cgiurl->authority ne $baseurl->authority) {
618 # too far apart, fall back to absolute URLs
619 $local_url = "$config{url}/";
620 $local_cgiurl = $config{cgiurl};
624 $local_url =~ s{//$}{/};
627 $local_cgiurl = $config{cgiurl};
630 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
631 unless exists $config{wikistatedir} && defined $config{wikistatedir};
633 if (defined $config{umask}) {
634 my $u = possibly_foolish_untaint($config{umask});
636 if ($u =~ m/^\d+$/) {
639 elsif ($u eq 'private') {
642 elsif ($u eq 'group') {
645 elsif ($u eq 'public') {
649 error(sprintf(gettext("unsupported umask setting %s"), $u));
653 run_hooks(checkconfig => sub { shift->() });
661 foreach my $dir (@INC, $config{libdir}) {
662 next unless defined $dir && length $dir;
663 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
664 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
668 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
669 next unless defined $dir && length $dir;
670 foreach my $file (glob("$dir/plugins/*")) {
671 $ret{basename($file)}=1 if -x $file;
679 if (defined $config{libdir} && length $config{libdir}) {
680 unshift @INC, possibly_foolish_untaint($config{libdir});
683 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
688 if (exists $hooks{rcs}) {
689 error(gettext("cannot use multiple rcs plugins"));
691 loadplugin($config{rcs});
693 if (! exists $hooks{rcs}) {
697 run_hooks(getopt => sub { shift->() });
698 if (grep /^-/, @ARGV) {
699 print STDERR "Unknown option (or missing parameter): $_\n"
700 foreach grep /^-/, @ARGV;
707 sub loadplugin ($;$) {
711 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
713 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
714 "$installdir/lib/ikiwiki") {
715 if (defined $dir && -x "$dir/plugins/$plugin") {
716 eval { require IkiWiki::Plugin::external };
719 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
721 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
722 $loaded_plugins{$plugin}=1;
727 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
730 error("Failed to load plugin $mod: $@");
732 $loaded_plugins{$plugin}=1;
739 log_message('err' => $message) if $config{syslog};
740 if (defined $cleaner) {
747 return unless $config{verbose};
748 return log_message(debug => @_);
753 sub log_message ($$) {
756 if ($config{syslog}) {
759 Sys::Syslog::setlogsock('unix');
760 Sys::Syslog::openlog('ikiwiki', '', 'user');
764 # keep a copy to avoid editing the original config repeatedly
765 my $wikiname = $config{wikiname};
766 utf8::encode($wikiname);
767 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
770 print STDERR "failed to syslog: $@" unless $log_failed;
776 elsif (! $config{cgi}) {
780 return print STDERR "@_\n";
784 sub possibly_foolish_untaint ($) {
786 my ($untainted)=$tainted=~/(.*)/s;
806 return exists $pagesources{$page} &&
807 $pagesources{$page} =~ /\._([^.]+)$/;
813 if ($file =~ /\.([^.]+)$/) {
814 return $1 if exists $hooks{htmlize}{$1};
816 my $base=basename($file);
817 if (exists $hooks{htmlize}{$base} &&
818 $hooks{htmlize}{$base}{noextension}) {
829 if (exists $pagename_cache{$file}) {
830 return $pagename_cache{$file};
833 my $type=pagetype($file);
835 $page=~s/\Q.$type\E*$//
836 if defined $type && !$hooks{htmlize}{$type}{keepextension}
837 && !$hooks{htmlize}{$type}{noextension};
838 if ($config{indexpages} && $page=~/(.*)\/index$/) {
842 $pagename_cache{$file} = $page;
846 sub newpagefile ($$) {
850 if (! $config{indexpages} || $page eq 'index') {
851 return $page.".".$type;
854 return $page."/index.".$type;
858 sub targetpage ($$;$) {
863 if (defined $filename) {
864 return $page."/".$filename.".".$ext;
866 elsif (! $config{usedirs} || $page eq 'index') {
867 return $page.".".$ext;
870 return $page."/index.".$ext;
877 return targetpage($page, $config{htmlext});
884 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
885 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
886 return "$dir/$file", stat(_) if -e "$dir/$file";
888 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
893 return (srcfile_stat(@_))[0];
896 sub add_literal_underlay ($) {
899 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
900 unshift @{$config{underlaydirs}}, $dir;
904 sub add_underlay ($) {
908 $dir="$config{underlaydirbase}/$dir";
911 add_literal_underlay($dir);
912 # why does it return 1? we just don't know
916 sub readfile ($;$$) {
922 error("cannot read a symlink ($file)");
926 open (my $in, "<", $file) || error("failed to read $file: $!");
927 binmode($in) if ($binary);
928 return \*$in if $wantfd;
930 # check for invalid utf-8, and toss it back to avoid crashes
931 if (! utf8::valid($ret)) {
932 $ret=encode_utf8($ret);
934 close $in || error("failed to read $file: $!");
938 sub prep_writefile ($$) {
943 while (length $test) {
944 if (-l "$destdir/$test") {
945 error("cannot write to a symlink ($test)");
947 if (-f _ && $test ne $file) {
948 # Remove conflicting file.
949 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
950 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
952 unlink("$destdir/$test");
958 $test=dirname($test);
961 my $dir=dirname("$destdir/$file");
964 foreach my $s (split(m!/+!, $dir)) {
967 mkdir($d) || error("failed to create directory $d: $!");
975 sub writefile ($$$;$$) {
976 my $file=shift; # can include subdirs
977 my $destdir=shift; # directory to put file in
982 prep_writefile($file, $destdir);
984 my $newfile="$destdir/$file.ikiwiki-new";
986 error("cannot write to a symlink ($newfile)");
989 my $cleanup = sub { unlink($newfile) };
990 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
991 binmode($out) if ($binary);
993 $writer->(\*$out, $cleanup);
996 print $out $content or error("failed writing to $newfile: $!", $cleanup);
998 close $out || error("failed saving $newfile: $!", $cleanup);
999 rename($newfile, "$destdir/$file") ||
1000 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1006 sub will_render ($$;$) {
1011 # Important security check for independently created files.
1012 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1013 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1014 my $from_other_page=0;
1015 # Expensive, but rarely runs.
1016 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1019 dirname($_) eq $dest
1020 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1026 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1027 unless $from_other_page;
1030 # If $dest exists as a directory, remove conflicting files in it
1031 # rendered from other pages.
1033 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1034 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1035 if (dirname($f) eq $dest) {
1036 unlink("$config{destdir}/$f");
1037 rmdir(dirname("$config{destdir}/$f"));
1043 if (! $clear || $cleared{$page}) {
1044 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1047 foreach my $old (@{$renderedfiles{$page}}) {
1048 delete $destsources{$old};
1050 $renderedfiles{$page}=[$dest];
1053 $destsources{$dest}=$page;
1063 if ($link=~s/^\/+//) {
1071 $l.="/" if length $l;
1074 if (exists $pagesources{$l}) {
1077 elsif (exists $pagecase{lc $l}) {
1078 return $pagecase{lc $l};
1080 } while $cwd=~s{/?[^/]+$}{};
1082 if (length $config{userdir}) {
1083 my $l = "$config{userdir}/".lc($link);
1084 if (exists $pagesources{$l}) {
1087 elsif (exists $pagecase{lc $l}) {
1088 return $pagecase{lc $l};
1092 #print STDERR "warning: page $page, broken link: $link\n";
1096 sub isinlinableimage ($) {
1099 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1102 sub pagetitle ($;$) {
1104 my $unescaped=shift;
1107 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1110 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1118 # support use w/o %config set
1119 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1120 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1126 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1127 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1134 my $cgiurl=$local_cgiurl;
1136 if (exists $params{cgiurl}) {
1137 $cgiurl=$params{cgiurl};
1138 delete $params{cgiurl};
1146 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1149 sub cgiurl_abs (@) {
1151 URI->new_abs(cgiurl(@_), $config{cgiurl});
1157 return $local_url if ! defined $page;
1159 $page=htmlpage($page);
1161 $page=~s/[^\/]+\//..\//g;
1169 return $url unless defined $urlbase && length $urlbase;
1172 URI->new_abs($url, $urlbase)->as_string;
1176 # Work around very innefficient behavior in File::Spec if abs2rel
1177 # is passed two relative paths. It's much faster if paths are
1178 # absolute! (Debian bug #376658; fixed in debian unstable now)
1183 my $ret=File::Spec->abs2rel($path, $base);
1184 $ret=~s/^// if defined $ret;
1188 sub displaytime ($;$$) {
1189 # Plugins can override this function to mark up the time to
1191 my $time=formattime($_[0], $_[1]);
1192 if ($config{html5}) {
1193 return '<time datetime="'.date_3339($_[0]).'"'.
1194 ($_[2] ? ' pubdate="pubdate"' : '').
1195 '>'.$time.'</time>';
1198 return '<span class="date">'.$time.'</span>';
1202 sub formattime ($;$) {
1203 # Plugins can override this function to format the time.
1206 if (! defined $format) {
1207 $format=$config{timeformat};
1210 return strftime_utf8($format, localtime($time));
1213 my $strftime_encoding;
1215 # strftime doesn't know about encodings, so make sure
1216 # its output is properly treated as utf8.
1217 # Note that this does not handle utf-8 in the format string.
1218 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1219 unless defined $strftime_encoding;
1221 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1222 : POSIX::strftime(@_);
1228 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1229 POSIX::setlocale(&POSIX::LC_TIME, "C");
1230 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1231 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1235 sub beautify_urlpath ($) {
1238 # Ensure url is not an empty link, and if necessary,
1239 # add ./ to avoid colon confusion.
1240 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1244 if ($config{usedirs}) {
1245 $url =~ s!/index.$config{htmlext}$!/!;
1260 if (! $destsources{$to}) {
1265 return $config{url}.beautify_urlpath("/".$to);
1268 if (! defined $from) {
1269 my $u = $local_url || '';
1271 return $u.beautify_urlpath("/".$to);
1274 my $link = abs2rel($to, dirname(htmlpage($from)));
1276 return beautify_urlpath($link);
1279 sub isselflink ($$) {
1280 # Plugins can override this function to support special types
1285 return $page eq $link;
1288 sub htmllink ($$$;@) {
1289 my $lpage=shift; # the page doing the linking
1290 my $page=shift; # the page that will contain the link (different for inline)
1297 if (! $opts{forcesubpage}) {
1298 $bestlink=bestlink($lpage, $link);
1301 $bestlink="$lpage/".lc($link);
1305 if (defined $opts{linktext}) {
1306 $linktext=$opts{linktext};
1309 $linktext=pagetitle(basename($link));
1312 return "<span class=\"selflink\">$linktext</span>"
1313 if length $bestlink && isselflink($page, $bestlink) &&
1314 ! defined $opts{anchor};
1316 if (! $destsources{$bestlink}) {
1317 $bestlink=htmlpage($bestlink);
1319 if (! $destsources{$bestlink}) {
1321 if (length $config{cgiurl}) {
1322 $cgilink = "<a href=\"".
1327 )."\" rel=\"nofollow\">?</a>";
1329 return "<span class=\"createlink\">$cgilink$linktext</span>"
1333 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1334 $bestlink=beautify_urlpath($bestlink);
1336 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1337 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1340 if (defined $opts{anchor}) {
1341 $bestlink.="#".$opts{anchor};
1345 foreach my $attr (qw{rel class title}) {
1346 if (defined $opts{$attr}) {
1347 push @attrs, " $attr=\"$opts{$attr}\"";
1351 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1356 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1359 sub openiduser ($) {
1362 if (defined $user && $user =~ m!^https?://! &&
1363 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1366 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1367 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1370 # backcompat with old version
1371 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1372 $display=$oid->display;
1375 # Convert "user.somehost.com" to "user [somehost.com]"
1376 # (also "user.somehost.co.uk")
1377 if ($display !~ /\[/) {
1378 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1380 # Convert "http://somehost.com/user" to "user [somehost.com]".
1381 # (also "https://somehost.com/user/")
1382 if ($display !~ /\[/) {
1383 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1385 $display=~s!^https?://!!; # make sure this is removed
1386 eval q{use CGI 'escapeHTML'};
1388 return escapeHTML($display);
1393 sub htmlize ($$$$) {
1399 my $oneline = $content !~ /\n/;
1401 if (exists $hooks{htmlize}{$type}) {
1402 $content=$hooks{htmlize}{$type}{call}->(
1404 content => $content,
1408 error("htmlization of $type not supported");
1411 run_hooks(sanitize => sub {
1414 destpage => $destpage,
1415 content => $content,
1420 # hack to get rid of enclosing junk added by markdown
1421 # and other htmlizers/sanitizers
1422 $content=~s/^<p>//i;
1423 $content=~s/<\/p>\n*$//i;
1434 run_hooks(linkify => sub {
1437 destpage => $destpage,
1438 content => $content,
1446 our $preprocess_preview=0;
1447 sub preprocess ($$$;$$) {
1448 my $page=shift; # the page the data comes from
1449 my $destpage=shift; # the page the data will appear in (different for inline)
1454 # Using local because it needs to be set within any nested calls
1456 local $preprocess_preview=$preview if defined $preview;
1463 $params="" if ! defined $params;
1465 if (length $escape) {
1466 return "[[$prefix$command $params]]";
1468 elsif (exists $hooks{preprocess}{$command}) {
1469 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1470 # Note: preserve order of params, some plugins may
1471 # consider it significant.
1473 while ($params =~ m{
1474 (?:([-.\w]+)=)? # 1: named parameter key?
1476 """(.*?)""" # 2: triple-quoted value
1478 "([^"]*?)" # 3: single-quoted value
1480 '''(.*?)''' # 4: triple-single-quote
1482 <<([a-zA-Z]+)\n # 5: heredoc start
1483 (.*?)\n\5 # 6: heredoc value
1485 (\S+) # 7: unquoted value
1487 (?:\s+|$) # delimiter to next param
1497 elsif (defined $3) {
1500 elsif (defined $4) {
1503 elsif (defined $7) {
1506 elsif (defined $6) {
1511 push @params, $key, $val;
1514 push @params, $val, '';
1517 if ($preprocessing{$page}++ > 8) {
1518 # Avoid loops of preprocessed pages preprocessing
1519 # other pages that preprocess them, etc.
1520 return "[[!$command <span class=\"error\">".
1521 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1522 $page, $preprocessing{$page}).
1528 $hooks{preprocess}{$command}{call}->(
1531 destpage => $destpage,
1532 preview => $preprocess_preview,
1538 $ret="[[!$command <span class=\"error\">".
1539 gettext("Error").": $error"."</span>]]";
1543 # use void context during scan pass
1545 $hooks{preprocess}{$command}{call}->(
1548 destpage => $destpage,
1549 preview => $preprocess_preview,
1554 $preprocessing{$page}--;
1558 return "[[$prefix$command $params]]";
1563 if ($config{prefix_directives}) {
1566 \[\[(!) # directive open; 2: prefix
1567 ([-\w]+) # 3: command
1568 ( # 4: the parameters..
1569 \s+ # Must have space if parameters present
1571 (?:[-.\w]+=)? # named parameter key?
1573 """.*?""" # triple-quoted value
1575 "[^"]*?" # single-quoted value
1577 '''.*?''' # triple-single-quote
1579 <<([a-zA-Z]+)\n # 5: heredoc start
1580 (?:.*?)\n\5 # heredoc value
1582 [^"\s\]]+ # unquoted value
1584 \s* # whitespace or end
1587 *)? # 0 or more parameters
1588 \]\] # directive closed
1594 \[\[(!?) # directive open; 2: optional prefix
1595 ([-\w]+) # 3: command
1597 ( # 4: the parameters..
1599 (?:[-.\w]+=)? # named parameter key?
1601 """.*?""" # triple-quoted value
1603 "[^"]*?" # single-quoted value
1605 '''.*?''' # triple-single-quote
1607 <<([a-zA-Z]+)\n # 5: heredoc start
1608 (?:.*?)\n\5 # heredoc value
1610 [^"\s\]]+ # unquoted value
1612 \s* # whitespace or end
1615 *) # 0 or more parameters
1616 \]\] # directive closed
1620 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1629 run_hooks(filter => sub {
1630 $content=shift->(page => $page, destpage => $destpage,
1631 content => $content);
1637 sub check_canedit ($$$;$) {
1644 run_hooks(canedit => sub {
1645 return if defined $canedit;
1646 my $ret=shift->($page, $q, $session);
1651 elsif (ref $ret eq 'CODE') {
1652 $ret->() unless $nonfatal;
1655 elsif (defined $ret) {
1656 error($ret) unless $nonfatal;
1661 return defined $canedit ? $canedit : 1;
1664 sub check_content (@) {
1667 return 1 if ! exists $hooks{checkcontent}; # optimisation
1669 if (exists $pagesources{$params{page}}) {
1671 my %old=map { $_ => 1 }
1672 split("\n", readfile(srcfile($pagesources{$params{page}})));
1673 foreach my $line (split("\n", $params{content})) {
1674 push @diff, $line if ! exists $old{$line};
1676 $params{diff}=join("\n", @diff);
1680 run_hooks(checkcontent => sub {
1681 return if defined $ok;
1682 my $ret=shift->(%params);
1687 elsif (ref $ret eq 'CODE') {
1688 $ret->() unless $params{nonfatal};
1691 elsif (defined $ret) {
1692 error($ret) unless $params{nonfatal};
1698 return defined $ok ? $ok : 1;
1701 sub check_canchange (@) {
1703 my $cgi = $params{cgi};
1704 my $session = $params{session};
1705 my @changes = @{$params{changes}};
1708 foreach my $change (@changes) {
1709 # This untaint is safe because we check file_pruned and
1711 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1712 $file=possibly_foolish_untaint($file);
1713 if (! defined $file || ! length $file ||
1714 file_pruned($file)) {
1715 error(gettext("bad file name %s"), $file);
1718 my $type=pagetype($file);
1719 my $page=pagename($file) if defined $type;
1721 if ($change->{action} eq 'add') {
1725 if ($change->{action} eq 'change' ||
1726 $change->{action} eq 'add') {
1727 if (defined $page) {
1728 check_canedit($page, $cgi, $session);
1732 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1733 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1734 check_canedit($file, $cgi, $session);
1739 elsif ($change->{action} eq 'remove') {
1740 # check_canremove tests to see if the file is present
1741 # on disk. This will fail when a single commit adds a
1742 # file and then removes it again. Avoid the problem
1743 # by not testing the removal in such pairs of changes.
1744 # (The add is still tested, just to make sure that
1745 # no data is added to the repo that a web edit
1747 next if $newfiles{$file};
1749 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1750 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1751 check_canedit(defined $page ? $page : $file, $cgi, $session);
1756 error "unknown action ".$change->{action};
1759 error sprintf(gettext("you are not allowed to change %s"), $file);
1767 # Take an exclusive lock on the wiki to prevent multiple concurrent
1768 # run issues. The lock will be dropped on program exit.
1769 if (! -d $config{wikistatedir}) {
1770 mkdir($config{wikistatedir});
1772 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1773 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1774 if (! flock($wikilock, 2)) { # LOCK_EX
1775 error("failed to get lock");
1781 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1782 return close($wikilock) if $wikilock;
1788 sub commit_hook_enabled () {
1789 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1790 error("cannot write to $config{wikistatedir}/commitlock: $!");
1791 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1792 close($commitlock) || error("failed closing commitlock: $!");
1795 close($commitlock) || error("failed closing commitlock: $!");
1799 sub disable_commit_hook () {
1800 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1801 error("cannot write to $config{wikistatedir}/commitlock: $!");
1802 if (! flock($commitlock, 2)) { # LOCK_EX
1803 error("failed to get commit lock");
1808 sub enable_commit_hook () {
1809 return close($commitlock) if $commitlock;
1814 %oldrenderedfiles=%pagectime=();
1815 my $rebuild=$config{rebuild};
1817 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1818 %destsources=%renderedfiles=%pagecase=%pagestate=
1819 %depends_simple=%typedlinks=%oldtypedlinks=();
1822 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1823 if (-e "$config{wikistatedir}/index") {
1824 system("ikiwiki-transition", "indexdb", $config{srcdir});
1825 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1828 $config{gettime}=1; # first build
1833 my $index=Storable::fd_retrieve($in);
1834 if (! defined $index) {
1839 if (exists $index->{version} && ! ref $index->{version}) {
1840 $pages=$index->{page};
1841 %wikistate=%{$index->{state}};
1842 # Handle plugins that got disabled by loading a new setup.
1843 if (exists $config{setupfile}) {
1844 require IkiWiki::Setup;
1845 IkiWiki::Setup::disabled_plugins(
1846 grep { ! $loaded_plugins{$_} } keys %wikistate);
1854 foreach my $src (keys %$pages) {
1855 my $d=$pages->{$src};
1857 if (exists $d->{page} && ! $rebuild) {
1861 $page=pagename($src);
1863 $pagectime{$page}=$d->{ctime};
1864 $pagesources{$page}=$src;
1866 $pagemtime{$page}=$d->{mtime};
1867 $renderedfiles{$page}=$d->{dest};
1868 if (exists $d->{links} && ref $d->{links}) {
1869 $links{$page}=$d->{links};
1870 $oldlinks{$page}=[@{$d->{links}}];
1872 if (ref $d->{depends_simple} eq 'ARRAY') {
1874 $depends_simple{$page}={
1875 map { $_ => 1 } @{$d->{depends_simple}}
1878 elsif (exists $d->{depends_simple}) {
1879 $depends_simple{$page}=$d->{depends_simple};
1881 if (exists $d->{dependslist}) {
1884 map { $_ => $DEPEND_CONTENT }
1885 @{$d->{dependslist}}
1888 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1890 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1892 elsif (exists $d->{depends}) {
1893 $depends{$page}=$d->{depends};
1895 if (exists $d->{state}) {
1896 $pagestate{$page}=$d->{state};
1898 if (exists $d->{typedlinks}) {
1899 $typedlinks{$page}=$d->{typedlinks};
1901 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1902 next unless %$links;
1903 $oldtypedlinks{$page}{$type} = {%$links};
1907 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1909 foreach my $page (keys %pagesources) {
1910 $pagecase{lc $page}=$page;
1912 foreach my $page (keys %renderedfiles) {
1913 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1915 $lastrev=$index->{lastrev};
1916 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1921 run_hooks(savestate => sub { shift->() });
1923 my @plugins=keys %loaded_plugins;
1925 if (! -d $config{wikistatedir}) {
1926 mkdir($config{wikistatedir});
1928 my $newfile="$config{wikistatedir}/indexdb.new";
1929 my $cleanup = sub { unlink($newfile) };
1930 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1933 foreach my $page (keys %pagemtime) {
1934 next unless $pagemtime{$page};
1935 my $src=$pagesources{$page};
1937 $index{page}{$src}={
1939 ctime => $pagectime{$page},
1940 mtime => $pagemtime{$page},
1941 dest => $renderedfiles{$page},
1942 links => $links{$page},
1945 if (exists $depends{$page}) {
1946 $index{page}{$src}{depends} = $depends{$page};
1949 if (exists $depends_simple{$page}) {
1950 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1953 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1954 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1957 if (exists $pagestate{$page}) {
1958 $index{page}{$src}{state}=$pagestate{$page};
1963 foreach my $id (@plugins) {
1964 $index{state}{$id}={}; # used to detect disabled plugins
1965 foreach my $key (keys %{$wikistate{$id}}) {
1966 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1970 $index{lastrev}=$lastrev;
1971 $index{underlayfiles}=\@underlayfiles;
1973 $index{version}="3";
1974 my $ret=Storable::nstore_fd(\%index, $out);
1975 return if ! defined $ret || ! $ret;
1976 close $out || error("failed saving to $newfile: $!", $cleanup);
1977 rename($newfile, "$config{wikistatedir}/indexdb") ||
1978 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1983 sub template_file ($) {
1986 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1988 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1989 $template=srcfile($pagesources{$tpage}, 1);
1993 $template=srcfile($tpage, 1);
1996 if (defined $template) {
1997 return $template, $tpage, 1 if wantarray;
2001 $name=~s:/::; # avoid path traversal
2002 foreach my $dir ($config{templatedir},
2003 "$installdir/share/ikiwiki/templates") {
2004 if (-e "$dir/$name") {
2005 $template="$dir/$name";
2009 if (defined $template) {
2010 return $template, $tpage if wantarray;
2018 sub template_depends ($$;@) {
2022 my ($filename, $tpage, $untrusted)=template_file($name);
2023 if (! defined $filename) {
2024 error(sprintf(gettext("template %s not found"), $name))
2027 if (defined $page && defined $tpage) {
2028 add_depends($page, $tpage);
2033 my $text_ref = shift;
2034 ${$text_ref} = decode_utf8(${$text_ref});
2035 run_hooks(readtemplate => sub {
2036 ${$text_ref} = shift->(
2039 content => ${$text_ref},
2040 untrusted => $untrusted,
2044 loop_context_vars => 1,
2045 die_on_bad_params => 0,
2046 parent_global_vars => 1,
2047 filename => $filename,
2049 ($untrusted ? (no_includes => 1) : ()),
2051 return @opts if wantarray;
2053 require HTML::Template;
2054 return HTML::Template->new(@opts);
2057 sub template ($;@) {
2058 template_depends(shift, undef, @_);
2061 sub templateactions ($$) {
2067 run_hooks(pageactions => sub {
2068 push @actions, map { { action => $_ } }
2069 grep { defined } shift->(page => $page);
2071 $template->param(actions => \@actions);
2073 if ($config{cgiurl} && exists $hooks{auth}) {
2074 $template->param(prefsurl => cgiurl(do => "prefs"));
2078 if ($have_actions || @actions) {
2079 $template->param(have_actions => 1);
2086 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2087 error 'hook requires type, call, and id parameters';
2090 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2092 $hooks{$param{type}}{$param{id}}=\%param;
2096 sub run_hooks ($$) {
2097 # Calls the given sub for each hook of the given type,
2098 # passing it the hook function to call.
2102 if (exists $hooks{$type}) {
2103 my (@first, @middle, @last);
2104 foreach my $id (keys %{$hooks{$type}}) {
2105 if ($hooks{$type}{$id}{first}) {
2108 elsif ($hooks{$type}{$id}{last}) {
2115 foreach my $id (@first, @middle, @last) {
2116 $sub->($hooks{$type}{$id}{call});
2124 $hooks{rcs}{rcs_update}{call}->(@_);
2127 sub rcs_prepedit ($) {
2128 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2131 sub rcs_commit (@) {
2132 $hooks{rcs}{rcs_commit}{call}->(@_);
2135 sub rcs_commit_staged (@) {
2136 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2140 $hooks{rcs}{rcs_add}{call}->(@_);
2143 sub rcs_remove ($) {
2144 $hooks{rcs}{rcs_remove}{call}->(@_);
2147 sub rcs_rename ($$) {
2148 $hooks{rcs}{rcs_rename}{call}->(@_);
2151 sub rcs_recentchanges ($) {
2152 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2155 sub rcs_diff ($;$) {
2156 $hooks{rcs}{rcs_diff}{call}->(@_);
2159 sub rcs_getctime ($) {
2160 $hooks{rcs}{rcs_getctime}{call}->(@_);
2163 sub rcs_getmtime ($) {
2164 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2167 sub rcs_receive () {
2168 $hooks{rcs}{rcs_receive}{call}->();
2171 sub add_depends ($$;$) {
2174 my $deptype=shift || $DEPEND_CONTENT;
2176 # Is the pagespec a simple page name?
2177 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2178 $pagespec !~ /[\s*?()!]/) {
2179 $depends_simple{$page}{lc $pagespec} |= $deptype;
2183 # Add explicit dependencies for influences.
2184 my $sub=pagespec_translate($pagespec);
2185 return unless defined $sub;
2186 foreach my $p (keys %pagesources) {
2187 my $r=$sub->($p, location => $page);
2188 my $i=$r->influences;
2189 my $static=$r->influences_static;
2190 foreach my $k (keys %$i) {
2191 next unless $r || $static || $k eq $page;
2192 $depends_simple{$page}{lc $k} |= $i->{$k};
2197 $depends{$page}{$pagespec} |= $deptype;
2203 foreach my $type (@_) {
2204 if ($type eq 'presence') {
2205 $deptype |= $DEPEND_PRESENCE;
2207 elsif ($type eq 'links') {
2208 $deptype |= $DEPEND_LINKS;
2210 elsif ($type eq 'content') {
2211 $deptype |= $DEPEND_CONTENT;
2217 my $file_prune_regexp;
2218 sub file_pruned ($) {
2221 if (defined $config{include} && length $config{include}) {
2222 return 0 if $file =~ m/$config{include}/;
2225 if (! defined $file_prune_regexp) {
2226 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2227 $file_prune_regexp=qr/$file_prune_regexp/;
2229 return $file =~ m/$file_prune_regexp/;
2232 sub define_gettext () {
2233 # If translation is needed, redefine the gettext function to do it.
2234 # Otherwise, it becomes a quick no-op.
2237 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2238 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2239 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2241 $gettext_obj=eval q{
2242 use Locale::gettext q{textdomain};
2243 Locale::gettext->domain('ikiwiki')
2248 no warnings 'redefine';
2250 $getobj->() if $getobj;
2252 $gettext_obj->get(shift);
2259 $getobj->() if $getobj;
2261 $gettext_obj->nget(@_);
2264 return ($_[2] == 1 ? $_[0] : $_[1])
2282 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2286 # Injects a new function into the symbol table to replace an
2287 # exported function.
2290 # This is deep ugly perl foo, beware.
2293 if (! defined $params{parent}) {
2294 $params{parent}='::';
2295 $params{old}=\&{$params{name}};
2296 $params{name}=~s/.*:://;
2298 my $parent=$params{parent};
2299 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2300 $ns = $params{parent} . $ns;
2301 inject(%params, parent => $ns) unless $ns eq '::main::';
2302 *{$ns . $params{name}} = $params{call}
2303 if exists ${$ns}{$params{name}} &&
2304 \&{${$ns}{$params{name}}} == $params{old};
2310 sub add_link ($$;$) {
2315 push @{$links{$page}}, $link
2316 unless grep { $_ eq $link } @{$links{$page}};
2318 if (defined $type) {
2319 $typedlinks{$page}{$type}{$link} = 1;
2323 sub add_autofile ($$$) {
2326 my $generator=shift;
2328 $autofiles{$file}{plugin}=$plugin;
2329 $autofiles{$file}{generator}=$generator;
2333 return LWP::UserAgent->new(
2334 cookie_jar => $config{cookiejar},
2335 env_proxy => 1, # respect proxy env vars
2336 agent => $config{useragent},
2340 sub sortspec_translate ($$) {
2342 my $reverse = shift;
2348 (-?) # group 1: perhaps negated
2351 \w+\([^\)]*\) # command(params)
2353 [^\s]+ # or anything else
2361 if ($word =~ m/^(\w+)\((.*)\)$/) {
2362 # command with parameters
2366 elsif ($word !~ m/^\w+$/) {
2367 error(sprintf(gettext("invalid sort type %s"), $word));
2378 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2379 if (defined $params) {
2380 push @data, $params;
2381 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2384 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2388 error(sprintf(gettext("unknown sort type %s"), $word));
2392 if (! length $code) {
2393 # undefined sorting method... sort arbitrarily
2402 return eval 'sub { '.$code.' }';
2405 sub pagespec_translate ($) {
2408 # Convert spec to perl code.
2412 \s* # ignore whitespace
2413 ( # 1: match a single word
2420 \w+\([^\)]*\) # command(params)
2422 [^\s()]+ # any other text
2424 \s* # ignore whitespace
2427 if (lc $word eq 'and') {
2430 elsif (lc $word eq 'or') {
2433 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2436 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2437 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2439 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2442 push @data, qq{unknown function in pagespec "$word"};
2443 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2448 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2452 if (! length $code) {
2453 $code="IkiWiki::FailReason->new('empty pagespec')";
2457 return eval 'sub { my $page=shift; '.$code.' }';
2460 sub pagespec_match ($$;@) {
2465 # Backwards compatability with old calling convention.
2467 unshift @params, 'location';
2470 my $sub=pagespec_translate($spec);
2471 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2473 return $sub->($page, @params);
2476 sub pagespec_match_list ($$;@) {
2481 # Backwards compatability with old calling convention.
2483 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2484 $params{list}=$page;
2485 $page=$params{location}; # ugh!
2488 my $sub=pagespec_translate($pagespec);
2489 error "syntax error in pagespec \"$pagespec\""
2491 my $sort=sortspec_translate($params{sort}, $params{reverse})
2492 if defined $params{sort};
2495 if (exists $params{list}) {
2496 @candidates=exists $params{filter}
2497 ? grep { ! $params{filter}->($_) } @{$params{list}}
2501 @candidates=exists $params{filter}
2502 ? grep { ! $params{filter}->($_) } keys %pagesources
2503 : keys %pagesources;
2506 # clear params, remainder is passed to pagespec
2507 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2508 my $num=$params{num};
2509 delete @params{qw{num deptype reverse sort filter list}};
2511 # when only the top matches will be returned, it's efficient to
2512 # sort before matching to pagespec,
2513 if (defined $num && defined $sort) {
2514 @candidates=IkiWiki::SortSpec::sort_pages(
2515 $sort, @candidates);
2521 my $accum=IkiWiki::SuccessReason->new();
2522 foreach my $p (@candidates) {
2523 my $r=$sub->($p, %params, location => $page);
2524 error(sprintf(gettext("cannot match pages: %s"), $r))
2525 if $r->isa("IkiWiki::ErrorReason");
2526 unless ($r || $r->influences_static) {
2527 $r->remove_influence($p);
2532 last if defined $num && ++$count == $num;
2536 # Add simple dependencies for accumulated influences.
2537 my $i=$accum->influences;
2538 foreach my $k (keys %$i) {
2539 $depends_simple{$page}{lc $k} |= $i->{$k};
2542 # when all matches will be returned, it's efficient to
2543 # sort after matching
2544 if (! defined $num && defined $sort) {
2545 return IkiWiki::SortSpec::sort_pages(
2553 sub pagespec_valid ($) {
2556 return defined pagespec_translate($spec);
2560 my $re=quotemeta(shift);
2566 package IkiWiki::FailReason;
2569 '""' => sub { $_[0][0] },
2571 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2572 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2573 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2577 our @ISA = 'IkiWiki::SuccessReason';
2579 package IkiWiki::SuccessReason;
2582 '""' => sub { $_[0][0] },
2584 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2585 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2586 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2593 return bless [$value, {@_}], $class;
2598 $this->[1]={@_} if @_;
2599 my %i=%{$this->[1]};
2604 sub influences_static {
2605 return ! $_[0][1]->{""};
2608 sub merge_influences {
2613 if (! $anded || (($this || %{$this->[1]}) &&
2614 ($other || %{$other->[1]}))) {
2615 foreach my $influence (keys %{$other->[1]}) {
2616 $this->[1]{$influence} |= $other->[1]{$influence};
2625 sub remove_influence {
2629 delete $this->[1]{$torm};
2632 package IkiWiki::ErrorReason;
2634 our @ISA = 'IkiWiki::FailReason';
2636 package IkiWiki::PageSpec;
2642 if ($path =~ m!^\.(/|$)!) {
2644 $from=~s#/?[^/]+$## if defined $from;
2646 $path="$from/$path" if defined $from && length $from;
2650 $path = "" unless defined $path;
2659 sub match_glob ($$;@) {
2664 $glob=derel($glob, $params{location});
2666 # Instead of converting the glob to a regex every time,
2667 # cache the compiled regex to save time.
2668 my $re=$glob_cache{$glob};
2669 unless (defined $re) {
2670 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2673 if (! IkiWiki::isinternal($page) || $params{internal}) {
2674 return IkiWiki::SuccessReason->new("$glob matches $page");
2677 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2681 return IkiWiki::FailReason->new("$glob does not match $page");
2685 sub match_internal ($$;@) {
2686 return match_glob(shift, shift, @_, internal => 1)
2689 sub match_page ($$;@) {
2691 my $match=match_glob($page, shift, @_);
2693 my $source=exists $IkiWiki::pagesources{$page} ?
2694 $IkiWiki::pagesources{$page} :
2695 $IkiWiki::delpagesources{$page};
2696 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2697 if (! defined $type) {
2698 return IkiWiki::FailReason->new("$page is not a page");
2704 sub match_link ($$;@) {
2709 $link=derel($link, $params{location});
2710 my $from=exists $params{location} ? $params{location} : '';
2711 my $linktype=$params{linktype};
2713 if (defined $linktype) {
2714 $qualifier=" with type $linktype";
2717 my $links = $IkiWiki::links{$page};
2718 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2719 unless $links && @{$links};
2720 my $bestlink = IkiWiki::bestlink($from, $link);
2721 foreach my $p (@{$links}) {
2722 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2724 if (length $bestlink) {
2725 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2726 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2730 if (match_glob($p, $link, %params)) {
2731 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2733 my ($p_rel)=$p=~/^\/?(.*)/;
2735 if (match_glob($p_rel, $link, %params)) {
2736 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2740 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2743 sub match_backlink ($$;@) {
2747 if ($testpage eq '.') {
2748 $testpage = $params{'location'}
2750 my $ret=match_link($testpage, $page, @_);
2751 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2755 sub match_created_before ($$;@) {
2760 $testpage=derel($testpage, $params{location});
2762 if (exists $IkiWiki::pagectime{$testpage}) {
2763 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2764 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2767 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2771 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2775 sub match_created_after ($$;@) {
2780 $testpage=derel($testpage, $params{location});
2782 if (exists $IkiWiki::pagectime{$testpage}) {
2783 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2784 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2787 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2791 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2795 sub match_creation_day ($$;@) {
2798 if ($d !~ /^\d+$/) {
2799 return IkiWiki::ErrorReason->new("invalid day $d");
2801 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2802 return IkiWiki::SuccessReason->new('creation_day matched');
2805 return IkiWiki::FailReason->new('creation_day did not match');
2809 sub match_creation_month ($$;@) {
2812 if ($m !~ /^\d+$/) {
2813 return IkiWiki::ErrorReason->new("invalid month $m");
2815 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2816 return IkiWiki::SuccessReason->new('creation_month matched');
2819 return IkiWiki::FailReason->new('creation_month did not match');
2823 sub match_creation_year ($$;@) {
2826 if ($y !~ /^\d+$/) {
2827 return IkiWiki::ErrorReason->new("invalid year $y");
2829 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2830 return IkiWiki::SuccessReason->new('creation_year matched');
2833 return IkiWiki::FailReason->new('creation_year did not match');
2837 sub match_user ($$;@) {
2842 if (! exists $params{user}) {
2843 return IkiWiki::ErrorReason->new("no user specified");
2846 my $regexp=IkiWiki::glob2re($user);
2848 if (defined $params{user} && $params{user}=~$regexp) {
2849 return IkiWiki::SuccessReason->new("user is $user");
2851 elsif (! defined $params{user}) {
2852 return IkiWiki::FailReason->new("not logged in");
2855 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2859 sub match_admin ($$;@) {
2864 if (! exists $params{user}) {
2865 return IkiWiki::ErrorReason->new("no user specified");
2868 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2869 return IkiWiki::SuccessReason->new("user is an admin");
2871 elsif (! defined $params{user}) {
2872 return IkiWiki::FailReason->new("not logged in");
2875 return IkiWiki::FailReason->new("user is not an admin");
2879 sub match_ip ($$;@) {
2884 if (! exists $params{ip}) {
2885 return IkiWiki::ErrorReason->new("no IP specified");
2888 my $regexp=IkiWiki::glob2re(lc $ip);
2890 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2891 return IkiWiki::SuccessReason->new("IP is $ip");
2894 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2898 package IkiWiki::SortSpec;
2900 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2901 # are easily available in this namespace, for cmp functions to use them.
2908 IkiWiki::pagetitle(IkiWiki::basename($a))
2910 IkiWiki::pagetitle(IkiWiki::basename($b))
2913 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2914 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2915 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }