8 use URI::Escape q{uri_escape_utf8};
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %linkbases %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 %linkbases %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)",
124 description => "rcs backend to use",
125 safe => 0, # don't allow overriding
130 default => [qw{mdwn link inline meta htmlscrubber passwordauth
131 openid signinedit lockedit conditional
132 recentchanges parentlinks editpage}],
133 description => "plugins to enable by default",
140 description => "plugins to add to the default configuration",
147 description => "plugins to disable",
153 default => "$installdir/share/ikiwiki/templates",
154 description => "additional directory to search for template files",
161 default => "$installdir/share/ikiwiki/basewiki",
162 description => "base wiki source location",
169 default => "$installdir/share/ikiwiki",
170 description => "parent directory containing additional underlays",
177 description => "wrappers to generate",
184 description => "additional underlays to use",
191 description => "display verbose messages?",
198 description => "log to syslog?",
205 description => "create output files named page/index.html?",
206 safe => 0, # changing requires manual transition
209 prefix_directives => {
212 description => "use '!'-prefixed preprocessor directives?",
213 safe => 0, # changing requires manual transition
219 description => "use page/index.mdwn source files",
226 description => "enable Discussion pages?",
232 default => gettext("Discussion"),
233 description => "name of Discussion pages",
240 description => "generate HTML5?",
248 description => "only send cookies over SSL connections?",
256 description => "extension to use for new pages",
257 safe => 0, # not sanitized
263 description => "extension to use for html files",
264 safe => 0, # not sanitized
270 description => "strftime format string to display date",
278 example => "en_US.UTF-8",
279 description => "UTF-8 locale to use",
288 description => "put user pages below specified page",
295 description => "how many backlinks to show before hiding excess (0 to show all)",
302 description => "attempt to hardlink source files? (optimisation for large files)",
304 safe => 0, # paranoia
310 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
312 safe => 0, # paranoia
317 example => "ikiwiki",
318 description => "group for wrappers to run in",
320 safe => 0, # paranoia
326 example => "$ENV{HOME}/.ikiwiki/",
327 description => "extra library and plugin directory",
329 safe => 0, # directory
335 description => "environment variables",
336 safe => 0, # paranoia
342 example => "US/Eastern",
343 description => "time zone name",
350 example => '^\.htaccess$',
351 description => "regexp of normally excluded files to include",
359 example => '^(*\.private|Makefile)$',
360 description => "regexp of files that should be skipped",
365 wiki_file_prune_regexps => {
367 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
368 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
369 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
370 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
371 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
372 description => "regexps of source files to ignore",
378 description => "specifies the characters that are allowed in source filenames",
379 default => "-[:alnum:]+/.:_",
383 wiki_file_regexp => {
385 description => "regexp of legal source files",
389 web_commit_regexp => {
391 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
392 description => "regexp to parse web commits from logs",
399 description => "run as a cgi",
403 cgi_disable_uploads => {
406 description => "whether CGI should accept file uploads",
413 description => "run as a post-commit hook",
420 description => "running in rebuild mode",
427 description => "running in setup mode",
434 description => "running in clean mode",
441 description => "running in refresh mode",
448 description => "running in receive test mode",
452 wrapper_background_command => {
455 description => "background shell command to run",
461 description => "running in gettime mode",
468 description => "running in w3mmode",
475 description => "path to the .ikiwiki directory holding ikiwiki state",
482 description => "path to setup file",
489 description => "perl class to use to dump setup file",
493 allow_symlinks_before_srcdir => {
496 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
502 sub defaultconfig () {
505 foreach my $key (keys %s) {
506 push @ret, $key, $s{$key}->{default};
511 # URL to top of wiki as a path starting with /, valid from any wiki page or
512 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
514 # URL to CGI script, similar to $local_url
518 # locale stuff; avoid LC_ALL since it overrides everything
519 if (defined $ENV{LC_ALL}) {
520 $ENV{LANG} = $ENV{LC_ALL};
523 if (defined $config{locale}) {
524 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
525 $ENV{LANG}=$config{locale};
530 if (! defined $config{wiki_file_regexp}) {
531 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
534 if (ref $config{ENV} eq 'HASH') {
535 foreach my $val (keys %{$config{ENV}}) {
536 $ENV{$val}=$config{ENV}{$val};
539 if (defined $config{timezone} && length $config{timezone}) {
540 $ENV{TZ}=$config{timezone};
543 $config{timezone}=$ENV{TZ};
546 if ($config{w3mmode}) {
547 eval q{use Cwd q{abs_path}};
549 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
550 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
551 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
552 unless $config{cgiurl} =~ m!file:///!;
553 $config{url}="file://".$config{destdir};
556 if ($config{cgi} && ! length $config{url}) {
557 error(gettext("Must specify url to wiki with --url when using --cgi"));
560 if (defined $config{url} && length $config{url}) {
562 my $baseurl = URI->new($config{url});
564 $local_url = $baseurl->path . "/";
565 $local_cgiurl = undef;
567 if (length $config{cgiurl}) {
568 my $cgiurl = URI->new($config{cgiurl});
570 $local_cgiurl = $cgiurl->path;
572 if ($cgiurl->scheme ne $baseurl->scheme or
573 $cgiurl->authority ne $baseurl->authority) {
574 # too far apart, fall back to absolute URLs
575 $local_url = "$config{url}/";
576 $local_cgiurl = $config{cgiurl};
580 $local_url =~ s{//$}{/};
583 $local_cgiurl = $config{cgiurl};
586 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
587 unless exists $config{wikistatedir} && defined $config{wikistatedir};
589 if (defined $config{umask}) {
590 my $u = possibly_foolish_untaint($config{umask});
592 if ($u =~ m/^\d+$/) {
595 elsif ($u eq 'private') {
598 elsif ($u eq 'group') {
601 elsif ($u eq 'public') {
605 error(sprintf(gettext("unsupported umask setting %s"), $u));
609 run_hooks(checkconfig => sub { shift->() });
617 foreach my $dir (@INC, $config{libdir}) {
618 next unless defined $dir && length $dir;
619 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
620 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
624 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
625 next unless defined $dir && length $dir;
626 foreach my $file (glob("$dir/plugins/*")) {
627 $ret{basename($file)}=1 if -x $file;
635 if (defined $config{libdir} && length $config{libdir}) {
636 unshift @INC, possibly_foolish_untaint($config{libdir});
639 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
644 if (exists $hooks{rcs}) {
645 error(gettext("cannot use multiple rcs plugins"));
647 loadplugin($config{rcs});
649 if (! exists $hooks{rcs}) {
653 run_hooks(getopt => sub { shift->() });
654 if (grep /^-/, @ARGV) {
655 print STDERR "Unknown option (or missing parameter): $_\n"
656 foreach grep /^-/, @ARGV;
663 sub loadplugin ($;$) {
667 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
669 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
670 "$installdir/lib/ikiwiki") {
671 if (defined $dir && -x "$dir/plugins/$plugin") {
672 eval { require IkiWiki::Plugin::external };
675 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
677 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
678 $loaded_plugins{$plugin}=1;
683 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
686 error("Failed to load plugin $mod: $@");
688 $loaded_plugins{$plugin}=1;
695 log_message('err' => $message) if $config{syslog};
696 if (defined $cleaner) {
703 return unless $config{verbose};
704 return log_message(debug => @_);
708 sub log_message ($$) {
711 if ($config{syslog}) {
714 Sys::Syslog::setlogsock('unix');
715 Sys::Syslog::openlog('ikiwiki', '', 'user');
719 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
722 elsif (! $config{cgi}) {
726 return print STDERR "@_\n";
730 sub possibly_foolish_untaint ($) {
732 my ($untainted)=$tainted=~/(.*)/s;
752 return exists $pagesources{$page} &&
753 $pagesources{$page} =~ /\._([^.]+)$/;
759 if ($file =~ /\.([^.]+)$/) {
760 return $1 if exists $hooks{htmlize}{$1};
762 my $base=basename($file);
763 if (exists $hooks{htmlize}{$base} &&
764 $hooks{htmlize}{$base}{noextension}) {
775 if (exists $pagename_cache{$file}) {
776 return $pagename_cache{$file};
779 my $type=pagetype($file);
781 $page=~s/\Q.$type\E*$//
782 if defined $type && !$hooks{htmlize}{$type}{keepextension}
783 && !$hooks{htmlize}{$type}{noextension};
784 if ($config{indexpages} && $page=~/(.*)\/index$/) {
788 $pagename_cache{$file} = $page;
792 sub newpagefile ($$) {
796 if (! $config{indexpages} || $page eq 'index') {
797 return $page.".".$type;
800 return $page."/index.".$type;
804 sub targetpage ($$;$) {
809 if (defined $filename) {
810 return $page."/".$filename.".".$ext;
812 elsif (! $config{usedirs} || $page eq 'index') {
813 return $page.".".$ext;
816 return $page."/index.".$ext;
823 return targetpage($page, $config{htmlext});
830 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
831 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
832 return "$dir/$file", stat(_) if -e "$dir/$file";
834 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
839 return (srcfile_stat(@_))[0];
842 sub add_literal_underlay ($) {
845 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
846 unshift @{$config{underlaydirs}}, $dir;
850 sub add_underlay ($) {
854 $dir="$config{underlaydirbase}/$dir";
857 add_literal_underlay($dir);
858 # why does it return 1? we just don't know
862 sub readfile ($;$$) {
868 error("cannot read a symlink ($file)");
872 open (my $in, "<", $file) || error("failed to read $file: $!");
873 binmode($in) if ($binary);
874 return \*$in if $wantfd;
876 # check for invalid utf-8, and toss it back to avoid crashes
877 if (! utf8::valid($ret)) {
878 $ret=encode_utf8($ret);
880 close $in || error("failed to read $file: $!");
884 sub prep_writefile ($$) {
889 while (length $test) {
890 if (-l "$destdir/$test") {
891 error("cannot write to a symlink ($test)");
893 if (-f _ && $test ne $file) {
894 # Remove conflicting file.
895 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
896 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
898 unlink("$destdir/$test");
904 $test=dirname($test);
907 my $dir=dirname("$destdir/$file");
910 foreach my $s (split(m!/+!, $dir)) {
913 mkdir($d) || error("failed to create directory $d: $!");
921 sub writefile ($$$;$$) {
922 my $file=shift; # can include subdirs
923 my $destdir=shift; # directory to put file in
928 prep_writefile($file, $destdir);
930 my $newfile="$destdir/$file.ikiwiki-new";
932 error("cannot write to a symlink ($newfile)");
935 my $cleanup = sub { unlink($newfile) };
936 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
937 binmode($out) if ($binary);
939 $writer->(\*$out, $cleanup);
942 print $out $content or error("failed writing to $newfile: $!", $cleanup);
944 close $out || error("failed saving $newfile: $!", $cleanup);
945 rename($newfile, "$destdir/$file") ||
946 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
952 sub will_render ($$;$) {
957 # Important security check for independently created files.
958 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
959 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
960 my $from_other_page=0;
961 # Expensive, but rarely runs.
962 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
966 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
972 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
973 unless $from_other_page;
976 # If $dest exists as a directory, remove conflicting files in it
977 # rendered from other pages.
979 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
980 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
981 if (dirname($f) eq $dest) {
982 unlink("$config{destdir}/$f");
983 rmdir(dirname("$config{destdir}/$f"));
989 if (! $clear || $cleared{$page}) {
990 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
993 foreach my $old (@{$renderedfiles{$page}}) {
994 delete $destsources{$old};
996 $renderedfiles{$page}=[$dest];
999 $destsources{$dest}=$page;
1009 if ($link=~s/^\/+//) {
1013 foreach my $spec (keys %{$linkbases{pagespec}}) {
1014 if (pagespec_match($page, $spec)) {
1015 unshift @bases, @{$linkbases{pagespec}{$spec}};
1018 if (defined $linkbases{page}{$page}) {
1019 unshift @bases, @{$linkbases{page}{$page}};
1021 unshift @bases, $page;
1025 foreach my $cwd (@bases) {
1028 $l.="/" if length $l;
1031 if (exists $pagesources{$l}) {
1034 elsif (exists $pagecase{lc $l}) {
1035 return $pagecase{lc $l};
1037 } while $cwd=~s{/?[^/]+$}{};
1040 if (length $config{userdir}) {
1041 my $l = "$config{userdir}/".lc($link);
1042 if (exists $pagesources{$l}) {
1045 elsif (exists $pagecase{lc $l}) {
1046 return $pagecase{lc $l};
1050 #print STDERR "warning: page $page, broken link: $link\n";
1054 sub isinlinableimage ($) {
1057 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1060 sub pagetitle ($;$) {
1062 my $unescaped=shift;
1065 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1068 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1076 # support use w/o %config set
1077 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1078 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1084 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1085 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1092 my $cgiurl=$local_cgiurl;
1094 if (exists $params{cgiurl}) {
1095 $cgiurl=$params{cgiurl};
1096 delete $params{cgiurl};
1104 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1107 sub cgiurl_abs (@) {
1109 URI->new_abs(cgiurl(@_), $config{cgiurl});
1115 return $local_url if ! defined $page;
1117 $page=htmlpage($page);
1119 $page=~s/[^\/]+\//..\//g;
1127 return $url unless defined $urlbase && length $urlbase;
1130 URI->new_abs($url, $urlbase)->as_string;
1134 # Work around very innefficient behavior in File::Spec if abs2rel
1135 # is passed two relative paths. It's much faster if paths are
1136 # absolute! (Debian bug #376658; fixed in debian unstable now)
1141 my $ret=File::Spec->abs2rel($path, $base);
1142 $ret=~s/^// if defined $ret;
1146 sub displaytime ($;$$) {
1147 # Plugins can override this function to mark up the time to
1149 my $time=formattime($_[0], $_[1]);
1150 if ($config{html5}) {
1151 return '<time datetime="'.date_3339($_[0]).'"'.
1152 ($_[2] ? ' pubdate="pubdate"' : '').
1153 '>'.$time.'</time>';
1156 return '<span class="date">'.$time.'</span>';
1160 sub formattime ($;$) {
1161 # Plugins can override this function to format the time.
1164 if (! defined $format) {
1165 $format=$config{timeformat};
1168 return strftime_utf8($format, localtime($time));
1171 my $strftime_encoding;
1173 # strftime doesn't know about encodings, so make sure
1174 # its output is properly treated as utf8.
1175 # Note that this does not handle utf-8 in the format string.
1176 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1177 unless defined $strftime_encoding;
1179 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1180 : POSIX::strftime(@_);
1186 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1187 POSIX::setlocale(&POSIX::LC_TIME, "C");
1188 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1189 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1193 sub beautify_urlpath ($) {
1196 # Ensure url is not an empty link, and if necessary,
1197 # add ./ to avoid colon confusion.
1198 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1202 if ($config{usedirs}) {
1203 $url =~ s!/index.$config{htmlext}$!/!;
1218 if (! $destsources{$to}) {
1223 return $config{url}.beautify_urlpath("/".$to);
1226 if (! defined $from) {
1227 my $u = $local_url || '';
1229 return $u.beautify_urlpath("/".$to);
1232 my $link = abs2rel($to, dirname(htmlpage($from)));
1234 return beautify_urlpath($link);
1237 sub isselflink ($$) {
1238 # Plugins can override this function to support special types
1243 return $page eq $link;
1246 sub htmllink ($$$;@) {
1247 my $lpage=shift; # the page doing the linking
1248 my $page=shift; # the page that will contain the link (different for inline)
1255 if (! $opts{forcesubpage}) {
1256 $bestlink=bestlink($lpage, $link);
1259 $bestlink="$lpage/".lc($link);
1263 if (defined $opts{linktext}) {
1264 $linktext=$opts{linktext};
1267 $linktext=pagetitle(basename($link));
1270 return "<span class=\"selflink\">$linktext</span>"
1271 if length $bestlink && isselflink($page, $bestlink) &&
1272 ! defined $opts{anchor};
1274 if (! $destsources{$bestlink}) {
1275 $bestlink=htmlpage($bestlink);
1277 if (! $destsources{$bestlink}) {
1279 if (length $config{cgiurl}) {
1280 $cgilink = "<a href=\"".
1285 )."\" rel=\"nofollow\">?</a>";
1287 return "<span class=\"createlink\">$cgilink$linktext</span>"
1291 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1292 $bestlink=beautify_urlpath($bestlink);
1294 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1295 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1298 if (defined $opts{anchor}) {
1299 $bestlink.="#".$opts{anchor};
1303 foreach my $attr (qw{rel class title}) {
1304 if (defined $opts{$attr}) {
1305 push @attrs, " $attr=\"$opts{$attr}\"";
1309 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1314 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1317 sub openiduser ($) {
1320 if (defined $user && $user =~ m!^https?://! &&
1321 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1324 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1325 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1328 # backcompat with old version
1329 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1330 $display=$oid->display;
1333 # Convert "user.somehost.com" to "user [somehost.com]"
1334 # (also "user.somehost.co.uk")
1335 if ($display !~ /\[/) {
1336 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1338 # Convert "http://somehost.com/user" to "user [somehost.com]".
1339 # (also "https://somehost.com/user/")
1340 if ($display !~ /\[/) {
1341 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1343 $display=~s!^https?://!!; # make sure this is removed
1344 eval q{use CGI 'escapeHTML'};
1346 return escapeHTML($display);
1351 sub htmlize ($$$$) {
1357 my $oneline = $content !~ /\n/;
1359 if (exists $hooks{htmlize}{$type}) {
1360 $content=$hooks{htmlize}{$type}{call}->(
1362 content => $content,
1366 error("htmlization of $type not supported");
1369 run_hooks(sanitize => sub {
1372 destpage => $destpage,
1373 content => $content,
1378 # hack to get rid of enclosing junk added by markdown
1379 # and other htmlizers/sanitizers
1380 $content=~s/^<p>//i;
1381 $content=~s/<\/p>\n*$//i;
1392 run_hooks(linkify => sub {
1395 destpage => $destpage,
1396 content => $content,
1404 our $preprocess_preview=0;
1405 sub preprocess ($$$;$$) {
1406 my $page=shift; # the page the data comes from
1407 my $destpage=shift; # the page the data will appear in (different for inline)
1412 # Using local because it needs to be set within any nested calls
1414 local $preprocess_preview=$preview if defined $preview;
1421 $params="" if ! defined $params;
1423 if (length $escape) {
1424 return "[[$prefix$command $params]]";
1426 elsif (exists $hooks{preprocess}{$command}) {
1427 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1428 # Note: preserve order of params, some plugins may
1429 # consider it significant.
1431 while ($params =~ m{
1432 (?:([-\w]+)=)? # 1: named parameter key?
1434 """(.*?)""" # 2: triple-quoted value
1436 "([^"]*?)" # 3: single-quoted value
1438 '''(.*?)''' # 4: triple-single-quote
1440 <<([a-zA-Z]+)\n # 5: heredoc start
1441 (.*?)\n\5 # 6: heredoc value
1443 (\S+) # 7: unquoted value
1445 (?:\s+|$) # delimiter to next param
1455 elsif (defined $3) {
1458 elsif (defined $4) {
1461 elsif (defined $7) {
1464 elsif (defined $6) {
1469 push @params, $key, $val;
1472 push @params, $val, '';
1475 if ($preprocessing{$page}++ > 3) {
1476 # Avoid loops of preprocessed pages preprocessing
1477 # other pages that preprocess them, etc.
1478 return "[[!$command <span class=\"error\">".
1479 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1480 $page, $preprocessing{$page}).
1486 $hooks{preprocess}{$command}{call}->(
1489 destpage => $destpage,
1490 preview => $preprocess_preview,
1496 $ret="[[!$command <span class=\"error\">".
1497 gettext("Error").": $error"."</span>]]";
1501 # use void context during scan pass
1503 $hooks{preprocess}{$command}{call}->(
1506 destpage => $destpage,
1507 preview => $preprocess_preview,
1512 $preprocessing{$page}--;
1516 return "[[$prefix$command $params]]";
1521 if ($config{prefix_directives}) {
1524 \[\[(!) # directive open; 2: prefix
1525 ([-\w]+) # 3: command
1526 ( # 4: the parameters..
1527 \s+ # Must have space if parameters present
1529 (?:[-\w]+=)? # named parameter key?
1531 """.*?""" # triple-quoted value
1533 "[^"]*?" # single-quoted value
1535 '''.*?''' # triple-single-quote
1537 <<([a-zA-Z]+)\n # 5: heredoc start
1538 (?:.*?)\n\5 # heredoc value
1540 [^"\s\]]+ # unquoted value
1542 \s* # whitespace or end
1545 *)? # 0 or more parameters
1546 \]\] # directive closed
1552 \[\[(!?) # directive open; 2: optional prefix
1553 ([-\w]+) # 3: command
1555 ( # 4: the parameters..
1557 (?:[-\w]+=)? # named parameter key?
1559 """.*?""" # triple-quoted value
1561 "[^"]*?" # single-quoted value
1563 '''.*?''' # triple-single-quote
1565 <<([a-zA-Z]+)\n # 5: heredoc start
1566 (?:.*?)\n\5 # heredoc value
1568 [^"\s\]]+ # unquoted value
1570 \s* # whitespace or end
1573 *) # 0 or more parameters
1574 \]\] # directive closed
1578 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1587 run_hooks(filter => sub {
1588 $content=shift->(page => $page, destpage => $destpage,
1589 content => $content);
1595 sub check_canedit ($$$;$) {
1602 run_hooks(canedit => sub {
1603 return if defined $canedit;
1604 my $ret=shift->($page, $q, $session);
1609 elsif (ref $ret eq 'CODE') {
1610 $ret->() unless $nonfatal;
1613 elsif (defined $ret) {
1614 error($ret) unless $nonfatal;
1619 return defined $canedit ? $canedit : 1;
1622 sub check_content (@) {
1625 return 1 if ! exists $hooks{checkcontent}; # optimisation
1627 if (exists $pagesources{$params{page}}) {
1629 my %old=map { $_ => 1 }
1630 split("\n", readfile(srcfile($pagesources{$params{page}})));
1631 foreach my $line (split("\n", $params{content})) {
1632 push @diff, $line if ! exists $old{$line};
1634 $params{diff}=join("\n", @diff);
1638 run_hooks(checkcontent => sub {
1639 return if defined $ok;
1640 my $ret=shift->(%params);
1645 elsif (ref $ret eq 'CODE') {
1646 $ret->() unless $params{nonfatal};
1649 elsif (defined $ret) {
1650 error($ret) unless $params{nonfatal};
1656 return defined $ok ? $ok : 1;
1659 sub check_canchange (@) {
1661 my $cgi = $params{cgi};
1662 my $session = $params{session};
1663 my @changes = @{$params{changes}};
1666 foreach my $change (@changes) {
1667 # This untaint is safe because we check file_pruned and
1669 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1670 $file=possibly_foolish_untaint($file);
1671 if (! defined $file || ! length $file ||
1672 file_pruned($file)) {
1673 error(gettext("bad file name %s"), $file);
1676 my $type=pagetype($file);
1677 my $page=pagename($file) if defined $type;
1679 if ($change->{action} eq 'add') {
1683 if ($change->{action} eq 'change' ||
1684 $change->{action} eq 'add') {
1685 if (defined $page) {
1686 check_canedit($page, $cgi, $session);
1690 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1691 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1692 check_canedit($file, $cgi, $session);
1697 elsif ($change->{action} eq 'remove') {
1698 # check_canremove tests to see if the file is present
1699 # on disk. This will fail when a single commit adds a
1700 # file and then removes it again. Avoid the problem
1701 # by not testing the removal in such pairs of changes.
1702 # (The add is still tested, just to make sure that
1703 # no data is added to the repo that a web edit
1705 next if $newfiles{$file};
1707 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1708 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1709 check_canedit(defined $page ? $page : $file, $cgi, $session);
1714 error "unknown action ".$change->{action};
1717 error sprintf(gettext("you are not allowed to change %s"), $file);
1725 # Take an exclusive lock on the wiki to prevent multiple concurrent
1726 # run issues. The lock will be dropped on program exit.
1727 if (! -d $config{wikistatedir}) {
1728 mkdir($config{wikistatedir});
1730 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1731 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1732 if (! flock($wikilock, 2)) { # LOCK_EX
1733 error("failed to get lock");
1739 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1740 return close($wikilock) if $wikilock;
1746 sub commit_hook_enabled () {
1747 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1748 error("cannot write to $config{wikistatedir}/commitlock: $!");
1749 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1750 close($commitlock) || error("failed closing commitlock: $!");
1753 close($commitlock) || error("failed closing commitlock: $!");
1757 sub disable_commit_hook () {
1758 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1759 error("cannot write to $config{wikistatedir}/commitlock: $!");
1760 if (! flock($commitlock, 2)) { # LOCK_EX
1761 error("failed to get commit lock");
1766 sub enable_commit_hook () {
1767 return close($commitlock) if $commitlock;
1772 %oldrenderedfiles=%pagectime=();
1773 if (! $config{rebuild}) {
1774 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1775 %destsources=%renderedfiles=%pagecase=%pagestate=
1776 %depends_simple=%typedlinks=%oldtypedlinks=();
1777 %linkbases=(page=>{},pagespec=>{});
1780 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1781 if (-e "$config{wikistatedir}/index") {
1782 system("ikiwiki-transition", "indexdb", $config{srcdir});
1783 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1786 $config{gettime}=1; # first build
1791 my $index=Storable::fd_retrieve($in);
1792 if (! defined $index) {
1797 if (exists $index->{version} && ! ref $index->{version}) {
1798 $pages=$index->{page};
1799 %wikistate=%{$index->{state}};
1800 # Handle plugins that got disabled by loading a new setup.
1801 if (exists $config{setupfile}) {
1802 require IkiWiki::Setup;
1803 IkiWiki::Setup::disabled_plugins(
1804 grep { ! $loaded_plugins{$_} } keys %wikistate);
1812 foreach my $src (keys %$pages) {
1813 my $d=$pages->{$src};
1814 my $page=pagename($src);
1815 $pagectime{$page}=$d->{ctime};
1816 $pagesources{$page}=$src;
1817 if (! $config{rebuild}) {
1818 $pagemtime{$page}=$d->{mtime};
1819 $renderedfiles{$page}=$d->{dest};
1820 if (exists $d->{links} && ref $d->{links}) {
1821 $links{$page}=$d->{links};
1822 $oldlinks{$page}=[@{$d->{links}}];
1824 if (ref $d->{depends_simple} eq 'ARRAY') {
1826 $depends_simple{$page}={
1827 map { $_ => 1 } @{$d->{depends_simple}}
1830 elsif (exists $d->{depends_simple}) {
1831 $depends_simple{$page}=$d->{depends_simple};
1833 if (exists $d->{dependslist}) {
1836 map { $_ => $DEPEND_CONTENT }
1837 @{$d->{dependslist}}
1840 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1842 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1844 elsif (exists $d->{depends}) {
1845 $depends{$page}=$d->{depends};
1847 if (exists $d->{state}) {
1848 $pagestate{$page}=$d->{state};
1850 if (exists $d->{typedlinks}) {
1851 $typedlinks{$page}=$d->{typedlinks};
1853 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1854 next unless %$links;
1855 $oldtypedlinks{$page}{$type} = {%$links};
1859 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1861 foreach my $page (keys %pagesources) {
1862 $pagecase{lc $page}=$page;
1864 foreach my $page (keys %renderedfiles) {
1865 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1871 run_hooks(savestate => sub { shift->() });
1873 my @plugins=keys %loaded_plugins;
1875 if (! -d $config{wikistatedir}) {
1876 mkdir($config{wikistatedir});
1878 my $newfile="$config{wikistatedir}/indexdb.new";
1879 my $cleanup = sub { unlink($newfile) };
1880 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1883 foreach my $page (keys %pagemtime) {
1884 next unless $pagemtime{$page};
1885 my $src=$pagesources{$page};
1887 $index{page}{$src}={
1888 ctime => $pagectime{$page},
1889 mtime => $pagemtime{$page},
1890 dest => $renderedfiles{$page},
1891 links => $links{$page},
1894 if (exists $depends{$page}) {
1895 $index{page}{$src}{depends} = $depends{$page};
1898 if (exists $depends_simple{$page}) {
1899 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1902 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1903 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1906 if (exists $pagestate{$page}) {
1907 foreach my $id (@plugins) {
1908 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1909 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1916 foreach my $id (@plugins) {
1917 $index{state}{$id}={}; # used to detect disabled plugins
1918 foreach my $key (keys %{$wikistate{$id}}) {
1919 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1923 $index{version}="3";
1924 my $ret=Storable::nstore_fd(\%index, $out);
1925 return if ! defined $ret || ! $ret;
1926 close $out || error("failed saving to $newfile: $!", $cleanup);
1927 rename($newfile, "$config{wikistatedir}/indexdb") ||
1928 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1933 sub template_file ($) {
1936 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1938 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1939 $template=srcfile($pagesources{$tpage}, 1);
1943 $template=srcfile($tpage, 1);
1946 if (defined $template) {
1947 return $template, $tpage, 1 if wantarray;
1951 $name=~s:/::; # avoid path traversal
1952 foreach my $dir ($config{templatedir},
1953 "$installdir/share/ikiwiki/templates") {
1954 if (-e "$dir/$name") {
1955 $template="$dir/$name";
1959 if (defined $template) {
1960 return $template, $tpage if wantarray;
1968 sub template_depends ($$;@) {
1972 my ($filename, $tpage, $untrusted)=template_file($name);
1973 if (! defined $filename) {
1974 error(sprintf(gettext("template %s not found"), $name))
1977 if (defined $page && defined $tpage) {
1978 add_depends($page, $tpage);
1983 my $text_ref = shift;
1984 ${$text_ref} = decode_utf8(${$text_ref});
1986 loop_context_vars => 1,
1987 die_on_bad_params => 0,
1988 parent_global_vars => 1,
1989 filename => $filename,
1991 ($untrusted ? (no_includes => 1) : ()),
1993 return @opts if wantarray;
1995 require HTML::Template;
1996 return HTML::Template->new(@opts);
1999 sub template ($;@) {
2000 template_depends(shift, undef, @_);
2003 sub templateactions ($$) {
2009 run_hooks(pageactions => sub {
2010 push @actions, map { { action => $_ } }
2011 grep { defined } shift->(page => $page);
2013 $template->param(actions => \@actions);
2015 if ($config{cgiurl} && exists $hooks{auth}) {
2016 $template->param(prefsurl => cgiurl(do => "prefs"));
2020 if ($have_actions || @actions) {
2021 $template->param(have_actions => 1);
2028 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2029 error 'hook requires type, call, and id parameters';
2032 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2034 $hooks{$param{type}}{$param{id}}=\%param;
2038 sub run_hooks ($$) {
2039 # Calls the given sub for each hook of the given type,
2040 # passing it the hook function to call.
2044 if (exists $hooks{$type}) {
2045 my (@first, @middle, @last);
2046 foreach my $id (keys %{$hooks{$type}}) {
2047 if ($hooks{$type}{$id}{first}) {
2050 elsif ($hooks{$type}{$id}{last}) {
2057 foreach my $id (@first, @middle, @last) {
2058 $sub->($hooks{$type}{$id}{call});
2066 $hooks{rcs}{rcs_update}{call}->(@_);
2069 sub rcs_prepedit ($) {
2070 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2073 sub rcs_commit (@) {
2074 $hooks{rcs}{rcs_commit}{call}->(@_);
2077 sub rcs_commit_staged (@) {
2078 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2082 $hooks{rcs}{rcs_add}{call}->(@_);
2085 sub rcs_remove ($) {
2086 $hooks{rcs}{rcs_remove}{call}->(@_);
2089 sub rcs_rename ($$) {
2090 $hooks{rcs}{rcs_rename}{call}->(@_);
2093 sub rcs_recentchanges ($) {
2094 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2097 sub rcs_diff ($;$) {
2098 $hooks{rcs}{rcs_diff}{call}->(@_);
2101 sub rcs_getctime ($) {
2102 $hooks{rcs}{rcs_getctime}{call}->(@_);
2105 sub rcs_getmtime ($) {
2106 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2109 sub rcs_receive () {
2110 $hooks{rcs}{rcs_receive}{call}->();
2113 sub add_depends ($$;$) {
2116 my $deptype=shift || $DEPEND_CONTENT;
2118 # Is the pagespec a simple page name?
2119 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2120 $pagespec !~ /[\s*?()!]/) {
2121 $depends_simple{$page}{lc $pagespec} |= $deptype;
2125 # Add explicit dependencies for influences.
2126 my $sub=pagespec_translate($pagespec);
2127 return unless defined $sub;
2128 foreach my $p (keys %pagesources) {
2129 my $r=$sub->($p, location => $page);
2130 my $i=$r->influences;
2131 my $static=$r->influences_static;
2132 foreach my $k (keys %$i) {
2133 next unless $r || $static || $k eq $page;
2134 $depends_simple{$page}{lc $k} |= $i->{$k};
2139 $depends{$page}{$pagespec} |= $deptype;
2145 foreach my $type (@_) {
2146 if ($type eq 'presence') {
2147 $deptype |= $DEPEND_PRESENCE;
2149 elsif ($type eq 'links') {
2150 $deptype |= $DEPEND_LINKS;
2152 elsif ($type eq 'content') {
2153 $deptype |= $DEPEND_CONTENT;
2159 my $file_prune_regexp;
2160 sub file_pruned ($) {
2163 if (defined $config{include} && length $config{include}) {
2164 return 0 if $file =~ m/$config{include}/;
2167 if (! defined $file_prune_regexp) {
2168 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2169 $file_prune_regexp=qr/$file_prune_regexp/;
2171 return $file =~ m/$file_prune_regexp/;
2174 sub define_gettext () {
2175 # If translation is needed, redefine the gettext function to do it.
2176 # Otherwise, it becomes a quick no-op.
2179 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2180 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2181 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2183 $gettext_obj=eval q{
2184 use Locale::gettext q{textdomain};
2185 Locale::gettext->domain('ikiwiki')
2190 no warnings 'redefine';
2192 $getobj->() if $getobj;
2194 $gettext_obj->get(shift);
2201 $getobj->() if $getobj;
2203 $gettext_obj->nget(@_);
2206 return ($_[2] == 1 ? $_[0] : $_[1])
2224 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2228 # Injects a new function into the symbol table to replace an
2229 # exported function.
2232 # This is deep ugly perl foo, beware.
2235 if (! defined $params{parent}) {
2236 $params{parent}='::';
2237 $params{old}=\&{$params{name}};
2238 $params{name}=~s/.*:://;
2240 my $parent=$params{parent};
2241 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2242 $ns = $params{parent} . $ns;
2243 inject(%params, parent => $ns) unless $ns eq '::main::';
2244 *{$ns . $params{name}} = $params{call}
2245 if exists ${$ns}{$params{name}} &&
2246 \&{${$ns}{$params{name}}} == $params{old};
2252 sub add_link ($$;$) {
2257 push @{$links{$page}}, $link
2258 unless grep { $_ eq $link } @{$links{$page}};
2260 if (defined $type) {
2261 $typedlinks{$page}{$type}{$link} = 1;
2265 sub add_autofile ($$$) {
2268 my $generator=shift;
2270 $autofiles{$file}{plugin}=$plugin;
2271 $autofiles{$file}{generator}=$generator;
2274 sub sortspec_translate ($$) {
2276 my $reverse = shift;
2282 (-?) # group 1: perhaps negated
2285 \w+\([^\)]*\) # command(params)
2287 [^\s]+ # or anything else
2295 if ($word =~ m/^(\w+)\((.*)\)$/) {
2296 # command with parameters
2300 elsif ($word !~ m/^\w+$/) {
2301 error(sprintf(gettext("invalid sort type %s"), $word));
2312 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2313 if (defined $params) {
2314 push @data, $params;
2315 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2318 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2322 error(sprintf(gettext("unknown sort type %s"), $word));
2326 if (! length $code) {
2327 # undefined sorting method... sort arbitrarily
2336 return eval 'sub { '.$code.' }';
2339 sub pagespec_translate ($) {
2342 # Convert spec to perl code.
2346 \s* # ignore whitespace
2347 ( # 1: match a single word
2354 \w+\([^\)]*\) # command(params)
2356 [^\s()]+ # any other text
2358 \s* # ignore whitespace
2361 if (lc $word eq 'and') {
2364 elsif (lc $word eq 'or') {
2367 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2370 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2371 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2373 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2376 push @data, qq{unknown function in pagespec "$word"};
2377 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2382 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2386 if (! length $code) {
2387 $code="IkiWiki::FailReason->new('empty pagespec')";
2391 return eval 'sub { my $page=shift; '.$code.' }';
2394 sub pagespec_match ($$;@) {
2399 # Backwards compatability with old calling convention.
2401 unshift @params, 'location';
2404 my $sub=pagespec_translate($spec);
2405 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2407 return $sub->($page, @params);
2410 sub pagespec_match_list ($$;@) {
2415 # Backwards compatability with old calling convention.
2417 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2418 $params{list}=$page;
2419 $page=$params{location}; # ugh!
2422 my $sub=pagespec_translate($pagespec);
2423 error "syntax error in pagespec \"$pagespec\""
2425 my $sort=sortspec_translate($params{sort}, $params{reverse})
2426 if defined $params{sort};
2429 if (exists $params{list}) {
2430 @candidates=exists $params{filter}
2431 ? grep { ! $params{filter}->($_) } @{$params{list}}
2435 @candidates=exists $params{filter}
2436 ? grep { ! $params{filter}->($_) } keys %pagesources
2437 : keys %pagesources;
2440 # clear params, remainder is passed to pagespec
2441 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2442 my $num=$params{num};
2443 delete @params{qw{num deptype reverse sort filter list}};
2445 # when only the top matches will be returned, it's efficient to
2446 # sort before matching to pagespec,
2447 if (defined $num && defined $sort) {
2448 @candidates=IkiWiki::SortSpec::sort_pages(
2449 $sort, @candidates);
2455 my $accum=IkiWiki::SuccessReason->new();
2456 foreach my $p (@candidates) {
2457 my $r=$sub->($p, %params, location => $page);
2458 error(sprintf(gettext("cannot match pages: %s"), $r))
2459 if $r->isa("IkiWiki::ErrorReason");
2460 unless ($r || $r->influences_static) {
2461 $r->remove_influence($p);
2466 last if defined $num && ++$count == $num;
2470 # Add simple dependencies for accumulated influences.
2471 my $i=$accum->influences;
2472 foreach my $k (keys %$i) {
2473 $depends_simple{$page}{lc $k} |= $i->{$k};
2476 # when all matches will be returned, it's efficient to
2477 # sort after matching
2478 if (! defined $num && defined $sort) {
2479 return IkiWiki::SortSpec::sort_pages(
2487 sub pagespec_valid ($) {
2490 return defined pagespec_translate($spec);
2494 my $re=quotemeta(shift);
2500 package IkiWiki::FailReason;
2503 '""' => sub { $_[0][0] },
2505 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2506 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2507 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2511 our @ISA = 'IkiWiki::SuccessReason';
2513 package IkiWiki::SuccessReason;
2516 '""' => sub { $_[0][0] },
2518 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2519 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2520 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2527 return bless [$value, {@_}], $class;
2532 $this->[1]={@_} if @_;
2533 my %i=%{$this->[1]};
2538 sub influences_static {
2539 return ! $_[0][1]->{""};
2542 sub merge_influences {
2547 if (! $anded || (($this || %{$this->[1]}) &&
2548 ($other || %{$other->[1]}))) {
2549 foreach my $influence (keys %{$other->[1]}) {
2550 $this->[1]{$influence} |= $other->[1]{$influence};
2559 sub remove_influence {
2563 delete $this->[1]{$torm};
2566 package IkiWiki::ErrorReason;
2568 our @ISA = 'IkiWiki::FailReason';
2570 package IkiWiki::PageSpec;
2576 if ($path =~ m!^\.(/|$)!) {
2578 $from=~s#/?[^/]+$## if defined $from;
2580 $path="$from/$path" if defined $from && length $from;
2584 $path = "" unless defined $path;
2593 sub match_glob ($$;@) {
2598 $glob=derel($glob, $params{location});
2600 # Instead of converting the glob to a regex every time,
2601 # cache the compiled regex to save time.
2602 my $re=$glob_cache{$glob};
2603 unless (defined $re) {
2604 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2607 if (! IkiWiki::isinternal($page) || $params{internal}) {
2608 return IkiWiki::SuccessReason->new("$glob matches $page");
2611 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2615 return IkiWiki::FailReason->new("$glob does not match $page");
2619 sub match_internal ($$;@) {
2620 return match_glob(shift, shift, @_, internal => 1)
2623 sub match_page ($$;@) {
2625 my $match=match_glob($page, shift, @_);
2627 my $source=exists $IkiWiki::pagesources{$page} ?
2628 $IkiWiki::pagesources{$page} :
2629 $IkiWiki::delpagesources{$page};
2630 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2631 if (! defined $type) {
2632 return IkiWiki::FailReason->new("$page is not a page");
2638 sub match_link ($$;@) {
2643 $link=derel($link, $params{location});
2644 my $from=exists $params{location} ? $params{location} : '';
2645 my $linktype=$params{linktype};
2647 if (defined $linktype) {
2648 $qualifier=" with type $linktype";
2651 my $links = $IkiWiki::links{$page};
2652 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2653 unless $links && @{$links};
2654 my $bestlink = IkiWiki::bestlink($from, $link);
2655 foreach my $p (@{$links}) {
2656 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2658 if (length $bestlink) {
2659 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2660 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2664 if (match_glob($p, $link, %params)) {
2665 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2667 my ($p_rel)=$p=~/^\/?(.*)/;
2669 if (match_glob($p_rel, $link, %params)) {
2670 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2674 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2677 sub match_backlink ($$;@) {
2681 if ($testpage eq '.') {
2682 $testpage = $params{'location'}
2684 my $ret=match_link($testpage, $page, @_);
2685 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2689 sub match_created_before ($$;@) {
2694 $testpage=derel($testpage, $params{location});
2696 if (exists $IkiWiki::pagectime{$testpage}) {
2697 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2698 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2701 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2705 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2709 sub match_created_after ($$;@) {
2714 $testpage=derel($testpage, $params{location});
2716 if (exists $IkiWiki::pagectime{$testpage}) {
2717 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2718 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2721 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2725 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2729 sub match_creation_day ($$;@) {
2732 if ($d !~ /^\d+$/) {
2733 return IkiWiki::ErrorReason->new("invalid day $d");
2735 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2736 return IkiWiki::SuccessReason->new('creation_day matched');
2739 return IkiWiki::FailReason->new('creation_day did not match');
2743 sub match_creation_month ($$;@) {
2746 if ($m !~ /^\d+$/) {
2747 return IkiWiki::ErrorReason->new("invalid month $m");
2749 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2750 return IkiWiki::SuccessReason->new('creation_month matched');
2753 return IkiWiki::FailReason->new('creation_month did not match');
2757 sub match_creation_year ($$;@) {
2760 if ($y !~ /^\d+$/) {
2761 return IkiWiki::ErrorReason->new("invalid year $y");
2763 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2764 return IkiWiki::SuccessReason->new('creation_year matched');
2767 return IkiWiki::FailReason->new('creation_year did not match');
2771 sub match_user ($$;@) {
2776 my $regexp=IkiWiki::glob2re($user);
2778 if (! exists $params{user}) {
2779 return IkiWiki::ErrorReason->new("no user specified");
2782 if (defined $params{user} && $params{user}=~$regexp) {
2783 return IkiWiki::SuccessReason->new("user is $user");
2785 elsif (! defined $params{user}) {
2786 return IkiWiki::FailReason->new("not logged in");
2789 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2793 sub match_admin ($$;@) {
2798 if (! exists $params{user}) {
2799 return IkiWiki::ErrorReason->new("no user specified");
2802 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2803 return IkiWiki::SuccessReason->new("user is an admin");
2805 elsif (! defined $params{user}) {
2806 return IkiWiki::FailReason->new("not logged in");
2809 return IkiWiki::FailReason->new("user is not an admin");
2813 sub match_ip ($$;@) {
2818 if (! exists $params{ip}) {
2819 return IkiWiki::ErrorReason->new("no IP specified");
2822 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2823 return IkiWiki::SuccessReason->new("IP is $ip");
2826 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2830 package IkiWiki::SortSpec;
2832 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2833 # are easily available in this namespace, for cmp functions to use them.
2840 IkiWiki::pagetitle(IkiWiki::basename($a))
2842 IkiWiki::pagetitle(IkiWiki::basename($b))
2845 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2846 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2847 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }