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 useragent
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
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 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
519 description => "cookie control",
520 safe => 0, # hooks into perl module internals
525 sub defaultconfig () {
528 foreach my $key (keys %s) {
529 push @ret, $key, $s{$key}->{default};
534 # URL to top of wiki as a path starting with /, valid from any wiki page or
535 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
537 # URL to CGI script, similar to $local_url
541 # locale stuff; avoid LC_ALL since it overrides everything
542 if (defined $ENV{LC_ALL}) {
543 $ENV{LANG} = $ENV{LC_ALL};
546 if (defined $config{locale}) {
547 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
548 $ENV{LANG}=$config{locale};
553 if (! defined $config{wiki_file_regexp}) {
554 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
557 if (ref $config{ENV} eq 'HASH') {
558 foreach my $val (keys %{$config{ENV}}) {
559 $ENV{$val}=$config{ENV}{$val};
562 if (defined $config{timezone} && length $config{timezone}) {
563 $ENV{TZ}=$config{timezone};
566 $config{timezone}=$ENV{TZ};
569 if ($config{w3mmode}) {
570 eval q{use Cwd q{abs_path}};
572 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
573 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
574 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
575 unless $config{cgiurl} =~ m!file:///!;
576 $config{url}="file://".$config{destdir};
579 if ($config{cgi} && ! length $config{url}) {
580 error(gettext("Must specify url to wiki with --url when using --cgi"));
583 if (defined $config{url} && length $config{url}) {
585 my $baseurl = URI->new($config{url});
587 $local_url = $baseurl->path . "/";
588 $local_cgiurl = undef;
590 if (length $config{cgiurl}) {
591 my $cgiurl = URI->new($config{cgiurl});
593 $local_cgiurl = $cgiurl->path;
595 if ($cgiurl->scheme ne $baseurl->scheme or
596 $cgiurl->authority ne $baseurl->authority) {
597 # too far apart, fall back to absolute URLs
598 $local_url = "$config{url}/";
599 $local_cgiurl = $config{cgiurl};
603 $local_url =~ s{//$}{/};
606 $local_cgiurl = $config{cgiurl};
609 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
610 unless exists $config{wikistatedir} && defined $config{wikistatedir};
612 if (defined $config{umask}) {
613 my $u = possibly_foolish_untaint($config{umask});
615 if ($u =~ m/^\d+$/) {
618 elsif ($u eq 'private') {
621 elsif ($u eq 'group') {
624 elsif ($u eq 'public') {
628 error(sprintf(gettext("unsupported umask setting %s"), $u));
632 run_hooks(checkconfig => sub { shift->() });
640 foreach my $dir (@INC, $config{libdir}) {
641 next unless defined $dir && length $dir;
642 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
643 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
647 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
648 next unless defined $dir && length $dir;
649 foreach my $file (glob("$dir/plugins/*")) {
650 $ret{basename($file)}=1 if -x $file;
658 if (defined $config{libdir} && length $config{libdir}) {
659 unshift @INC, possibly_foolish_untaint($config{libdir});
662 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
667 if (exists $hooks{rcs}) {
668 error(gettext("cannot use multiple rcs plugins"));
670 loadplugin($config{rcs});
672 if (! exists $hooks{rcs}) {
676 run_hooks(getopt => sub { shift->() });
677 if (grep /^-/, @ARGV) {
678 print STDERR "Unknown option (or missing parameter): $_\n"
679 foreach grep /^-/, @ARGV;
686 sub loadplugin ($;$) {
690 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
692 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
693 "$installdir/lib/ikiwiki") {
694 if (defined $dir && -x "$dir/plugins/$plugin") {
695 eval { require IkiWiki::Plugin::external };
698 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
700 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
701 $loaded_plugins{$plugin}=1;
706 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
709 error("Failed to load plugin $mod: $@");
711 $loaded_plugins{$plugin}=1;
718 log_message('err' => $message) if $config{syslog};
719 if (defined $cleaner) {
726 return unless $config{verbose};
727 return log_message(debug => @_);
732 sub log_message ($$) {
735 if ($config{syslog}) {
738 Sys::Syslog::setlogsock('unix');
739 Sys::Syslog::openlog('ikiwiki', '', 'user');
743 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
746 print STDERR "failed to syslog: $@" unless $log_failed;
752 elsif (! $config{cgi}) {
756 return print STDERR "@_\n";
760 sub possibly_foolish_untaint ($) {
762 my ($untainted)=$tainted=~/(.*)/s;
782 return exists $pagesources{$page} &&
783 $pagesources{$page} =~ /\._([^.]+)$/;
789 if ($file =~ /\.([^.]+)$/) {
790 return $1 if exists $hooks{htmlize}{$1};
792 my $base=basename($file);
793 if (exists $hooks{htmlize}{$base} &&
794 $hooks{htmlize}{$base}{noextension}) {
805 if (exists $pagename_cache{$file}) {
806 return $pagename_cache{$file};
809 my $type=pagetype($file);
811 $page=~s/\Q.$type\E*$//
812 if defined $type && !$hooks{htmlize}{$type}{keepextension}
813 && !$hooks{htmlize}{$type}{noextension};
814 if ($config{indexpages} && $page=~/(.*)\/index$/) {
818 $pagename_cache{$file} = $page;
822 sub newpagefile ($$) {
826 if (! $config{indexpages} || $page eq 'index') {
827 return $page.".".$type;
830 return $page."/index.".$type;
834 sub targetpage ($$;$) {
839 if (defined $filename) {
840 return $page."/".$filename.".".$ext;
842 elsif (! $config{usedirs} || $page eq 'index') {
843 return $page.".".$ext;
846 return $page."/index.".$ext;
853 return targetpage($page, $config{htmlext});
860 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
861 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
862 return "$dir/$file", stat(_) if -e "$dir/$file";
864 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
869 return (srcfile_stat(@_))[0];
872 sub add_literal_underlay ($) {
875 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
876 unshift @{$config{underlaydirs}}, $dir;
880 sub add_underlay ($) {
884 $dir="$config{underlaydirbase}/$dir";
887 add_literal_underlay($dir);
888 # why does it return 1? we just don't know
892 sub readfile ($;$$) {
898 error("cannot read a symlink ($file)");
902 open (my $in, "<", $file) || error("failed to read $file: $!");
903 binmode($in) if ($binary);
904 return \*$in if $wantfd;
906 # check for invalid utf-8, and toss it back to avoid crashes
907 if (! utf8::valid($ret)) {
908 $ret=encode_utf8($ret);
910 close $in || error("failed to read $file: $!");
914 sub prep_writefile ($$) {
919 while (length $test) {
920 if (-l "$destdir/$test") {
921 error("cannot write to a symlink ($test)");
923 if (-f _ && $test ne $file) {
924 # Remove conflicting file.
925 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
926 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
928 unlink("$destdir/$test");
934 $test=dirname($test);
937 my $dir=dirname("$destdir/$file");
940 foreach my $s (split(m!/+!, $dir)) {
943 mkdir($d) || error("failed to create directory $d: $!");
951 sub writefile ($$$;$$) {
952 my $file=shift; # can include subdirs
953 my $destdir=shift; # directory to put file in
958 prep_writefile($file, $destdir);
960 my $newfile="$destdir/$file.ikiwiki-new";
962 error("cannot write to a symlink ($newfile)");
965 my $cleanup = sub { unlink($newfile) };
966 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
967 binmode($out) if ($binary);
969 $writer->(\*$out, $cleanup);
972 print $out $content or error("failed writing to $newfile: $!", $cleanup);
974 close $out || error("failed saving $newfile: $!", $cleanup);
975 rename($newfile, "$destdir/$file") ||
976 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
982 sub will_render ($$;$) {
987 # Important security check for independently created files.
988 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
989 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
990 my $from_other_page=0;
991 # Expensive, but rarely runs.
992 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
996 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1002 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1003 unless $from_other_page;
1006 # If $dest exists as a directory, remove conflicting files in it
1007 # rendered from other pages.
1009 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1010 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1011 if (dirname($f) eq $dest) {
1012 unlink("$config{destdir}/$f");
1013 rmdir(dirname("$config{destdir}/$f"));
1019 if (! $clear || $cleared{$page}) {
1020 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1023 foreach my $old (@{$renderedfiles{$page}}) {
1024 delete $destsources{$old};
1026 $renderedfiles{$page}=[$dest];
1029 $destsources{$dest}=$page;
1039 if ($link=~s/^\/+//) {
1047 $l.="/" if length $l;
1050 if (exists $pagesources{$l}) {
1053 elsif (exists $pagecase{lc $l}) {
1054 return $pagecase{lc $l};
1056 } while $cwd=~s{/?[^/]+$}{};
1058 if (length $config{userdir}) {
1059 my $l = "$config{userdir}/".lc($link);
1060 if (exists $pagesources{$l}) {
1063 elsif (exists $pagecase{lc $l}) {
1064 return $pagecase{lc $l};
1068 #print STDERR "warning: page $page, broken link: $link\n";
1072 sub isinlinableimage ($) {
1075 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1078 sub pagetitle ($;$) {
1080 my $unescaped=shift;
1083 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1086 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1094 # support use w/o %config set
1095 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1096 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1102 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1103 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1110 my $cgiurl=$local_cgiurl;
1112 if (exists $params{cgiurl}) {
1113 $cgiurl=$params{cgiurl};
1114 delete $params{cgiurl};
1122 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1125 sub cgiurl_abs (@) {
1127 URI->new_abs(cgiurl(@_), $config{cgiurl});
1133 return $local_url if ! defined $page;
1135 $page=htmlpage($page);
1137 $page=~s/[^\/]+\//..\//g;
1145 return $url unless defined $urlbase && length $urlbase;
1148 URI->new_abs($url, $urlbase)->as_string;
1152 # Work around very innefficient behavior in File::Spec if abs2rel
1153 # is passed two relative paths. It's much faster if paths are
1154 # absolute! (Debian bug #376658; fixed in debian unstable now)
1159 my $ret=File::Spec->abs2rel($path, $base);
1160 $ret=~s/^// if defined $ret;
1164 sub displaytime ($;$$) {
1165 # Plugins can override this function to mark up the time to
1167 my $time=formattime($_[0], $_[1]);
1168 if ($config{html5}) {
1169 return '<time datetime="'.date_3339($_[0]).'"'.
1170 ($_[2] ? ' pubdate="pubdate"' : '').
1171 '>'.$time.'</time>';
1174 return '<span class="date">'.$time.'</span>';
1178 sub formattime ($;$) {
1179 # Plugins can override this function to format the time.
1182 if (! defined $format) {
1183 $format=$config{timeformat};
1186 return strftime_utf8($format, localtime($time));
1189 my $strftime_encoding;
1191 # strftime doesn't know about encodings, so make sure
1192 # its output is properly treated as utf8.
1193 # Note that this does not handle utf-8 in the format string.
1194 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1195 unless defined $strftime_encoding;
1197 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1198 : POSIX::strftime(@_);
1204 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1205 POSIX::setlocale(&POSIX::LC_TIME, "C");
1206 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1207 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1211 sub beautify_urlpath ($) {
1214 # Ensure url is not an empty link, and if necessary,
1215 # add ./ to avoid colon confusion.
1216 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1220 if ($config{usedirs}) {
1221 $url =~ s!/index.$config{htmlext}$!/!;
1236 if (! $destsources{$to}) {
1241 return $config{url}.beautify_urlpath("/".$to);
1244 if (! defined $from) {
1245 my $u = $local_url || '';
1247 return $u.beautify_urlpath("/".$to);
1250 my $link = abs2rel($to, dirname(htmlpage($from)));
1252 return beautify_urlpath($link);
1255 sub isselflink ($$) {
1256 # Plugins can override this function to support special types
1261 return $page eq $link;
1264 sub htmllink ($$$;@) {
1265 my $lpage=shift; # the page doing the linking
1266 my $page=shift; # the page that will contain the link (different for inline)
1273 if (! $opts{forcesubpage}) {
1274 $bestlink=bestlink($lpage, $link);
1277 $bestlink="$lpage/".lc($link);
1281 if (defined $opts{linktext}) {
1282 $linktext=$opts{linktext};
1285 $linktext=pagetitle(basename($link));
1288 return "<span class=\"selflink\">$linktext</span>"
1289 if length $bestlink && isselflink($page, $bestlink) &&
1290 ! defined $opts{anchor};
1292 if (! $destsources{$bestlink}) {
1293 $bestlink=htmlpage($bestlink);
1295 if (! $destsources{$bestlink}) {
1297 if (length $config{cgiurl}) {
1298 $cgilink = "<a href=\"".
1303 )."\" rel=\"nofollow\">?</a>";
1305 return "<span class=\"createlink\">$cgilink$linktext</span>"
1309 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1310 $bestlink=beautify_urlpath($bestlink);
1312 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1313 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1316 if (defined $opts{anchor}) {
1317 $bestlink.="#".$opts{anchor};
1321 foreach my $attr (qw{rel class title}) {
1322 if (defined $opts{$attr}) {
1323 push @attrs, " $attr=\"$opts{$attr}\"";
1327 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1332 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1335 sub openiduser ($) {
1338 if (defined $user && $user =~ m!^https?://! &&
1339 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1342 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1343 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1346 # backcompat with old version
1347 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1348 $display=$oid->display;
1351 # Convert "user.somehost.com" to "user [somehost.com]"
1352 # (also "user.somehost.co.uk")
1353 if ($display !~ /\[/) {
1354 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1356 # Convert "http://somehost.com/user" to "user [somehost.com]".
1357 # (also "https://somehost.com/user/")
1358 if ($display !~ /\[/) {
1359 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1361 $display=~s!^https?://!!; # make sure this is removed
1362 eval q{use CGI 'escapeHTML'};
1364 return escapeHTML($display);
1369 sub htmlize ($$$$) {
1375 my $oneline = $content !~ /\n/;
1377 if (exists $hooks{htmlize}{$type}) {
1378 $content=$hooks{htmlize}{$type}{call}->(
1380 content => $content,
1384 error("htmlization of $type not supported");
1387 run_hooks(sanitize => sub {
1390 destpage => $destpage,
1391 content => $content,
1396 # hack to get rid of enclosing junk added by markdown
1397 # and other htmlizers/sanitizers
1398 $content=~s/^<p>//i;
1399 $content=~s/<\/p>\n*$//i;
1410 run_hooks(linkify => sub {
1413 destpage => $destpage,
1414 content => $content,
1422 our $preprocess_preview=0;
1423 sub preprocess ($$$;$$) {
1424 my $page=shift; # the page the data comes from
1425 my $destpage=shift; # the page the data will appear in (different for inline)
1430 # Using local because it needs to be set within any nested calls
1432 local $preprocess_preview=$preview if defined $preview;
1439 $params="" if ! defined $params;
1441 if (length $escape) {
1442 return "[[$prefix$command $params]]";
1444 elsif (exists $hooks{preprocess}{$command}) {
1445 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1446 # Note: preserve order of params, some plugins may
1447 # consider it significant.
1449 while ($params =~ m{
1450 (?:([-.\w]+)=)? # 1: named parameter key?
1452 """(.*?)""" # 2: triple-quoted value
1454 "([^"]*?)" # 3: single-quoted value
1456 '''(.*?)''' # 4: triple-single-quote
1458 <<([a-zA-Z]+)\n # 5: heredoc start
1459 (.*?)\n\5 # 6: heredoc value
1461 (\S+) # 7: unquoted value
1463 (?:\s+|$) # delimiter to next param
1473 elsif (defined $3) {
1476 elsif (defined $4) {
1479 elsif (defined $7) {
1482 elsif (defined $6) {
1487 push @params, $key, $val;
1490 push @params, $val, '';
1493 if ($preprocessing{$page}++ > 3) {
1494 # Avoid loops of preprocessed pages preprocessing
1495 # other pages that preprocess them, etc.
1496 return "[[!$command <span class=\"error\">".
1497 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1498 $page, $preprocessing{$page}).
1504 $hooks{preprocess}{$command}{call}->(
1507 destpage => $destpage,
1508 preview => $preprocess_preview,
1514 $ret="[[!$command <span class=\"error\">".
1515 gettext("Error").": $error"."</span>]]";
1519 # use void context during scan pass
1521 $hooks{preprocess}{$command}{call}->(
1524 destpage => $destpage,
1525 preview => $preprocess_preview,
1530 $preprocessing{$page}--;
1534 return "[[$prefix$command $params]]";
1539 if ($config{prefix_directives}) {
1542 \[\[(!) # directive open; 2: prefix
1543 ([-\w]+) # 3: command
1544 ( # 4: the parameters..
1545 \s+ # Must have space if parameters present
1547 (?:[-.\w]+=)? # named parameter key?
1549 """.*?""" # triple-quoted value
1551 "[^"]*?" # single-quoted value
1553 '''.*?''' # triple-single-quote
1555 <<([a-zA-Z]+)\n # 5: heredoc start
1556 (?:.*?)\n\5 # heredoc value
1558 [^"\s\]]+ # unquoted value
1560 \s* # whitespace or end
1563 *)? # 0 or more parameters
1564 \]\] # directive closed
1570 \[\[(!?) # directive open; 2: optional prefix
1571 ([-\w]+) # 3: command
1573 ( # 4: the parameters..
1575 (?:[-.\w]+=)? # named parameter key?
1577 """.*?""" # triple-quoted value
1579 "[^"]*?" # single-quoted value
1581 '''.*?''' # triple-single-quote
1583 <<([a-zA-Z]+)\n # 5: heredoc start
1584 (?:.*?)\n\5 # heredoc value
1586 [^"\s\]]+ # unquoted value
1588 \s* # whitespace or end
1591 *) # 0 or more parameters
1592 \]\] # directive closed
1596 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1605 run_hooks(filter => sub {
1606 $content=shift->(page => $page, destpage => $destpage,
1607 content => $content);
1613 sub check_canedit ($$$;$) {
1620 run_hooks(canedit => sub {
1621 return if defined $canedit;
1622 my $ret=shift->($page, $q, $session);
1627 elsif (ref $ret eq 'CODE') {
1628 $ret->() unless $nonfatal;
1631 elsif (defined $ret) {
1632 error($ret) unless $nonfatal;
1637 return defined $canedit ? $canedit : 1;
1640 sub check_content (@) {
1643 return 1 if ! exists $hooks{checkcontent}; # optimisation
1645 if (exists $pagesources{$params{page}}) {
1647 my %old=map { $_ => 1 }
1648 split("\n", readfile(srcfile($pagesources{$params{page}})));
1649 foreach my $line (split("\n", $params{content})) {
1650 push @diff, $line if ! exists $old{$line};
1652 $params{diff}=join("\n", @diff);
1656 run_hooks(checkcontent => sub {
1657 return if defined $ok;
1658 my $ret=shift->(%params);
1663 elsif (ref $ret eq 'CODE') {
1664 $ret->() unless $params{nonfatal};
1667 elsif (defined $ret) {
1668 error($ret) unless $params{nonfatal};
1674 return defined $ok ? $ok : 1;
1677 sub check_canchange (@) {
1679 my $cgi = $params{cgi};
1680 my $session = $params{session};
1681 my @changes = @{$params{changes}};
1684 foreach my $change (@changes) {
1685 # This untaint is safe because we check file_pruned and
1687 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1688 $file=possibly_foolish_untaint($file);
1689 if (! defined $file || ! length $file ||
1690 file_pruned($file)) {
1691 error(gettext("bad file name %s"), $file);
1694 my $type=pagetype($file);
1695 my $page=pagename($file) if defined $type;
1697 if ($change->{action} eq 'add') {
1701 if ($change->{action} eq 'change' ||
1702 $change->{action} eq 'add') {
1703 if (defined $page) {
1704 check_canedit($page, $cgi, $session);
1708 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1709 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1710 check_canedit($file, $cgi, $session);
1715 elsif ($change->{action} eq 'remove') {
1716 # check_canremove tests to see if the file is present
1717 # on disk. This will fail when a single commit adds a
1718 # file and then removes it again. Avoid the problem
1719 # by not testing the removal in such pairs of changes.
1720 # (The add is still tested, just to make sure that
1721 # no data is added to the repo that a web edit
1723 next if $newfiles{$file};
1725 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1726 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1727 check_canedit(defined $page ? $page : $file, $cgi, $session);
1732 error "unknown action ".$change->{action};
1735 error sprintf(gettext("you are not allowed to change %s"), $file);
1743 # Take an exclusive lock on the wiki to prevent multiple concurrent
1744 # run issues. The lock will be dropped on program exit.
1745 if (! -d $config{wikistatedir}) {
1746 mkdir($config{wikistatedir});
1748 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1749 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1750 if (! flock($wikilock, 2)) { # LOCK_EX
1751 error("failed to get lock");
1757 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1758 return close($wikilock) if $wikilock;
1764 sub commit_hook_enabled () {
1765 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1766 error("cannot write to $config{wikistatedir}/commitlock: $!");
1767 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1768 close($commitlock) || error("failed closing commitlock: $!");
1771 close($commitlock) || error("failed closing commitlock: $!");
1775 sub disable_commit_hook () {
1776 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1777 error("cannot write to $config{wikistatedir}/commitlock: $!");
1778 if (! flock($commitlock, 2)) { # LOCK_EX
1779 error("failed to get commit lock");
1784 sub enable_commit_hook () {
1785 return close($commitlock) if $commitlock;
1790 %oldrenderedfiles=%pagectime=();
1791 if (! $config{rebuild}) {
1792 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1793 %destsources=%renderedfiles=%pagecase=%pagestate=
1794 %depends_simple=%typedlinks=%oldtypedlinks=();
1797 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1798 if (-e "$config{wikistatedir}/index") {
1799 system("ikiwiki-transition", "indexdb", $config{srcdir});
1800 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1803 $config{gettime}=1; # first build
1808 my $index=Storable::fd_retrieve($in);
1809 if (! defined $index) {
1814 if (exists $index->{version} && ! ref $index->{version}) {
1815 $pages=$index->{page};
1816 %wikistate=%{$index->{state}};
1817 # Handle plugins that got disabled by loading a new setup.
1818 if (exists $config{setupfile}) {
1819 require IkiWiki::Setup;
1820 IkiWiki::Setup::disabled_plugins(
1821 grep { ! $loaded_plugins{$_} } keys %wikistate);
1829 foreach my $src (keys %$pages) {
1830 my $d=$pages->{$src};
1831 my $page=pagename($src);
1832 $pagectime{$page}=$d->{ctime};
1833 $pagesources{$page}=$src;
1834 if (! $config{rebuild}) {
1835 $pagemtime{$page}=$d->{mtime};
1836 $renderedfiles{$page}=$d->{dest};
1837 if (exists $d->{links} && ref $d->{links}) {
1838 $links{$page}=$d->{links};
1839 $oldlinks{$page}=[@{$d->{links}}];
1841 if (ref $d->{depends_simple} eq 'ARRAY') {
1843 $depends_simple{$page}={
1844 map { $_ => 1 } @{$d->{depends_simple}}
1847 elsif (exists $d->{depends_simple}) {
1848 $depends_simple{$page}=$d->{depends_simple};
1850 if (exists $d->{dependslist}) {
1853 map { $_ => $DEPEND_CONTENT }
1854 @{$d->{dependslist}}
1857 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1859 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1861 elsif (exists $d->{depends}) {
1862 $depends{$page}=$d->{depends};
1864 if (exists $d->{state}) {
1865 $pagestate{$page}=$d->{state};
1867 if (exists $d->{typedlinks}) {
1868 $typedlinks{$page}=$d->{typedlinks};
1870 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1871 next unless %$links;
1872 $oldtypedlinks{$page}{$type} = {%$links};
1876 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1878 foreach my $page (keys %pagesources) {
1879 $pagecase{lc $page}=$page;
1881 foreach my $page (keys %renderedfiles) {
1882 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1888 run_hooks(savestate => sub { shift->() });
1890 my @plugins=keys %loaded_plugins;
1892 if (! -d $config{wikistatedir}) {
1893 mkdir($config{wikistatedir});
1895 my $newfile="$config{wikistatedir}/indexdb.new";
1896 my $cleanup = sub { unlink($newfile) };
1897 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1900 foreach my $page (keys %pagemtime) {
1901 next unless $pagemtime{$page};
1902 my $src=$pagesources{$page};
1904 $index{page}{$src}={
1905 ctime => $pagectime{$page},
1906 mtime => $pagemtime{$page},
1907 dest => $renderedfiles{$page},
1908 links => $links{$page},
1911 if (exists $depends{$page}) {
1912 $index{page}{$src}{depends} = $depends{$page};
1915 if (exists $depends_simple{$page}) {
1916 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1919 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1920 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1923 if (exists $pagestate{$page}) {
1924 foreach my $id (@plugins) {
1925 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1926 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1933 foreach my $id (@plugins) {
1934 $index{state}{$id}={}; # used to detect disabled plugins
1935 foreach my $key (keys %{$wikistate{$id}}) {
1936 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1940 $index{version}="3";
1941 my $ret=Storable::nstore_fd(\%index, $out);
1942 return if ! defined $ret || ! $ret;
1943 close $out || error("failed saving to $newfile: $!", $cleanup);
1944 rename($newfile, "$config{wikistatedir}/indexdb") ||
1945 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1950 sub template_file ($) {
1953 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1955 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1956 $template=srcfile($pagesources{$tpage}, 1);
1960 $template=srcfile($tpage, 1);
1963 if (defined $template) {
1964 return $template, $tpage, 1 if wantarray;
1968 $name=~s:/::; # avoid path traversal
1969 foreach my $dir ($config{templatedir},
1970 "$installdir/share/ikiwiki/templates") {
1971 if (-e "$dir/$name") {
1972 $template="$dir/$name";
1976 if (defined $template) {
1977 return $template, $tpage if wantarray;
1985 sub template_depends ($$;@) {
1989 my ($filename, $tpage, $untrusted)=template_file($name);
1990 if (! defined $filename) {
1991 error(sprintf(gettext("template %s not found"), $name))
1994 if (defined $page && defined $tpage) {
1995 add_depends($page, $tpage);
2000 my $text_ref = shift;
2001 ${$text_ref} = decode_utf8(${$text_ref});
2003 loop_context_vars => 1,
2004 die_on_bad_params => 0,
2005 parent_global_vars => 1,
2006 filename => $filename,
2008 ($untrusted ? (no_includes => 1) : ()),
2010 return @opts if wantarray;
2012 require HTML::Template;
2013 return HTML::Template->new(@opts);
2016 sub template ($;@) {
2017 template_depends(shift, undef, @_);
2020 sub templateactions ($$) {
2026 run_hooks(pageactions => sub {
2027 push @actions, map { { action => $_ } }
2028 grep { defined } shift->(page => $page);
2030 $template->param(actions => \@actions);
2032 if ($config{cgiurl} && exists $hooks{auth}) {
2033 $template->param(prefsurl => cgiurl(do => "prefs"));
2037 if ($have_actions || @actions) {
2038 $template->param(have_actions => 1);
2045 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2046 error 'hook requires type, call, and id parameters';
2049 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2051 $hooks{$param{type}}{$param{id}}=\%param;
2055 sub run_hooks ($$) {
2056 # Calls the given sub for each hook of the given type,
2057 # passing it the hook function to call.
2061 if (exists $hooks{$type}) {
2062 my (@first, @middle, @last);
2063 foreach my $id (keys %{$hooks{$type}}) {
2064 if ($hooks{$type}{$id}{first}) {
2067 elsif ($hooks{$type}{$id}{last}) {
2074 foreach my $id (@first, @middle, @last) {
2075 $sub->($hooks{$type}{$id}{call});
2083 $hooks{rcs}{rcs_update}{call}->(@_);
2086 sub rcs_prepedit ($) {
2087 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2090 sub rcs_commit (@) {
2091 $hooks{rcs}{rcs_commit}{call}->(@_);
2094 sub rcs_commit_staged (@) {
2095 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2099 $hooks{rcs}{rcs_add}{call}->(@_);
2102 sub rcs_remove ($) {
2103 $hooks{rcs}{rcs_remove}{call}->(@_);
2106 sub rcs_rename ($$) {
2107 $hooks{rcs}{rcs_rename}{call}->(@_);
2110 sub rcs_recentchanges ($) {
2111 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2114 sub rcs_diff ($;$) {
2115 $hooks{rcs}{rcs_diff}{call}->(@_);
2118 sub rcs_getctime ($) {
2119 $hooks{rcs}{rcs_getctime}{call}->(@_);
2122 sub rcs_getmtime ($) {
2123 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2126 sub rcs_receive () {
2127 $hooks{rcs}{rcs_receive}{call}->();
2130 sub add_depends ($$;$) {
2133 my $deptype=shift || $DEPEND_CONTENT;
2135 # Is the pagespec a simple page name?
2136 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2137 $pagespec !~ /[\s*?()!]/) {
2138 $depends_simple{$page}{lc $pagespec} |= $deptype;
2142 # Add explicit dependencies for influences.
2143 my $sub=pagespec_translate($pagespec);
2144 return unless defined $sub;
2145 foreach my $p (keys %pagesources) {
2146 my $r=$sub->($p, location => $page);
2147 my $i=$r->influences;
2148 my $static=$r->influences_static;
2149 foreach my $k (keys %$i) {
2150 next unless $r || $static || $k eq $page;
2151 $depends_simple{$page}{lc $k} |= $i->{$k};
2156 $depends{$page}{$pagespec} |= $deptype;
2162 foreach my $type (@_) {
2163 if ($type eq 'presence') {
2164 $deptype |= $DEPEND_PRESENCE;
2166 elsif ($type eq 'links') {
2167 $deptype |= $DEPEND_LINKS;
2169 elsif ($type eq 'content') {
2170 $deptype |= $DEPEND_CONTENT;
2176 my $file_prune_regexp;
2177 sub file_pruned ($) {
2180 if (defined $config{include} && length $config{include}) {
2181 return 0 if $file =~ m/$config{include}/;
2184 if (! defined $file_prune_regexp) {
2185 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2186 $file_prune_regexp=qr/$file_prune_regexp/;
2188 return $file =~ m/$file_prune_regexp/;
2191 sub define_gettext () {
2192 # If translation is needed, redefine the gettext function to do it.
2193 # Otherwise, it becomes a quick no-op.
2196 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2197 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2198 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2200 $gettext_obj=eval q{
2201 use Locale::gettext q{textdomain};
2202 Locale::gettext->domain('ikiwiki')
2207 no warnings 'redefine';
2209 $getobj->() if $getobj;
2211 $gettext_obj->get(shift);
2218 $getobj->() if $getobj;
2220 $gettext_obj->nget(@_);
2223 return ($_[2] == 1 ? $_[0] : $_[1])
2241 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2245 # Injects a new function into the symbol table to replace an
2246 # exported function.
2249 # This is deep ugly perl foo, beware.
2252 if (! defined $params{parent}) {
2253 $params{parent}='::';
2254 $params{old}=\&{$params{name}};
2255 $params{name}=~s/.*:://;
2257 my $parent=$params{parent};
2258 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2259 $ns = $params{parent} . $ns;
2260 inject(%params, parent => $ns) unless $ns eq '::main::';
2261 *{$ns . $params{name}} = $params{call}
2262 if exists ${$ns}{$params{name}} &&
2263 \&{${$ns}{$params{name}}} == $params{old};
2269 sub add_link ($$;$) {
2274 push @{$links{$page}}, $link
2275 unless grep { $_ eq $link } @{$links{$page}};
2277 if (defined $type) {
2278 $typedlinks{$page}{$type}{$link} = 1;
2282 sub add_autofile ($$$) {
2285 my $generator=shift;
2287 $autofiles{$file}{plugin}=$plugin;
2288 $autofiles{$file}{generator}=$generator;
2292 return LWP::UserAgent->new(
2293 cookie_jar => $config{cookiejar},
2294 env_proxy => 1, # respect proxy env vars
2298 sub sortspec_translate ($$) {
2300 my $reverse = shift;
2306 (-?) # group 1: perhaps negated
2309 \w+\([^\)]*\) # command(params)
2311 [^\s]+ # or anything else
2319 if ($word =~ m/^(\w+)\((.*)\)$/) {
2320 # command with parameters
2324 elsif ($word !~ m/^\w+$/) {
2325 error(sprintf(gettext("invalid sort type %s"), $word));
2336 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2337 if (defined $params) {
2338 push @data, $params;
2339 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2342 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2346 error(sprintf(gettext("unknown sort type %s"), $word));
2350 if (! length $code) {
2351 # undefined sorting method... sort arbitrarily
2360 return eval 'sub { '.$code.' }';
2363 sub pagespec_translate ($) {
2366 # Convert spec to perl code.
2370 \s* # ignore whitespace
2371 ( # 1: match a single word
2378 \w+\([^\)]*\) # command(params)
2380 [^\s()]+ # any other text
2382 \s* # ignore whitespace
2385 if (lc $word eq 'and') {
2388 elsif (lc $word eq 'or') {
2391 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2394 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2395 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2397 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2400 push @data, qq{unknown function in pagespec "$word"};
2401 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2406 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2410 if (! length $code) {
2411 $code="IkiWiki::FailReason->new('empty pagespec')";
2415 return eval 'sub { my $page=shift; '.$code.' }';
2418 sub pagespec_match ($$;@) {
2423 # Backwards compatability with old calling convention.
2425 unshift @params, 'location';
2428 my $sub=pagespec_translate($spec);
2429 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2431 return $sub->($page, @params);
2434 sub pagespec_match_list ($$;@) {
2439 # Backwards compatability with old calling convention.
2441 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2442 $params{list}=$page;
2443 $page=$params{location}; # ugh!
2446 my $sub=pagespec_translate($pagespec);
2447 error "syntax error in pagespec \"$pagespec\""
2449 my $sort=sortspec_translate($params{sort}, $params{reverse})
2450 if defined $params{sort};
2453 if (exists $params{list}) {
2454 @candidates=exists $params{filter}
2455 ? grep { ! $params{filter}->($_) } @{$params{list}}
2459 @candidates=exists $params{filter}
2460 ? grep { ! $params{filter}->($_) } keys %pagesources
2461 : keys %pagesources;
2464 # clear params, remainder is passed to pagespec
2465 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2466 my $num=$params{num};
2467 delete @params{qw{num deptype reverse sort filter list}};
2469 # when only the top matches will be returned, it's efficient to
2470 # sort before matching to pagespec,
2471 if (defined $num && defined $sort) {
2472 @candidates=IkiWiki::SortSpec::sort_pages(
2473 $sort, @candidates);
2479 my $accum=IkiWiki::SuccessReason->new();
2480 foreach my $p (@candidates) {
2481 my $r=$sub->($p, %params, location => $page);
2482 error(sprintf(gettext("cannot match pages: %s"), $r))
2483 if $r->isa("IkiWiki::ErrorReason");
2484 unless ($r || $r->influences_static) {
2485 $r->remove_influence($p);
2490 last if defined $num && ++$count == $num;
2494 # Add simple dependencies for accumulated influences.
2495 my $i=$accum->influences;
2496 foreach my $k (keys %$i) {
2497 $depends_simple{$page}{lc $k} |= $i->{$k};
2500 # when all matches will be returned, it's efficient to
2501 # sort after matching
2502 if (! defined $num && defined $sort) {
2503 return IkiWiki::SortSpec::sort_pages(
2511 sub pagespec_valid ($) {
2514 return defined pagespec_translate($spec);
2518 my $re=quotemeta(shift);
2524 package IkiWiki::FailReason;
2527 '""' => sub { $_[0][0] },
2529 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2530 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2531 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2535 our @ISA = 'IkiWiki::SuccessReason';
2537 package IkiWiki::SuccessReason;
2540 '""' => sub { $_[0][0] },
2542 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2543 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2544 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2551 return bless [$value, {@_}], $class;
2556 $this->[1]={@_} if @_;
2557 my %i=%{$this->[1]};
2562 sub influences_static {
2563 return ! $_[0][1]->{""};
2566 sub merge_influences {
2571 if (! $anded || (($this || %{$this->[1]}) &&
2572 ($other || %{$other->[1]}))) {
2573 foreach my $influence (keys %{$other->[1]}) {
2574 $this->[1]{$influence} |= $other->[1]{$influence};
2583 sub remove_influence {
2587 delete $this->[1]{$torm};
2590 package IkiWiki::ErrorReason;
2592 our @ISA = 'IkiWiki::FailReason';
2594 package IkiWiki::PageSpec;
2600 if ($path =~ m!^\.(/|$)!) {
2602 $from=~s#/?[^/]+$## if defined $from;
2604 $path="$from/$path" if defined $from && length $from;
2608 $path = "" unless defined $path;
2617 sub match_glob ($$;@) {
2622 $glob=derel($glob, $params{location});
2624 # Instead of converting the glob to a regex every time,
2625 # cache the compiled regex to save time.
2626 my $re=$glob_cache{$glob};
2627 unless (defined $re) {
2628 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2631 if (! IkiWiki::isinternal($page) || $params{internal}) {
2632 return IkiWiki::SuccessReason->new("$glob matches $page");
2635 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2639 return IkiWiki::FailReason->new("$glob does not match $page");
2643 sub match_internal ($$;@) {
2644 return match_glob(shift, shift, @_, internal => 1)
2647 sub match_page ($$;@) {
2649 my $match=match_glob($page, shift, @_);
2651 my $source=exists $IkiWiki::pagesources{$page} ?
2652 $IkiWiki::pagesources{$page} :
2653 $IkiWiki::delpagesources{$page};
2654 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2655 if (! defined $type) {
2656 return IkiWiki::FailReason->new("$page is not a page");
2662 sub match_link ($$;@) {
2667 $link=derel($link, $params{location});
2668 my $from=exists $params{location} ? $params{location} : '';
2669 my $linktype=$params{linktype};
2671 if (defined $linktype) {
2672 $qualifier=" with type $linktype";
2675 my $links = $IkiWiki::links{$page};
2676 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2677 unless $links && @{$links};
2678 my $bestlink = IkiWiki::bestlink($from, $link);
2679 foreach my $p (@{$links}) {
2680 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2682 if (length $bestlink) {
2683 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2684 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2688 if (match_glob($p, $link, %params)) {
2689 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2691 my ($p_rel)=$p=~/^\/?(.*)/;
2693 if (match_glob($p_rel, $link, %params)) {
2694 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2698 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2701 sub match_backlink ($$;@) {
2705 if ($testpage eq '.') {
2706 $testpage = $params{'location'}
2708 my $ret=match_link($testpage, $page, @_);
2709 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2713 sub match_created_before ($$;@) {
2718 $testpage=derel($testpage, $params{location});
2720 if (exists $IkiWiki::pagectime{$testpage}) {
2721 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2722 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2725 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2729 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2733 sub match_created_after ($$;@) {
2738 $testpage=derel($testpage, $params{location});
2740 if (exists $IkiWiki::pagectime{$testpage}) {
2741 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2742 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2745 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2749 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2753 sub match_creation_day ($$;@) {
2756 if ($d !~ /^\d+$/) {
2757 return IkiWiki::ErrorReason->new("invalid day $d");
2759 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2760 return IkiWiki::SuccessReason->new('creation_day matched');
2763 return IkiWiki::FailReason->new('creation_day did not match');
2767 sub match_creation_month ($$;@) {
2770 if ($m !~ /^\d+$/) {
2771 return IkiWiki::ErrorReason->new("invalid month $m");
2773 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2774 return IkiWiki::SuccessReason->new('creation_month matched');
2777 return IkiWiki::FailReason->new('creation_month did not match');
2781 sub match_creation_year ($$;@) {
2784 if ($y !~ /^\d+$/) {
2785 return IkiWiki::ErrorReason->new("invalid year $y");
2787 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2788 return IkiWiki::SuccessReason->new('creation_year matched');
2791 return IkiWiki::FailReason->new('creation_year did not match');
2795 sub match_user ($$;@) {
2800 if (! exists $params{user}) {
2801 return IkiWiki::ErrorReason->new("no user specified");
2804 my $regexp=IkiWiki::glob2re($user);
2806 if (defined $params{user} && $params{user}=~$regexp) {
2807 return IkiWiki::SuccessReason->new("user is $user");
2809 elsif (! defined $params{user}) {
2810 return IkiWiki::FailReason->new("not logged in");
2813 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2817 sub match_admin ($$;@) {
2822 if (! exists $params{user}) {
2823 return IkiWiki::ErrorReason->new("no user specified");
2826 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2827 return IkiWiki::SuccessReason->new("user is an admin");
2829 elsif (! defined $params{user}) {
2830 return IkiWiki::FailReason->new("not logged in");
2833 return IkiWiki::FailReason->new("user is not an admin");
2837 sub match_ip ($$;@) {
2842 if (! exists $params{ip}) {
2843 return IkiWiki::ErrorReason->new("no IP specified");
2846 my $regexp=IkiWiki::glob2re(lc $ip);
2848 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2849 return IkiWiki::SuccessReason->new("IP is $ip");
2852 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2856 package IkiWiki::SortSpec;
2858 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2859 # are easily available in this namespace, for cmp functions to use them.
2866 IkiWiki::pagetitle(IkiWiki::basename($a))
2868 IkiWiki::pagetitle(IkiWiki::basename($b))
2871 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2872 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2873 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }