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};
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
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;
40 memoize("sortspec_translate");
41 memoize("pagespec_translate");
42 memoize("template_file");
48 description => "name of the wiki",
55 example => 'me@example.com',
56 description => "contact email for wiki",
63 description => "users who are wiki admins",
70 description => "users who are banned from the wiki",
77 example => "$ENV{HOME}/wiki",
78 description => "where the source of the wiki is located",
85 example => "/var/www/wiki",
86 description => "where to build the wiki",
93 example => "http://example.com/wiki",
94 description => "base url to the wiki",
101 example => "http://example.com/wiki/ikiwiki.cgi",
102 description => "url to the ikiwiki.cgi",
109 example => "/var/www/wiki/ikiwiki.cgi",
110 description => "filename of cgi wrapper to generate",
117 description => "mode for cgi_wrapper (can safely be made suid)",
121 cgi_overload_delay => {
125 description => "number of seconds to delay CGI requests when overloaded",
129 cgi_overload_message => {
132 example => "Please wait",
133 description => "message to display when overloaded (may contain html)",
140 description => "rcs backend to use",
141 safe => 0, # don't allow overriding
146 default => [qw{mdwn link inline meta htmlscrubber passwordauth
147 openid signinedit lockedit conditional
148 recentchanges parentlinks editpage}],
149 description => "plugins to enable by default",
156 description => "plugins to add to the default configuration",
163 description => "plugins to disable",
169 default => "$installdir/share/ikiwiki/templates",
170 description => "additional directory to search for template files",
177 default => "$installdir/share/ikiwiki/basewiki",
178 description => "base wiki source location",
185 default => "$installdir/share/ikiwiki",
186 description => "parent directory containing additional underlays",
193 description => "wrappers to generate",
200 description => "additional underlays to use",
207 description => "display verbose messages?",
214 description => "log to syslog?",
221 description => "create output files named page/index.html?",
222 safe => 0, # changing requires manual transition
225 prefix_directives => {
228 description => "use '!'-prefixed preprocessor directives?",
229 safe => 0, # changing requires manual transition
235 description => "use page/index.mdwn source files",
242 description => "enable Discussion pages?",
248 default => gettext("Discussion"),
249 description => "name of Discussion pages",
256 description => "generate HTML5?",
264 description => "only send cookies over SSL connections?",
272 description => "extension to use for new pages",
273 safe => 0, # not sanitized
279 description => "extension to use for html files",
280 safe => 0, # not sanitized
286 description => "strftime format string to display date",
294 example => "en_US.UTF-8",
295 description => "UTF-8 locale to use",
304 description => "put user pages below specified page",
311 description => "how many backlinks to show before hiding excess (0 to show all)",
318 description => "attempt to hardlink source files? (optimisation for large files)",
320 safe => 0, # paranoia
326 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
328 safe => 0, # paranoia
333 example => "ikiwiki",
334 description => "group for wrappers to run in",
336 safe => 0, # paranoia
342 example => "$ENV{HOME}/.ikiwiki/",
343 description => "extra library and plugin directory",
345 safe => 0, # directory
351 description => "environment variables",
352 safe => 0, # paranoia
358 example => "US/Eastern",
359 description => "time zone name",
366 example => '^\.htaccess$',
367 description => "regexp of normally excluded files to include",
375 example => '^(*\.private|Makefile)$',
376 description => "regexp of files that should be skipped",
381 wiki_file_prune_regexps => {
383 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
384 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
385 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
386 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
387 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
388 description => "regexps of source files to ignore",
394 description => "specifies the characters that are allowed in source filenames",
395 default => "-[:alnum:]+/.:_",
399 wiki_file_regexp => {
401 description => "regexp of legal source files",
405 web_commit_regexp => {
407 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
408 description => "regexp to parse web commits from logs",
415 description => "run as a cgi",
419 cgi_disable_uploads => {
422 description => "whether CGI should accept file uploads",
429 description => "run as a post-commit hook",
436 description => "running in rebuild mode",
443 description => "running in setup mode",
450 description => "running in clean mode",
457 description => "running in refresh mode",
464 description => "running in receive test mode",
468 wrapper_background_command => {
471 description => "background shell command to run",
477 description => "running in gettime mode",
484 description => "running in w3mmode",
491 description => "path to the .ikiwiki directory holding ikiwiki state",
498 description => "path to setup file",
505 description => "perl class to use to dump setup file",
509 allow_symlinks_before_srcdir => {
512 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
518 sub defaultconfig () {
521 foreach my $key (keys %s) {
522 push @ret, $key, $s{$key}->{default};
527 # URL to top of wiki as a path starting with /, valid from any wiki page or
528 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
530 # URL to CGI script, similar to $local_url
534 # locale stuff; avoid LC_ALL since it overrides everything
535 if (defined $ENV{LC_ALL}) {
536 $ENV{LANG} = $ENV{LC_ALL};
539 if (defined $config{locale}) {
540 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
541 $ENV{LANG}=$config{locale};
546 if (! defined $config{wiki_file_regexp}) {
547 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
550 if (ref $config{ENV} eq 'HASH') {
551 foreach my $val (keys %{$config{ENV}}) {
552 $ENV{$val}=$config{ENV}{$val};
555 if (defined $config{timezone} && length $config{timezone}) {
556 $ENV{TZ}=$config{timezone};
559 $config{timezone}=$ENV{TZ};
562 if ($config{w3mmode}) {
563 eval q{use Cwd q{abs_path}};
565 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
566 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
567 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
568 unless $config{cgiurl} =~ m!file:///!;
569 $config{url}="file://".$config{destdir};
572 if ($config{cgi} && ! length $config{url}) {
573 error(gettext("Must specify url to wiki with --url when using --cgi"));
576 if (defined $config{url} && length $config{url}) {
578 my $baseurl = URI->new($config{url});
580 $local_url = $baseurl->path . "/";
581 $local_cgiurl = undef;
583 if (length $config{cgiurl}) {
584 my $cgiurl = URI->new($config{cgiurl});
586 $local_cgiurl = $cgiurl->path;
588 if ($cgiurl->scheme ne $baseurl->scheme or
589 $cgiurl->authority ne $baseurl->authority) {
590 # too far apart, fall back to absolute URLs
591 $local_url = "$config{url}/";
592 $local_cgiurl = $config{cgiurl};
596 $local_url =~ s{//$}{/};
599 $local_cgiurl = $config{cgiurl};
602 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
603 unless exists $config{wikistatedir} && defined $config{wikistatedir};
605 if (defined $config{umask}) {
606 my $u = possibly_foolish_untaint($config{umask});
608 if ($u =~ m/^\d+$/) {
611 elsif ($u eq 'private') {
614 elsif ($u eq 'group') {
617 elsif ($u eq 'public') {
621 error(sprintf(gettext("unsupported umask setting %s"), $u));
625 run_hooks(checkconfig => sub { shift->() });
633 foreach my $dir (@INC, $config{libdir}) {
634 next unless defined $dir && length $dir;
635 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
636 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
640 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
641 next unless defined $dir && length $dir;
642 foreach my $file (glob("$dir/plugins/*")) {
643 $ret{basename($file)}=1 if -x $file;
651 if (defined $config{libdir} && length $config{libdir}) {
652 unshift @INC, possibly_foolish_untaint($config{libdir});
655 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
660 if (exists $hooks{rcs}) {
661 error(gettext("cannot use multiple rcs plugins"));
663 loadplugin($config{rcs});
665 if (! exists $hooks{rcs}) {
669 run_hooks(getopt => sub { shift->() });
670 if (grep /^-/, @ARGV) {
671 print STDERR "Unknown option (or missing parameter): $_\n"
672 foreach grep /^-/, @ARGV;
679 sub loadplugin ($;$) {
683 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
685 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
686 "$installdir/lib/ikiwiki") {
687 if (defined $dir && -x "$dir/plugins/$plugin") {
688 eval { require IkiWiki::Plugin::external };
691 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
693 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
694 $loaded_plugins{$plugin}=1;
699 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
702 error("Failed to load plugin $mod: $@");
704 $loaded_plugins{$plugin}=1;
711 log_message('err' => $message) if $config{syslog};
712 if (defined $cleaner) {
719 return unless $config{verbose};
720 return log_message(debug => @_);
724 sub log_message ($$) {
727 if ($config{syslog}) {
730 Sys::Syslog::setlogsock('unix');
731 Sys::Syslog::openlog('ikiwiki', '', 'user');
735 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
738 elsif (! $config{cgi}) {
742 return print STDERR "@_\n";
746 sub possibly_foolish_untaint ($) {
748 my ($untainted)=$tainted=~/(.*)/s;
768 return exists $pagesources{$page} &&
769 $pagesources{$page} =~ /\._([^.]+)$/;
775 if ($file =~ /\.([^.]+)$/) {
776 return $1 if exists $hooks{htmlize}{$1};
778 my $base=basename($file);
779 if (exists $hooks{htmlize}{$base} &&
780 $hooks{htmlize}{$base}{noextension}) {
791 if (exists $pagename_cache{$file}) {
792 return $pagename_cache{$file};
795 my $type=pagetype($file);
797 $page=~s/\Q.$type\E*$//
798 if defined $type && !$hooks{htmlize}{$type}{keepextension}
799 && !$hooks{htmlize}{$type}{noextension};
800 if ($config{indexpages} && $page=~/(.*)\/index$/) {
804 $pagename_cache{$file} = $page;
808 sub newpagefile ($$) {
812 if (! $config{indexpages} || $page eq 'index') {
813 return $page.".".$type;
816 return $page."/index.".$type;
820 sub targetpage ($$;$) {
825 if (defined $filename) {
826 return $page."/".$filename.".".$ext;
828 elsif (! $config{usedirs} || $page eq 'index') {
829 return $page.".".$ext;
832 return $page."/index.".$ext;
839 return targetpage($page, $config{htmlext});
846 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
847 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
848 return "$dir/$file", stat(_) if -e "$dir/$file";
850 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
855 return (srcfile_stat(@_))[0];
858 sub add_literal_underlay ($) {
861 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
862 unshift @{$config{underlaydirs}}, $dir;
866 sub add_underlay ($) {
870 $dir="$config{underlaydirbase}/$dir";
873 add_literal_underlay($dir);
874 # why does it return 1? we just don't know
878 sub readfile ($;$$) {
884 error("cannot read a symlink ($file)");
888 open (my $in, "<", $file) || error("failed to read $file: $!");
889 binmode($in) if ($binary);
890 return \*$in if $wantfd;
892 # check for invalid utf-8, and toss it back to avoid crashes
893 if (! utf8::valid($ret)) {
894 $ret=encode_utf8($ret);
896 close $in || error("failed to read $file: $!");
900 sub prep_writefile ($$) {
905 while (length $test) {
906 if (-l "$destdir/$test") {
907 error("cannot write to a symlink ($test)");
909 if (-f _ && $test ne $file) {
910 # Remove conflicting file.
911 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
912 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
914 unlink("$destdir/$test");
920 $test=dirname($test);
923 my $dir=dirname("$destdir/$file");
926 foreach my $s (split(m!/+!, $dir)) {
929 mkdir($d) || error("failed to create directory $d: $!");
937 sub writefile ($$$;$$) {
938 my $file=shift; # can include subdirs
939 my $destdir=shift; # directory to put file in
944 prep_writefile($file, $destdir);
946 my $newfile="$destdir/$file.ikiwiki-new";
948 error("cannot write to a symlink ($newfile)");
951 my $cleanup = sub { unlink($newfile) };
952 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
953 binmode($out) if ($binary);
955 $writer->(\*$out, $cleanup);
958 print $out $content or error("failed writing to $newfile: $!", $cleanup);
960 close $out || error("failed saving $newfile: $!", $cleanup);
961 rename($newfile, "$destdir/$file") ||
962 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
968 sub will_render ($$;$) {
973 # Important security check for independently created files.
974 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
975 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
976 my $from_other_page=0;
977 # Expensive, but rarely runs.
978 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
982 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
988 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
989 unless $from_other_page;
992 # If $dest exists as a directory, remove conflicting files in it
993 # rendered from other pages.
995 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
996 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
997 if (dirname($f) eq $dest) {
998 unlink("$config{destdir}/$f");
999 rmdir(dirname("$config{destdir}/$f"));
1005 if (! $clear || $cleared{$page}) {
1006 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1009 foreach my $old (@{$renderedfiles{$page}}) {
1010 delete $destsources{$old};
1012 $renderedfiles{$page}=[$dest];
1015 $destsources{$dest}=$page;
1025 if ($link=~s/^\/+//) {
1033 $l.="/" if length $l;
1036 if (exists $pagesources{$l}) {
1039 elsif (exists $pagecase{lc $l}) {
1040 return $pagecase{lc $l};
1042 } while $cwd=~s{/?[^/]+$}{};
1044 if (length $config{userdir}) {
1045 my $l = "$config{userdir}/".lc($link);
1046 if (exists $pagesources{$l}) {
1049 elsif (exists $pagecase{lc $l}) {
1050 return $pagecase{lc $l};
1054 #print STDERR "warning: page $page, broken link: $link\n";
1058 sub isinlinableimage ($) {
1061 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1064 sub pagetitle ($;$) {
1066 my $unescaped=shift;
1069 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1072 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1080 # support use w/o %config set
1081 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1082 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1088 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1089 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1096 my $cgiurl=$local_cgiurl;
1098 if (exists $params{cgiurl}) {
1099 $cgiurl=$params{cgiurl};
1100 delete $params{cgiurl};
1108 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1111 sub cgiurl_abs (@) {
1113 URI->new_abs(cgiurl(@_), $config{cgiurl});
1119 return $local_url if ! defined $page;
1121 $page=htmlpage($page);
1123 $page=~s/[^\/]+\//..\//g;
1131 return $url unless defined $urlbase && length $urlbase;
1134 URI->new_abs($url, $urlbase)->as_string;
1138 # Work around very innefficient behavior in File::Spec if abs2rel
1139 # is passed two relative paths. It's much faster if paths are
1140 # absolute! (Debian bug #376658; fixed in debian unstable now)
1145 my $ret=File::Spec->abs2rel($path, $base);
1146 $ret=~s/^// if defined $ret;
1150 sub displaytime ($;$$) {
1151 # Plugins can override this function to mark up the time to
1153 my $time=formattime($_[0], $_[1]);
1154 if ($config{html5}) {
1155 return '<time datetime="'.date_3339($_[0]).'"'.
1156 ($_[2] ? ' pubdate="pubdate"' : '').
1157 '>'.$time.'</time>';
1160 return '<span class="date">'.$time.'</span>';
1164 sub formattime ($;$) {
1165 # Plugins can override this function to format the time.
1168 if (! defined $format) {
1169 $format=$config{timeformat};
1172 return strftime_utf8($format, localtime($time));
1175 my $strftime_encoding;
1177 # strftime doesn't know about encodings, so make sure
1178 # its output is properly treated as utf8.
1179 # Note that this does not handle utf-8 in the format string.
1180 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1181 unless defined $strftime_encoding;
1183 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1184 : POSIX::strftime(@_);
1190 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1191 POSIX::setlocale(&POSIX::LC_TIME, "C");
1192 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1193 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1197 sub beautify_urlpath ($) {
1200 # Ensure url is not an empty link, and if necessary,
1201 # add ./ to avoid colon confusion.
1202 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1206 if ($config{usedirs}) {
1207 $url =~ s!/index.$config{htmlext}$!/!;
1222 if (! $destsources{$to}) {
1227 return $config{url}.beautify_urlpath("/".$to);
1230 if (! defined $from) {
1231 my $u = $local_url || '';
1233 return $u.beautify_urlpath("/".$to);
1236 my $link = abs2rel($to, dirname(htmlpage($from)));
1238 return beautify_urlpath($link);
1241 sub isselflink ($$) {
1242 # Plugins can override this function to support special types
1247 return $page eq $link;
1250 sub htmllink ($$$;@) {
1251 my $lpage=shift; # the page doing the linking
1252 my $page=shift; # the page that will contain the link (different for inline)
1259 if (! $opts{forcesubpage}) {
1260 $bestlink=bestlink($lpage, $link);
1263 $bestlink="$lpage/".lc($link);
1267 if (defined $opts{linktext}) {
1268 $linktext=$opts{linktext};
1271 $linktext=pagetitle(basename($link));
1274 return "<span class=\"selflink\">$linktext</span>"
1275 if length $bestlink && isselflink($page, $bestlink) &&
1276 ! defined $opts{anchor};
1278 if (! $destsources{$bestlink}) {
1279 $bestlink=htmlpage($bestlink);
1281 if (! $destsources{$bestlink}) {
1283 if (length $config{cgiurl}) {
1284 $cgilink = "<a href=\"".
1289 )."\" rel=\"nofollow\">?</a>";
1291 return "<span class=\"createlink\">$cgilink$linktext</span>"
1295 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1296 $bestlink=beautify_urlpath($bestlink);
1298 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1299 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1302 if (defined $opts{anchor}) {
1303 $bestlink.="#".$opts{anchor};
1307 foreach my $attr (qw{rel class title}) {
1308 if (defined $opts{$attr}) {
1309 push @attrs, " $attr=\"$opts{$attr}\"";
1313 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1318 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1321 sub openiduser ($) {
1324 if (defined $user && $user =~ m!^https?://! &&
1325 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1328 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1329 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1332 # backcompat with old version
1333 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1334 $display=$oid->display;
1337 # Convert "user.somehost.com" to "user [somehost.com]"
1338 # (also "user.somehost.co.uk")
1339 if ($display !~ /\[/) {
1340 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1342 # Convert "http://somehost.com/user" to "user [somehost.com]".
1343 # (also "https://somehost.com/user/")
1344 if ($display !~ /\[/) {
1345 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1347 $display=~s!^https?://!!; # make sure this is removed
1348 eval q{use CGI 'escapeHTML'};
1350 return escapeHTML($display);
1355 sub htmlize ($$$$) {
1361 my $oneline = $content !~ /\n/;
1363 if (exists $hooks{htmlize}{$type}) {
1364 $content=$hooks{htmlize}{$type}{call}->(
1366 content => $content,
1370 error("htmlization of $type not supported");
1373 run_hooks(sanitize => sub {
1376 destpage => $destpage,
1377 content => $content,
1382 # hack to get rid of enclosing junk added by markdown
1383 # and other htmlizers/sanitizers
1384 $content=~s/^<p>//i;
1385 $content=~s/<\/p>\n*$//i;
1396 run_hooks(linkify => sub {
1399 destpage => $destpage,
1400 content => $content,
1408 our $preprocess_preview=0;
1409 sub preprocess ($$$;$$) {
1410 my $page=shift; # the page the data comes from
1411 my $destpage=shift; # the page the data will appear in (different for inline)
1416 # Using local because it needs to be set within any nested calls
1418 local $preprocess_preview=$preview if defined $preview;
1425 $params="" if ! defined $params;
1427 if (length $escape) {
1428 return "[[$prefix$command $params]]";
1430 elsif (exists $hooks{preprocess}{$command}) {
1431 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1432 # Note: preserve order of params, some plugins may
1433 # consider it significant.
1435 while ($params =~ m{
1436 (?:([-.\w]+)=)? # 1: named parameter key?
1438 """(.*?)""" # 2: triple-quoted value
1440 "([^"]*?)" # 3: single-quoted value
1442 '''(.*?)''' # 4: triple-single-quote
1444 <<([a-zA-Z]+)\n # 5: heredoc start
1445 (.*?)\n\5 # 6: heredoc value
1447 (\S+) # 7: unquoted value
1449 (?:\s+|$) # delimiter to next param
1459 elsif (defined $3) {
1462 elsif (defined $4) {
1465 elsif (defined $7) {
1468 elsif (defined $6) {
1473 push @params, $key, $val;
1476 push @params, $val, '';
1479 if ($preprocessing{$page}++ > 3) {
1480 # Avoid loops of preprocessed pages preprocessing
1481 # other pages that preprocess them, etc.
1482 return "[[!$command <span class=\"error\">".
1483 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1484 $page, $preprocessing{$page}).
1490 $hooks{preprocess}{$command}{call}->(
1493 destpage => $destpage,
1494 preview => $preprocess_preview,
1500 $ret="[[!$command <span class=\"error\">".
1501 gettext("Error").": $error"."</span>]]";
1505 # use void context during scan pass
1507 $hooks{preprocess}{$command}{call}->(
1510 destpage => $destpage,
1511 preview => $preprocess_preview,
1516 $preprocessing{$page}--;
1520 return "[[$prefix$command $params]]";
1525 if ($config{prefix_directives}) {
1528 \[\[(!) # directive open; 2: prefix
1529 ([-\w]+) # 3: command
1530 ( # 4: the parameters..
1531 \s+ # Must have space if parameters present
1533 (?:[-.\w]+=)? # named parameter key?
1535 """.*?""" # triple-quoted value
1537 "[^"]*?" # single-quoted value
1539 '''.*?''' # triple-single-quote
1541 <<([a-zA-Z]+)\n # 5: heredoc start
1542 (?:.*?)\n\5 # heredoc value
1544 [^"\s\]]+ # unquoted value
1546 \s* # whitespace or end
1549 *)? # 0 or more parameters
1550 \]\] # directive closed
1556 \[\[(!?) # directive open; 2: optional prefix
1557 ([-\w]+) # 3: command
1559 ( # 4: the parameters..
1561 (?:[-.\w]+=)? # named parameter key?
1563 """.*?""" # triple-quoted value
1565 "[^"]*?" # single-quoted value
1567 '''.*?''' # triple-single-quote
1569 <<([a-zA-Z]+)\n # 5: heredoc start
1570 (?:.*?)\n\5 # heredoc value
1572 [^"\s\]]+ # unquoted value
1574 \s* # whitespace or end
1577 *) # 0 or more parameters
1578 \]\] # directive closed
1582 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1591 run_hooks(filter => sub {
1592 $content=shift->(page => $page, destpage => $destpage,
1593 content => $content);
1599 sub check_canedit ($$$;$) {
1606 run_hooks(canedit => sub {
1607 return if defined $canedit;
1608 my $ret=shift->($page, $q, $session);
1613 elsif (ref $ret eq 'CODE') {
1614 $ret->() unless $nonfatal;
1617 elsif (defined $ret) {
1618 error($ret) unless $nonfatal;
1623 return defined $canedit ? $canedit : 1;
1626 sub check_content (@) {
1629 return 1 if ! exists $hooks{checkcontent}; # optimisation
1631 if (exists $pagesources{$params{page}}) {
1633 my %old=map { $_ => 1 }
1634 split("\n", readfile(srcfile($pagesources{$params{page}})));
1635 foreach my $line (split("\n", $params{content})) {
1636 push @diff, $line if ! exists $old{$line};
1638 $params{diff}=join("\n", @diff);
1642 run_hooks(checkcontent => sub {
1643 return if defined $ok;
1644 my $ret=shift->(%params);
1649 elsif (ref $ret eq 'CODE') {
1650 $ret->() unless $params{nonfatal};
1653 elsif (defined $ret) {
1654 error($ret) unless $params{nonfatal};
1660 return defined $ok ? $ok : 1;
1663 sub check_canchange (@) {
1665 my $cgi = $params{cgi};
1666 my $session = $params{session};
1667 my @changes = @{$params{changes}};
1670 foreach my $change (@changes) {
1671 # This untaint is safe because we check file_pruned and
1673 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1674 $file=possibly_foolish_untaint($file);
1675 if (! defined $file || ! length $file ||
1676 file_pruned($file)) {
1677 error(gettext("bad file name %s"), $file);
1680 my $type=pagetype($file);
1681 my $page=pagename($file) if defined $type;
1683 if ($change->{action} eq 'add') {
1687 if ($change->{action} eq 'change' ||
1688 $change->{action} eq 'add') {
1689 if (defined $page) {
1690 check_canedit($page, $cgi, $session);
1694 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1695 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1696 check_canedit($file, $cgi, $session);
1701 elsif ($change->{action} eq 'remove') {
1702 # check_canremove tests to see if the file is present
1703 # on disk. This will fail when a single commit adds a
1704 # file and then removes it again. Avoid the problem
1705 # by not testing the removal in such pairs of changes.
1706 # (The add is still tested, just to make sure that
1707 # no data is added to the repo that a web edit
1709 next if $newfiles{$file};
1711 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1712 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1713 check_canedit(defined $page ? $page : $file, $cgi, $session);
1718 error "unknown action ".$change->{action};
1721 error sprintf(gettext("you are not allowed to change %s"), $file);
1729 # Take an exclusive lock on the wiki to prevent multiple concurrent
1730 # run issues. The lock will be dropped on program exit.
1731 if (! -d $config{wikistatedir}) {
1732 mkdir($config{wikistatedir});
1734 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1735 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1736 if (! flock($wikilock, 2)) { # LOCK_EX
1737 error("failed to get lock");
1743 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1744 return close($wikilock) if $wikilock;
1750 sub commit_hook_enabled () {
1751 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1752 error("cannot write to $config{wikistatedir}/commitlock: $!");
1753 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1754 close($commitlock) || error("failed closing commitlock: $!");
1757 close($commitlock) || error("failed closing commitlock: $!");
1761 sub disable_commit_hook () {
1762 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1763 error("cannot write to $config{wikistatedir}/commitlock: $!");
1764 if (! flock($commitlock, 2)) { # LOCK_EX
1765 error("failed to get commit lock");
1770 sub enable_commit_hook () {
1771 return close($commitlock) if $commitlock;
1776 %oldrenderedfiles=%pagectime=();
1777 if (! $config{rebuild}) {
1778 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1779 %destsources=%renderedfiles=%pagecase=%pagestate=
1780 %depends_simple=%typedlinks=%oldtypedlinks=();
1783 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1784 if (-e "$config{wikistatedir}/index") {
1785 system("ikiwiki-transition", "indexdb", $config{srcdir});
1786 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1789 $config{gettime}=1; # first build
1794 my $index=Storable::fd_retrieve($in);
1795 if (! defined $index) {
1800 if (exists $index->{version} && ! ref $index->{version}) {
1801 $pages=$index->{page};
1802 %wikistate=%{$index->{state}};
1803 # Handle plugins that got disabled by loading a new setup.
1804 if (exists $config{setupfile}) {
1805 require IkiWiki::Setup;
1806 IkiWiki::Setup::disabled_plugins(
1807 grep { ! $loaded_plugins{$_} } keys %wikistate);
1815 foreach my $src (keys %$pages) {
1816 my $d=$pages->{$src};
1817 my $page=pagename($src);
1818 $pagectime{$page}=$d->{ctime};
1819 $pagesources{$page}=$src;
1820 if (! $config{rebuild}) {
1821 $pagemtime{$page}=$d->{mtime};
1822 $renderedfiles{$page}=$d->{dest};
1823 if (exists $d->{links} && ref $d->{links}) {
1824 $links{$page}=$d->{links};
1825 $oldlinks{$page}=[@{$d->{links}}];
1827 if (ref $d->{depends_simple} eq 'ARRAY') {
1829 $depends_simple{$page}={
1830 map { $_ => 1 } @{$d->{depends_simple}}
1833 elsif (exists $d->{depends_simple}) {
1834 $depends_simple{$page}=$d->{depends_simple};
1836 if (exists $d->{dependslist}) {
1839 map { $_ => $DEPEND_CONTENT }
1840 @{$d->{dependslist}}
1843 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1845 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1847 elsif (exists $d->{depends}) {
1848 $depends{$page}=$d->{depends};
1850 if (exists $d->{state}) {
1851 $pagestate{$page}=$d->{state};
1853 if (exists $d->{typedlinks}) {
1854 $typedlinks{$page}=$d->{typedlinks};
1856 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1857 next unless %$links;
1858 $oldtypedlinks{$page}{$type} = {%$links};
1862 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1864 foreach my $page (keys %pagesources) {
1865 $pagecase{lc $page}=$page;
1867 foreach my $page (keys %renderedfiles) {
1868 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1874 run_hooks(savestate => sub { shift->() });
1876 my @plugins=keys %loaded_plugins;
1878 if (! -d $config{wikistatedir}) {
1879 mkdir($config{wikistatedir});
1881 my $newfile="$config{wikistatedir}/indexdb.new";
1882 my $cleanup = sub { unlink($newfile) };
1883 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1886 foreach my $page (keys %pagemtime) {
1887 next unless $pagemtime{$page};
1888 my $src=$pagesources{$page};
1890 $index{page}{$src}={
1891 ctime => $pagectime{$page},
1892 mtime => $pagemtime{$page},
1893 dest => $renderedfiles{$page},
1894 links => $links{$page},
1897 if (exists $depends{$page}) {
1898 $index{page}{$src}{depends} = $depends{$page};
1901 if (exists $depends_simple{$page}) {
1902 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1905 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1906 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1909 if (exists $pagestate{$page}) {
1910 foreach my $id (@plugins) {
1911 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1912 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1919 foreach my $id (@plugins) {
1920 $index{state}{$id}={}; # used to detect disabled plugins
1921 foreach my $key (keys %{$wikistate{$id}}) {
1922 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1926 $index{version}="3";
1927 my $ret=Storable::nstore_fd(\%index, $out);
1928 return if ! defined $ret || ! $ret;
1929 close $out || error("failed saving to $newfile: $!", $cleanup);
1930 rename($newfile, "$config{wikistatedir}/indexdb") ||
1931 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1936 sub template_file ($) {
1939 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1941 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1942 $template=srcfile($pagesources{$tpage}, 1);
1946 $template=srcfile($tpage, 1);
1949 if (defined $template) {
1950 return $template, $tpage, 1 if wantarray;
1954 $name=~s:/::; # avoid path traversal
1955 foreach my $dir ($config{templatedir},
1956 "$installdir/share/ikiwiki/templates") {
1957 if (-e "$dir/$name") {
1958 $template="$dir/$name";
1962 if (defined $template) {
1963 return $template, $tpage if wantarray;
1971 sub template_depends ($$;@) {
1975 my ($filename, $tpage, $untrusted)=template_file($name);
1976 if (! defined $filename) {
1977 error(sprintf(gettext("template %s not found"), $name))
1980 if (defined $page && defined $tpage) {
1981 add_depends($page, $tpage);
1986 my $text_ref = shift;
1987 ${$text_ref} = decode_utf8(${$text_ref});
1989 loop_context_vars => 1,
1990 die_on_bad_params => 0,
1991 parent_global_vars => 1,
1992 filename => $filename,
1994 ($untrusted ? (no_includes => 1) : ()),
1996 return @opts if wantarray;
1998 require HTML::Template;
1999 return HTML::Template->new(@opts);
2002 sub template ($;@) {
2003 template_depends(shift, undef, @_);
2006 sub templateactions ($$) {
2012 run_hooks(pageactions => sub {
2013 push @actions, map { { action => $_ } }
2014 grep { defined } shift->(page => $page);
2016 $template->param(actions => \@actions);
2018 if ($config{cgiurl} && exists $hooks{auth}) {
2019 $template->param(prefsurl => cgiurl(do => "prefs"));
2023 if ($have_actions || @actions) {
2024 $template->param(have_actions => 1);
2031 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2032 error 'hook requires type, call, and id parameters';
2035 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2037 $hooks{$param{type}}{$param{id}}=\%param;
2041 sub run_hooks ($$) {
2042 # Calls the given sub for each hook of the given type,
2043 # passing it the hook function to call.
2047 if (exists $hooks{$type}) {
2048 my (@first, @middle, @last);
2049 foreach my $id (keys %{$hooks{$type}}) {
2050 if ($hooks{$type}{$id}{first}) {
2053 elsif ($hooks{$type}{$id}{last}) {
2060 foreach my $id (@first, @middle, @last) {
2061 $sub->($hooks{$type}{$id}{call});
2069 $hooks{rcs}{rcs_update}{call}->(@_);
2072 sub rcs_prepedit ($) {
2073 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2076 sub rcs_commit (@) {
2077 $hooks{rcs}{rcs_commit}{call}->(@_);
2080 sub rcs_commit_staged (@) {
2081 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2085 $hooks{rcs}{rcs_add}{call}->(@_);
2088 sub rcs_remove ($) {
2089 $hooks{rcs}{rcs_remove}{call}->(@_);
2092 sub rcs_rename ($$) {
2093 $hooks{rcs}{rcs_rename}{call}->(@_);
2096 sub rcs_recentchanges ($) {
2097 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2100 sub rcs_diff ($;$) {
2101 $hooks{rcs}{rcs_diff}{call}->(@_);
2104 sub rcs_getctime ($) {
2105 $hooks{rcs}{rcs_getctime}{call}->(@_);
2108 sub rcs_getmtime ($) {
2109 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2112 sub rcs_receive () {
2113 $hooks{rcs}{rcs_receive}{call}->();
2116 sub add_depends ($$;$) {
2119 my $deptype=shift || $DEPEND_CONTENT;
2121 # Is the pagespec a simple page name?
2122 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2123 $pagespec !~ /[\s*?()!]/) {
2124 $depends_simple{$page}{lc $pagespec} |= $deptype;
2128 # Add explicit dependencies for influences.
2129 my $sub=pagespec_translate($pagespec);
2130 return unless defined $sub;
2131 foreach my $p (keys %pagesources) {
2132 my $r=$sub->($p, location => $page);
2133 my $i=$r->influences;
2134 my $static=$r->influences_static;
2135 foreach my $k (keys %$i) {
2136 next unless $r || $static || $k eq $page;
2137 $depends_simple{$page}{lc $k} |= $i->{$k};
2142 $depends{$page}{$pagespec} |= $deptype;
2148 foreach my $type (@_) {
2149 if ($type eq 'presence') {
2150 $deptype |= $DEPEND_PRESENCE;
2152 elsif ($type eq 'links') {
2153 $deptype |= $DEPEND_LINKS;
2155 elsif ($type eq 'content') {
2156 $deptype |= $DEPEND_CONTENT;
2162 my $file_prune_regexp;
2163 sub file_pruned ($) {
2166 if (defined $config{include} && length $config{include}) {
2167 return 0 if $file =~ m/$config{include}/;
2170 if (! defined $file_prune_regexp) {
2171 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2172 $file_prune_regexp=qr/$file_prune_regexp/;
2174 return $file =~ m/$file_prune_regexp/;
2177 sub define_gettext () {
2178 # If translation is needed, redefine the gettext function to do it.
2179 # Otherwise, it becomes a quick no-op.
2182 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2183 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2184 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2186 $gettext_obj=eval q{
2187 use Locale::gettext q{textdomain};
2188 Locale::gettext->domain('ikiwiki')
2193 no warnings 'redefine';
2195 $getobj->() if $getobj;
2197 $gettext_obj->get(shift);
2204 $getobj->() if $getobj;
2206 $gettext_obj->nget(@_);
2209 return ($_[2] == 1 ? $_[0] : $_[1])
2227 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2231 # Injects a new function into the symbol table to replace an
2232 # exported function.
2235 # This is deep ugly perl foo, beware.
2238 if (! defined $params{parent}) {
2239 $params{parent}='::';
2240 $params{old}=\&{$params{name}};
2241 $params{name}=~s/.*:://;
2243 my $parent=$params{parent};
2244 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2245 $ns = $params{parent} . $ns;
2246 inject(%params, parent => $ns) unless $ns eq '::main::';
2247 *{$ns . $params{name}} = $params{call}
2248 if exists ${$ns}{$params{name}} &&
2249 \&{${$ns}{$params{name}}} == $params{old};
2255 sub add_link ($$;$) {
2260 push @{$links{$page}}, $link
2261 unless grep { $_ eq $link } @{$links{$page}};
2263 if (defined $type) {
2264 $typedlinks{$page}{$type}{$link} = 1;
2268 sub add_autofile ($$$) {
2271 my $generator=shift;
2273 $autofiles{$file}{plugin}=$plugin;
2274 $autofiles{$file}{generator}=$generator;
2277 sub sortspec_translate ($$) {
2279 my $reverse = shift;
2285 (-?) # group 1: perhaps negated
2288 \w+\([^\)]*\) # command(params)
2290 [^\s]+ # or anything else
2298 if ($word =~ m/^(\w+)\((.*)\)$/) {
2299 # command with parameters
2303 elsif ($word !~ m/^\w+$/) {
2304 error(sprintf(gettext("invalid sort type %s"), $word));
2315 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2316 if (defined $params) {
2317 push @data, $params;
2318 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2321 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2325 error(sprintf(gettext("unknown sort type %s"), $word));
2329 if (! length $code) {
2330 # undefined sorting method... sort arbitrarily
2339 return eval 'sub { '.$code.' }';
2342 sub pagespec_translate ($) {
2345 # Convert spec to perl code.
2349 \s* # ignore whitespace
2350 ( # 1: match a single word
2357 \w+\([^\)]*\) # command(params)
2359 [^\s()]+ # any other text
2361 \s* # ignore whitespace
2364 if (lc $word eq 'and') {
2367 elsif (lc $word eq 'or') {
2370 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2373 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2374 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2376 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2379 push @data, qq{unknown function in pagespec "$word"};
2380 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2385 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2389 if (! length $code) {
2390 $code="IkiWiki::FailReason->new('empty pagespec')";
2394 return eval 'sub { my $page=shift; '.$code.' }';
2397 sub pagespec_match ($$;@) {
2402 # Backwards compatability with old calling convention.
2404 unshift @params, 'location';
2407 my $sub=pagespec_translate($spec);
2408 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2410 return $sub->($page, @params);
2413 sub pagespec_match_list ($$;@) {
2418 # Backwards compatability with old calling convention.
2420 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2421 $params{list}=$page;
2422 $page=$params{location}; # ugh!
2425 my $sub=pagespec_translate($pagespec);
2426 error "syntax error in pagespec \"$pagespec\""
2428 my $sort=sortspec_translate($params{sort}, $params{reverse})
2429 if defined $params{sort};
2432 if (exists $params{list}) {
2433 @candidates=exists $params{filter}
2434 ? grep { ! $params{filter}->($_) } @{$params{list}}
2438 @candidates=exists $params{filter}
2439 ? grep { ! $params{filter}->($_) } keys %pagesources
2440 : keys %pagesources;
2443 # clear params, remainder is passed to pagespec
2444 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2445 my $num=$params{num};
2446 delete @params{qw{num deptype reverse sort filter list}};
2448 # when only the top matches will be returned, it's efficient to
2449 # sort before matching to pagespec,
2450 if (defined $num && defined $sort) {
2451 @candidates=IkiWiki::SortSpec::sort_pages(
2452 $sort, @candidates);
2458 my $accum=IkiWiki::SuccessReason->new();
2459 foreach my $p (@candidates) {
2460 my $r=$sub->($p, %params, location => $page);
2461 error(sprintf(gettext("cannot match pages: %s"), $r))
2462 if $r->isa("IkiWiki::ErrorReason");
2463 unless ($r || $r->influences_static) {
2464 $r->remove_influence($p);
2469 last if defined $num && ++$count == $num;
2473 # Add simple dependencies for accumulated influences.
2474 my $i=$accum->influences;
2475 foreach my $k (keys %$i) {
2476 $depends_simple{$page}{lc $k} |= $i->{$k};
2479 # when all matches will be returned, it's efficient to
2480 # sort after matching
2481 if (! defined $num && defined $sort) {
2482 return IkiWiki::SortSpec::sort_pages(
2490 sub pagespec_valid ($) {
2493 return defined pagespec_translate($spec);
2497 my $re=quotemeta(shift);
2503 package IkiWiki::FailReason;
2506 '""' => sub { $_[0][0] },
2508 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2509 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2510 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2514 our @ISA = 'IkiWiki::SuccessReason';
2516 package IkiWiki::SuccessReason;
2519 '""' => sub { $_[0][0] },
2521 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2522 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2523 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2530 return bless [$value, {@_}], $class;
2535 $this->[1]={@_} if @_;
2536 my %i=%{$this->[1]};
2541 sub influences_static {
2542 return ! $_[0][1]->{""};
2545 sub merge_influences {
2550 if (! $anded || (($this || %{$this->[1]}) &&
2551 ($other || %{$other->[1]}))) {
2552 foreach my $influence (keys %{$other->[1]}) {
2553 $this->[1]{$influence} |= $other->[1]{$influence};
2562 sub remove_influence {
2566 delete $this->[1]{$torm};
2569 package IkiWiki::ErrorReason;
2571 our @ISA = 'IkiWiki::FailReason';
2573 package IkiWiki::PageSpec;
2579 if ($path =~ m!^\.(/|$)!) {
2581 $from=~s#/?[^/]+$## if defined $from;
2583 $path="$from/$path" if defined $from && length $from;
2587 $path = "" unless defined $path;
2596 sub match_glob ($$;@) {
2601 $glob=derel($glob, $params{location});
2603 # Instead of converting the glob to a regex every time,
2604 # cache the compiled regex to save time.
2605 my $re=$glob_cache{$glob};
2606 unless (defined $re) {
2607 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2610 if (! IkiWiki::isinternal($page) || $params{internal}) {
2611 return IkiWiki::SuccessReason->new("$glob matches $page");
2614 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2618 return IkiWiki::FailReason->new("$glob does not match $page");
2622 sub match_internal ($$;@) {
2623 return match_glob(shift, shift, @_, internal => 1)
2626 sub match_page ($$;@) {
2628 my $match=match_glob($page, shift, @_);
2630 my $source=exists $IkiWiki::pagesources{$page} ?
2631 $IkiWiki::pagesources{$page} :
2632 $IkiWiki::delpagesources{$page};
2633 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2634 if (! defined $type) {
2635 return IkiWiki::FailReason->new("$page is not a page");
2641 sub match_link ($$;@) {
2646 $link=derel($link, $params{location});
2647 my $from=exists $params{location} ? $params{location} : '';
2648 my $linktype=$params{linktype};
2650 if (defined $linktype) {
2651 $qualifier=" with type $linktype";
2654 my $links = $IkiWiki::links{$page};
2655 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2656 unless $links && @{$links};
2657 my $bestlink = IkiWiki::bestlink($from, $link);
2658 foreach my $p (@{$links}) {
2659 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2661 if (length $bestlink) {
2662 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2663 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2667 if (match_glob($p, $link, %params)) {
2668 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2670 my ($p_rel)=$p=~/^\/?(.*)/;
2672 if (match_glob($p_rel, $link, %params)) {
2673 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2677 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2680 sub match_backlink ($$;@) {
2684 if ($testpage eq '.') {
2685 $testpage = $params{'location'}
2687 my $ret=match_link($testpage, $page, @_);
2688 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2692 sub match_created_before ($$;@) {
2697 $testpage=derel($testpage, $params{location});
2699 if (exists $IkiWiki::pagectime{$testpage}) {
2700 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2701 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2704 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2708 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2712 sub match_created_after ($$;@) {
2717 $testpage=derel($testpage, $params{location});
2719 if (exists $IkiWiki::pagectime{$testpage}) {
2720 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2721 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2724 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2728 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2732 sub match_creation_day ($$;@) {
2735 if ($d !~ /^\d+$/) {
2736 return IkiWiki::ErrorReason->new("invalid day $d");
2738 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2739 return IkiWiki::SuccessReason->new('creation_day matched');
2742 return IkiWiki::FailReason->new('creation_day did not match');
2746 sub match_creation_month ($$;@) {
2749 if ($m !~ /^\d+$/) {
2750 return IkiWiki::ErrorReason->new("invalid month $m");
2752 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2753 return IkiWiki::SuccessReason->new('creation_month matched');
2756 return IkiWiki::FailReason->new('creation_month did not match');
2760 sub match_creation_year ($$;@) {
2763 if ($y !~ /^\d+$/) {
2764 return IkiWiki::ErrorReason->new("invalid year $y");
2766 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2767 return IkiWiki::SuccessReason->new('creation_year matched');
2770 return IkiWiki::FailReason->new('creation_year did not match');
2774 sub match_user ($$;@) {
2779 my $regexp=IkiWiki::glob2re($user);
2781 if (! exists $params{user}) {
2782 return IkiWiki::ErrorReason->new("no user specified");
2785 if (defined $params{user} && $params{user}=~$regexp) {
2786 return IkiWiki::SuccessReason->new("user is $user");
2788 elsif (! defined $params{user}) {
2789 return IkiWiki::FailReason->new("not logged in");
2792 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2796 sub match_admin ($$;@) {
2801 if (! exists $params{user}) {
2802 return IkiWiki::ErrorReason->new("no user specified");
2805 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2806 return IkiWiki::SuccessReason->new("user is an admin");
2808 elsif (! defined $params{user}) {
2809 return IkiWiki::FailReason->new("not logged in");
2812 return IkiWiki::FailReason->new("user is not an admin");
2816 sub match_ip ($$;@) {
2821 if (! exists $params{ip}) {
2822 return IkiWiki::ErrorReason->new("no IP specified");
2825 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2826 return IkiWiki::SuccessReason->new("IP is $ip");
2829 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2833 package IkiWiki::SortSpec;
2835 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2836 # are easily available in this namespace, for cmp functions to use them.
2843 IkiWiki::pagetitle(IkiWiki::basename($a))
2845 IkiWiki::pagetitle(IkiWiki::basename($b))
2848 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2849 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2850 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }