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 will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link add_autofile
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
40 memoize("sortspec_translate");
41 memoize("pagespec_translate");
42 memoize("template_file");
48 description => "name of the wiki",
55 example => 'me@example.com',
56 description => "contact email for wiki",
63 description => "users who are wiki admins",
70 description => "users who are banned from the wiki",
77 example => "$ENV{HOME}/wiki",
78 description => "where the source of the wiki is located",
85 example => "/var/www/wiki",
86 description => "where to build the wiki",
93 example => "http://example.com/wiki",
94 description => "base url to the wiki",
101 example => "http://example.com/wiki/ikiwiki.cgi",
102 description => "url to the ikiwiki.cgi",
109 example => "/var/www/wiki/ikiwiki.cgi",
110 description => "filename of cgi wrapper to generate",
117 description => "mode for cgi_wrapper (can safely be made suid)",
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? (experimental)",
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",
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 => '^\.htaccess$',
343 description => "regexp of normally excluded files to include",
351 example => '^(*\.private|Makefile)$',
352 description => "regexp of files that should be skipped",
357 wiki_file_prune_regexps => {
359 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
360 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
361 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
362 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
363 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
364 description => "regexps of source files to ignore",
370 description => "specifies the characters that are allowed in source filenames",
371 default => "-[:alnum:]+/.:_",
375 wiki_file_regexp => {
377 description => "regexp of legal source files",
381 web_commit_regexp => {
383 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
384 description => "regexp to parse web commits from logs",
391 description => "run as a cgi",
395 cgi_disable_uploads => {
398 description => "whether CGI should accept file uploads",
405 description => "run as a post-commit hook",
412 description => "running in rebuild mode",
419 description => "running in setup mode",
426 description => "running in clean mode",
433 description => "running in refresh mode",
440 description => "running in receive test mode",
444 wrapper_background_command => {
447 description => "background shell command to run",
453 description => "running in gettime mode",
460 description => "running in w3mmode",
467 description => "path to the .ikiwiki directory holding ikiwiki state",
474 description => "path to setup file",
480 default => "Standard",
481 description => "perl class to use to dump setup file",
485 allow_symlinks_before_srcdir => {
488 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
494 sub defaultconfig () {
497 foreach my $key (keys %s) {
498 push @ret, $key, $s{$key}->{default};
504 # URL to top of wiki as a path starting with /, valid from any wiki page or
505 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
507 # URL to CGI script, similar to $local_url
511 # locale stuff; avoid LC_ALL since it overrides everything
512 if (defined $ENV{LC_ALL}) {
513 $ENV{LANG} = $ENV{LC_ALL};
516 if (defined $config{locale}) {
517 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
518 $ENV{LANG}=$config{locale};
523 if (! defined $config{wiki_file_regexp}) {
524 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
527 if (ref $config{ENV} eq 'HASH') {
528 foreach my $val (keys %{$config{ENV}}) {
529 $ENV{$val}=$config{ENV}{$val};
533 if ($config{w3mmode}) {
534 eval q{use Cwd q{abs_path}};
536 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
537 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
538 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
539 unless $config{cgiurl} =~ m!file:///!;
540 $config{url}="file://".$config{destdir};
543 if ($config{cgi} && ! length $config{url}) {
544 error(gettext("Must specify url to wiki with --url when using --cgi"));
547 if (length $config{url}) {
549 my $baseurl = URI->new($config{url});
551 $local_url = $baseurl->path . "/";
552 $local_cgiurl = undef;
554 if (length $config{cgiurl}) {
555 my $cgiurl = URI->new($config{cgiurl});
557 $local_cgiurl = $cgiurl->path;
559 if ($cgiurl->scheme ne $baseurl->scheme or
560 $cgiurl->authority ne $baseurl->authority) {
561 # too far apart, fall back to absolute URLs
562 $local_url = "$config{url}/";
563 $local_cgiurl = $config{cgiurl};
567 $local_url =~ s{//$}{/};
570 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
571 unless exists $config{wikistatedir} && defined $config{wikistatedir};
573 if (defined $config{umask}) {
574 umask(possibly_foolish_untaint($config{umask}));
577 run_hooks(checkconfig => sub { shift->() });
585 foreach my $dir (@INC, $config{libdir}) {
586 next unless defined $dir && length $dir;
587 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
588 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
592 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
593 next unless defined $dir && length $dir;
594 foreach my $file (glob("$dir/plugins/*")) {
595 $ret{basename($file)}=1 if -x $file;
603 if (defined $config{libdir} && length $config{libdir}) {
604 unshift @INC, possibly_foolish_untaint($config{libdir});
607 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
612 if (exists $hooks{rcs}) {
613 error(gettext("cannot use multiple rcs plugins"));
615 loadplugin($config{rcs});
617 if (! exists $hooks{rcs}) {
621 run_hooks(getopt => sub { shift->() });
622 if (grep /^-/, @ARGV) {
623 print STDERR "Unknown option (or missing parameter): $_\n"
624 foreach grep /^-/, @ARGV;
631 sub loadplugin ($;$) {
635 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
637 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
638 "$installdir/lib/ikiwiki") {
639 if (defined $dir && -x "$dir/plugins/$plugin") {
640 eval { require IkiWiki::Plugin::external };
643 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
645 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
646 $loaded_plugins{$plugin}=1;
651 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
654 error("Failed to load plugin $mod: $@");
656 $loaded_plugins{$plugin}=1;
663 log_message('err' => $message) if $config{syslog};
664 if (defined $cleaner) {
671 return unless $config{verbose};
672 return log_message(debug => @_);
676 sub log_message ($$) {
679 if ($config{syslog}) {
682 Sys::Syslog::setlogsock('unix');
683 Sys::Syslog::openlog('ikiwiki', '', 'user');
687 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
690 elsif (! $config{cgi}) {
694 return print STDERR "@_\n";
698 sub possibly_foolish_untaint ($) {
700 my ($untainted)=$tainted=~/(.*)/s;
720 return exists $pagesources{$page} &&
721 $pagesources{$page} =~ /\._([^.]+)$/;
727 if ($file =~ /\.([^.]+)$/) {
728 return $1 if exists $hooks{htmlize}{$1};
730 my $base=basename($file);
731 if (exists $hooks{htmlize}{$base} &&
732 $hooks{htmlize}{$base}{noextension}) {
743 if (exists $pagename_cache{$file}) {
744 return $pagename_cache{$file};
747 my $type=pagetype($file);
749 $page=~s/\Q.$type\E*$//
750 if defined $type && !$hooks{htmlize}{$type}{keepextension}
751 && !$hooks{htmlize}{$type}{noextension};
752 if ($config{indexpages} && $page=~/(.*)\/index$/) {
756 $pagename_cache{$file} = $page;
760 sub newpagefile ($$) {
764 if (! $config{indexpages} || $page eq 'index') {
765 return $page.".".$type;
768 return $page."/index.".$type;
772 sub targetpage ($$;$) {
777 if (defined $filename) {
778 return $page."/".$filename.".".$ext;
780 elsif (! $config{usedirs} || $page eq 'index') {
781 return $page.".".$ext;
784 return $page."/index.".$ext;
791 return targetpage($page, $config{htmlext});
798 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
799 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
800 return "$dir/$file", stat(_) if -e "$dir/$file";
802 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
807 return (srcfile_stat(@_))[0];
810 sub add_underlay ($) {
814 $dir="$config{underlaydirbase}/$dir";
817 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
818 unshift @{$config{underlaydirs}}, $dir;
824 sub readfile ($;$$) {
830 error("cannot read a symlink ($file)");
834 open (my $in, "<", $file) || error("failed to read $file: $!");
835 binmode($in) if ($binary);
836 return \*$in if $wantfd;
838 # check for invalid utf-8, and toss it back to avoid crashes
839 if (! utf8::valid($ret)) {
840 $ret=encode_utf8($ret);
842 close $in || error("failed to read $file: $!");
846 sub prep_writefile ($$) {
851 while (length $test) {
852 if (-l "$destdir/$test") {
853 error("cannot write to a symlink ($test)");
855 if (-f _ && $test ne $file) {
856 # Remove conflicting file.
857 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
858 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
860 unlink("$destdir/$test");
866 $test=dirname($test);
869 my $dir=dirname("$destdir/$file");
872 foreach my $s (split(m!/+!, $dir)) {
875 mkdir($d) || error("failed to create directory $d: $!");
883 sub writefile ($$$;$$) {
884 my $file=shift; # can include subdirs
885 my $destdir=shift; # directory to put file in
890 prep_writefile($file, $destdir);
892 my $newfile="$destdir/$file.ikiwiki-new";
894 error("cannot write to a symlink ($newfile)");
897 my $cleanup = sub { unlink($newfile) };
898 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
899 binmode($out) if ($binary);
901 $writer->(\*$out, $cleanup);
904 print $out $content or error("failed writing to $newfile: $!", $cleanup);
906 close $out || error("failed saving $newfile: $!", $cleanup);
907 rename($newfile, "$destdir/$file") ||
908 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
914 sub will_render ($$;$) {
919 # Important security check for independently created files.
920 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
921 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
922 my $from_other_page=0;
923 # Expensive, but rarely runs.
924 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
928 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
934 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
935 unless $from_other_page;
938 # If $dest exists as a directory, remove conflicting files in it
939 # rendered from other pages.
941 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
942 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
943 if (dirname($f) eq $dest) {
944 unlink("$config{destdir}/$f");
945 rmdir(dirname("$config{destdir}/$f"));
951 if (! $clear || $cleared{$page}) {
952 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
955 foreach my $old (@{$renderedfiles{$page}}) {
956 delete $destsources{$old};
958 $renderedfiles{$page}=[$dest];
961 $destsources{$dest}=$page;
971 if ($link=~s/^\/+//) {
979 $l.="/" if length $l;
982 if (exists $pagesources{$l}) {
985 elsif (exists $pagecase{lc $l}) {
986 return $pagecase{lc $l};
988 } while $cwd=~s{/?[^/]+$}{};
990 if (length $config{userdir}) {
991 my $l = "$config{userdir}/".lc($link);
992 if (exists $pagesources{$l}) {
995 elsif (exists $pagecase{lc $l}) {
996 return $pagecase{lc $l};
1000 #print STDERR "warning: page $page, broken link: $link\n";
1004 sub isinlinableimage ($) {
1007 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
1010 sub pagetitle ($;$) {
1012 my $unescaped=shift;
1015 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1018 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1026 # support use w/o %config set
1027 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1028 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1034 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1035 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1042 my $cgiurl=$config{cgiurl};
1043 if (exists $params{cgiurl}) {
1044 $cgiurl=$params{cgiurl};
1045 delete $params{cgiurl};
1053 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1059 return "$config{url}/" if ! defined $page;
1061 $page=htmlpage($page);
1063 $page=~s/[^\/]+\//..\//g;
1068 # Work around very innefficient behavior in File::Spec if abs2rel
1069 # is passed two relative paths. It's much faster if paths are
1070 # absolute! (Debian bug #376658; fixed in debian unstable now)
1075 my $ret=File::Spec->abs2rel($path, $base);
1076 $ret=~s/^// if defined $ret;
1080 sub displaytime ($;$$) {
1081 # Plugins can override this function to mark up the time to
1083 my $time=formattime($_[0], $_[1]);
1084 if ($config{html5}) {
1085 return '<time datetime="'.date_3339($_[0]).'"'.
1086 ($_[2] ? ' pubdate="pubdate"' : '').
1087 '>'.$time.'</time>';
1090 return '<span class="date">'.$time.'</span>';
1094 sub formattime ($;$) {
1095 # Plugins can override this function to format the time.
1098 if (! defined $format) {
1099 $format=$config{timeformat};
1102 # strftime doesn't know about encodings, so make sure
1103 # its output is properly treated as utf8
1104 return decode_utf8(POSIX::strftime($format, localtime($time)));
1110 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1111 POSIX::setlocale(&POSIX::LC_TIME, "C");
1112 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1113 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1117 sub beautify_urlpath ($) {
1120 # Ensure url is not an empty link, and if necessary,
1121 # add ./ to avoid colon confusion.
1122 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1126 if ($config{usedirs}) {
1127 $url =~ s!/index.$config{htmlext}$!/!;
1139 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1142 if (! $destsources{$to}) {
1147 return $config{url}.beautify_urlpath("/".$to);
1150 my $link = abs2rel($to, dirname(htmlpage($from)));
1152 return beautify_urlpath($link);
1155 sub isselflink ($$) {
1156 # Plugins can override this function to support special types
1161 return $page eq $link;
1164 sub htmllink ($$$;@) {
1165 my $lpage=shift; # the page doing the linking
1166 my $page=shift; # the page that will contain the link (different for inline)
1173 if (! $opts{forcesubpage}) {
1174 $bestlink=bestlink($lpage, $link);
1177 $bestlink="$lpage/".lc($link);
1181 if (defined $opts{linktext}) {
1182 $linktext=$opts{linktext};
1185 $linktext=pagetitle(basename($link));
1188 return "<span class=\"selflink\">$linktext</span>"
1189 if length $bestlink && isselflink($page, $bestlink) &&
1190 ! defined $opts{anchor};
1192 if (! $destsources{$bestlink}) {
1193 $bestlink=htmlpage($bestlink);
1195 if (! $destsources{$bestlink}) {
1197 if (length $config{cgiurl}) {
1198 $cgilink = "<a href=\"".
1203 )."\" rel=\"nofollow\">?</a>";
1205 return "<span class=\"createlink\">$cgilink$linktext</span>"
1209 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1210 $bestlink=beautify_urlpath($bestlink);
1212 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1213 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1216 if (defined $opts{anchor}) {
1217 $bestlink.="#".$opts{anchor};
1221 foreach my $attr (qw{rel class title}) {
1222 if (defined $opts{$attr}) {
1223 push @attrs, " $attr=\"$opts{$attr}\"";
1227 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1232 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1235 sub openiduser ($) {
1238 if ($user =~ m!^https?://! &&
1239 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1242 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1243 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1246 # backcompat with old version
1247 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1248 $display=$oid->display;
1251 # Convert "user.somehost.com" to "user [somehost.com]"
1252 # (also "user.somehost.co.uk")
1253 if ($display !~ /\[/) {
1254 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1256 # Convert "http://somehost.com/user" to "user [somehost.com]".
1257 # (also "https://somehost.com/user/")
1258 if ($display !~ /\[/) {
1259 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1261 $display=~s!^https?://!!; # make sure this is removed
1262 eval q{use CGI 'escapeHTML'};
1264 return escapeHTML($display);
1269 sub htmlize ($$$$) {
1275 my $oneline = $content !~ /\n/;
1277 if (exists $hooks{htmlize}{$type}) {
1278 $content=$hooks{htmlize}{$type}{call}->(
1280 content => $content,
1284 error("htmlization of $type not supported");
1287 run_hooks(sanitize => sub {
1290 destpage => $destpage,
1291 content => $content,
1296 # hack to get rid of enclosing junk added by markdown
1297 # and other htmlizers/sanitizers
1298 $content=~s/^<p>//i;
1299 $content=~s/<\/p>\n*$//i;
1310 run_hooks(linkify => sub {
1313 destpage => $destpage,
1314 content => $content,
1322 our $preprocess_preview=0;
1323 sub preprocess ($$$;$$) {
1324 my $page=shift; # the page the data comes from
1325 my $destpage=shift; # the page the data will appear in (different for inline)
1330 # Using local because it needs to be set within any nested calls
1332 local $preprocess_preview=$preview if defined $preview;
1339 $params="" if ! defined $params;
1341 if (length $escape) {
1342 return "[[$prefix$command $params]]";
1344 elsif (exists $hooks{preprocess}{$command}) {
1345 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1346 # Note: preserve order of params, some plugins may
1347 # consider it significant.
1349 while ($params =~ m{
1350 (?:([-\w]+)=)? # 1: named parameter key?
1352 """(.*?)""" # 2: triple-quoted value
1354 "([^"]*?)" # 3: single-quoted value
1356 (\S+) # 4: unquoted value
1358 (?:\s+|$) # delimiter to next param
1368 elsif (defined $3) {
1371 elsif (defined $4) {
1376 push @params, $key, $val;
1379 push @params, $val, '';
1382 if ($preprocessing{$page}++ > 3) {
1383 # Avoid loops of preprocessed pages preprocessing
1384 # other pages that preprocess them, etc.
1385 return "[[!$command <span class=\"error\">".
1386 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1387 $page, $preprocessing{$page}).
1393 $hooks{preprocess}{$command}{call}->(
1396 destpage => $destpage,
1397 preview => $preprocess_preview,
1403 $ret="[[!$command <span class=\"error\">".
1404 gettext("Error").": $error"."</span>]]";
1408 # use void context during scan pass
1410 $hooks{preprocess}{$command}{call}->(
1413 destpage => $destpage,
1414 preview => $preprocess_preview,
1419 $preprocessing{$page}--;
1423 return "[[$prefix$command $params]]";
1428 if ($config{prefix_directives}) {
1431 \[\[(!) # directive open; 2: prefix
1432 ([-\w]+) # 3: command
1433 ( # 4: the parameters..
1434 \s+ # Must have space if parameters present
1436 (?:[-\w]+=)? # named parameter key?
1438 """.*?""" # triple-quoted value
1440 "[^"]*?" # single-quoted value
1442 [^"\s\]]+ # unquoted value
1444 \s* # whitespace or end
1447 *)? # 0 or more parameters
1448 \]\] # directive closed
1454 \[\[(!?) # directive open; 2: optional prefix
1455 ([-\w]+) # 3: command
1457 ( # 4: the parameters..
1459 (?:[-\w]+=)? # named parameter key?
1461 """.*?""" # triple-quoted value
1463 "[^"]*?" # single-quoted value
1465 [^"\s\]]+ # unquoted value
1467 \s* # whitespace or end
1470 *) # 0 or more parameters
1471 \]\] # directive closed
1475 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1484 run_hooks(filter => sub {
1485 $content=shift->(page => $page, destpage => $destpage,
1486 content => $content);
1492 sub check_canedit ($$$;$) {
1499 run_hooks(canedit => sub {
1500 return if defined $canedit;
1501 my $ret=shift->($page, $q, $session);
1506 elsif (ref $ret eq 'CODE') {
1507 $ret->() unless $nonfatal;
1510 elsif (defined $ret) {
1511 error($ret) unless $nonfatal;
1516 return defined $canedit ? $canedit : 1;
1519 sub check_content (@) {
1522 return 1 if ! exists $hooks{checkcontent}; # optimisation
1524 if (exists $pagesources{$params{page}}) {
1526 my %old=map { $_ => 1 }
1527 split("\n", readfile(srcfile($pagesources{$params{page}})));
1528 foreach my $line (split("\n", $params{content})) {
1529 push @diff, $line if ! exists $old{$line};
1531 $params{diff}=join("\n", @diff);
1535 run_hooks(checkcontent => sub {
1536 return if defined $ok;
1537 my $ret=shift->(%params);
1542 elsif (ref $ret eq 'CODE') {
1543 $ret->() unless $params{nonfatal};
1546 elsif (defined $ret) {
1547 error($ret) unless $params{nonfatal};
1553 return defined $ok ? $ok : 1;
1556 sub check_canchange (@) {
1558 my $cgi = $params{cgi};
1559 my $session = $params{session};
1560 my @changes = @{$params{changes}};
1563 foreach my $change (@changes) {
1564 # This untaint is safe because we check file_pruned and
1566 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1567 $file=possibly_foolish_untaint($file);
1568 if (! defined $file || ! length $file ||
1569 file_pruned($file)) {
1570 error(gettext("bad file name %s"), $file);
1573 my $type=pagetype($file);
1574 my $page=pagename($file) if defined $type;
1576 if ($change->{action} eq 'add') {
1580 if ($change->{action} eq 'change' ||
1581 $change->{action} eq 'add') {
1582 if (defined $page) {
1583 check_canedit($page, $cgi, $session);
1587 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1588 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1589 check_canedit($file, $cgi, $session);
1594 elsif ($change->{action} eq 'remove') {
1595 # check_canremove tests to see if the file is present
1596 # on disk. This will fail when a single commit adds a
1597 # file and then removes it again. Avoid the problem
1598 # by not testing the removal in such pairs of changes.
1599 # (The add is still tested, just to make sure that
1600 # no data is added to the repo that a web edit
1602 next if $newfiles{$file};
1604 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1605 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1606 check_canedit(defined $page ? $page : $file, $cgi, $session);
1611 error "unknown action ".$change->{action};
1614 error sprintf(gettext("you are not allowed to change %s"), $file);
1622 # Take an exclusive lock on the wiki to prevent multiple concurrent
1623 # run issues. The lock will be dropped on program exit.
1624 if (! -d $config{wikistatedir}) {
1625 mkdir($config{wikistatedir});
1627 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1628 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1629 if (! flock($wikilock, 2)) { # LOCK_EX
1630 error("failed to get lock");
1636 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1637 return close($wikilock) if $wikilock;
1643 sub commit_hook_enabled () {
1644 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1645 error("cannot write to $config{wikistatedir}/commitlock: $!");
1646 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1647 close($commitlock) || error("failed closing commitlock: $!");
1650 close($commitlock) || error("failed closing commitlock: $!");
1654 sub disable_commit_hook () {
1655 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1656 error("cannot write to $config{wikistatedir}/commitlock: $!");
1657 if (! flock($commitlock, 2)) { # LOCK_EX
1658 error("failed to get commit lock");
1663 sub enable_commit_hook () {
1664 return close($commitlock) if $commitlock;
1669 %oldrenderedfiles=%pagectime=();
1670 if (! $config{rebuild}) {
1671 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1672 %destsources=%renderedfiles=%pagecase=%pagestate=
1673 %depends_simple=%typedlinks=%oldtypedlinks=();
1676 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1677 if (-e "$config{wikistatedir}/index") {
1678 system("ikiwiki-transition", "indexdb", $config{srcdir});
1679 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1682 $config{gettime}=1; # first build
1687 my $index=Storable::fd_retrieve($in);
1688 if (! defined $index) {
1693 if (exists $index->{version} && ! ref $index->{version}) {
1694 $pages=$index->{page};
1695 %wikistate=%{$index->{state}};
1696 # Handle plugins that got disabled by loading a new setup.
1697 if (exists $config{setupfile}) {
1698 require IkiWiki::Setup;
1699 IkiWiki::Setup::disabled_plugins(
1700 grep { ! $loaded_plugins{$_} } keys %wikistate);
1708 foreach my $src (keys %$pages) {
1709 my $d=$pages->{$src};
1710 my $page=pagename($src);
1711 $pagectime{$page}=$d->{ctime};
1712 $pagesources{$page}=$src;
1713 if (! $config{rebuild}) {
1714 $pagemtime{$page}=$d->{mtime};
1715 $renderedfiles{$page}=$d->{dest};
1716 if (exists $d->{links} && ref $d->{links}) {
1717 $links{$page}=$d->{links};
1718 $oldlinks{$page}=[@{$d->{links}}];
1720 if (ref $d->{depends_simple} eq 'ARRAY') {
1722 $depends_simple{$page}={
1723 map { $_ => 1 } @{$d->{depends_simple}}
1726 elsif (exists $d->{depends_simple}) {
1727 $depends_simple{$page}=$d->{depends_simple};
1729 if (exists $d->{dependslist}) {
1732 map { $_ => $DEPEND_CONTENT }
1733 @{$d->{dependslist}}
1736 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1738 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1740 elsif (exists $d->{depends}) {
1741 $depends{$page}=$d->{depends};
1743 if (exists $d->{state}) {
1744 $pagestate{$page}=$d->{state};
1746 if (exists $d->{typedlinks}) {
1747 $typedlinks{$page}=$d->{typedlinks};
1749 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1750 next unless %$links;
1751 $oldtypedlinks{$page}{$type} = {%$links};
1755 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1757 foreach my $page (keys %pagesources) {
1758 $pagecase{lc $page}=$page;
1760 foreach my $page (keys %renderedfiles) {
1761 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1767 run_hooks(savestate => sub { shift->() });
1769 my @plugins=keys %loaded_plugins;
1771 if (! -d $config{wikistatedir}) {
1772 mkdir($config{wikistatedir});
1774 my $newfile="$config{wikistatedir}/indexdb.new";
1775 my $cleanup = sub { unlink($newfile) };
1776 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1779 foreach my $page (keys %pagemtime) {
1780 next unless $pagemtime{$page};
1781 my $src=$pagesources{$page};
1783 $index{page}{$src}={
1784 ctime => $pagectime{$page},
1785 mtime => $pagemtime{$page},
1786 dest => $renderedfiles{$page},
1787 links => $links{$page},
1790 if (exists $depends{$page}) {
1791 $index{page}{$src}{depends} = $depends{$page};
1794 if (exists $depends_simple{$page}) {
1795 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1798 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1799 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1802 if (exists $pagestate{$page}) {
1803 foreach my $id (@plugins) {
1804 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1805 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1812 foreach my $id (@plugins) {
1813 $index{state}{$id}={}; # used to detect disabled plugins
1814 foreach my $key (keys %{$wikistate{$id}}) {
1815 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1819 $index{version}="3";
1820 my $ret=Storable::nstore_fd(\%index, $out);
1821 return if ! defined $ret || ! $ret;
1822 close $out || error("failed saving to $newfile: $!", $cleanup);
1823 rename($newfile, "$config{wikistatedir}/indexdb") ||
1824 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1829 sub template_file ($) {
1832 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1834 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1835 $template=srcfile($pagesources{$tpage}, 1);
1839 $template=srcfile($tpage, 1);
1842 if (defined $template) {
1843 return $template, $tpage, 1 if wantarray;
1847 $name=~s:/::; # avoid path traversal
1848 foreach my $dir ($config{templatedir},
1849 "$installdir/share/ikiwiki/templates") {
1850 if (-e "$dir/$name") {
1851 $template="$dir/$name";
1855 if (defined $template) {
1856 return $template, $tpage if wantarray;
1864 sub template_depends ($$;@) {
1868 my ($filename, $tpage, $untrusted)=template_file($name);
1869 if (! defined $filename) {
1870 error(sprintf(gettext("template %s not found"), $name))
1873 if (defined $page && defined $tpage) {
1874 add_depends($page, $tpage);
1879 my $text_ref = shift;
1880 ${$text_ref} = decode_utf8(${$text_ref});
1882 loop_context_vars => 1,
1883 die_on_bad_params => 0,
1884 filename => $filename,
1886 ($untrusted ? (no_includes => 1) : ()),
1888 return @opts if wantarray;
1890 require HTML::Template;
1891 return HTML::Template->new(@opts);
1894 sub template ($;@) {
1895 template_depends(shift, undef, @_);
1898 sub misctemplate ($$;@) {
1903 my $template=template("page.tmpl");
1906 if (exists $params{page}) {
1907 $page=delete $params{page};
1909 run_hooks(pagetemplate => sub {
1913 template => $template,
1916 templateactions($template, "");
1921 wikiname => $config{wikiname},
1922 content => $content,
1923 baseurl => baseurl(),
1924 html5 => $config{html5},
1928 return $template->output;
1931 sub templateactions ($$) {
1937 run_hooks(pageactions => sub {
1938 push @actions, map { { action => $_ } }
1939 grep { defined } shift->(page => $page);
1941 $template->param(actions => \@actions);
1943 if ($config{cgiurl} && exists $hooks{auth}) {
1944 $template->param(prefsurl => cgiurl(do => "prefs"));
1948 if ($have_actions || @actions) {
1949 $template->param(have_actions => 1);
1956 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1957 error 'hook requires type, call, and id parameters';
1960 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1962 $hooks{$param{type}}{$param{id}}=\%param;
1966 sub run_hooks ($$) {
1967 # Calls the given sub for each hook of the given type,
1968 # passing it the hook function to call.
1972 if (exists $hooks{$type}) {
1973 my (@first, @middle, @last);
1974 foreach my $id (keys %{$hooks{$type}}) {
1975 if ($hooks{$type}{$id}{first}) {
1978 elsif ($hooks{$type}{$id}{last}) {
1985 foreach my $id (@first, @middle, @last) {
1986 $sub->($hooks{$type}{$id}{call});
1994 $hooks{rcs}{rcs_update}{call}->(@_);
1997 sub rcs_prepedit ($) {
1998 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2001 sub rcs_commit (@) {
2002 $hooks{rcs}{rcs_commit}{call}->(@_);
2005 sub rcs_commit_staged (@) {
2006 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2010 $hooks{rcs}{rcs_add}{call}->(@_);
2013 sub rcs_remove ($) {
2014 $hooks{rcs}{rcs_remove}{call}->(@_);
2017 sub rcs_rename ($$) {
2018 $hooks{rcs}{rcs_rename}{call}->(@_);
2021 sub rcs_recentchanges ($) {
2022 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2026 $hooks{rcs}{rcs_diff}{call}->(@_);
2029 sub rcs_getctime ($) {
2030 $hooks{rcs}{rcs_getctime}{call}->(@_);
2033 sub rcs_getmtime ($) {
2034 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2037 sub rcs_receive () {
2038 $hooks{rcs}{rcs_receive}{call}->();
2041 sub add_depends ($$;$) {
2044 my $deptype=shift || $DEPEND_CONTENT;
2046 # Is the pagespec a simple page name?
2047 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2048 $pagespec !~ /[\s*?()!]/) {
2049 $depends_simple{$page}{lc $pagespec} |= $deptype;
2053 # Add explicit dependencies for influences.
2054 my $sub=pagespec_translate($pagespec);
2055 return unless defined $sub;
2056 foreach my $p (keys %pagesources) {
2057 my $r=$sub->($p, location => $page);
2058 my $i=$r->influences;
2059 my $static=$r->influences_static;
2060 foreach my $k (keys %$i) {
2061 next unless $r || $static || $k eq $page;
2062 $depends_simple{$page}{lc $k} |= $i->{$k};
2067 $depends{$page}{$pagespec} |= $deptype;
2073 foreach my $type (@_) {
2074 if ($type eq 'presence') {
2075 $deptype |= $DEPEND_PRESENCE;
2077 elsif ($type eq 'links') {
2078 $deptype |= $DEPEND_LINKS;
2080 elsif ($type eq 'content') {
2081 $deptype |= $DEPEND_CONTENT;
2087 my $file_prune_regexp;
2088 sub file_pruned ($) {
2091 if (defined $config{include} && length $config{include}) {
2092 return 0 if $file =~ m/$config{include}/;
2095 if (! defined $file_prune_regexp) {
2096 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2097 $file_prune_regexp=qr/$file_prune_regexp/;
2099 return $file =~ m/$file_prune_regexp/;
2102 sub define_gettext () {
2103 # If translation is needed, redefine the gettext function to do it.
2104 # Otherwise, it becomes a quick no-op.
2107 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2108 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2109 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2111 $gettext_obj=eval q{
2112 use Locale::gettext q{textdomain};
2113 Locale::gettext->domain('ikiwiki')
2118 no warnings 'redefine';
2120 $getobj->() if $getobj;
2122 $gettext_obj->get(shift);
2129 $getobj->() if $getobj;
2131 $gettext_obj->nget(@_);
2134 return ($_[2] == 1 ? $_[0] : $_[1])
2152 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2156 # Injects a new function into the symbol table to replace an
2157 # exported function.
2160 # This is deep ugly perl foo, beware.
2163 if (! defined $params{parent}) {
2164 $params{parent}='::';
2165 $params{old}=\&{$params{name}};
2166 $params{name}=~s/.*:://;
2168 my $parent=$params{parent};
2169 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2170 $ns = $params{parent} . $ns;
2171 inject(%params, parent => $ns) unless $ns eq '::main::';
2172 *{$ns . $params{name}} = $params{call}
2173 if exists ${$ns}{$params{name}} &&
2174 \&{${$ns}{$params{name}}} == $params{old};
2180 sub add_link ($$;$) {
2185 push @{$links{$page}}, $link
2186 unless grep { $_ eq $link } @{$links{$page}};
2188 if (defined $type) {
2189 $typedlinks{$page}{$type}{$link} = 1;
2193 sub add_autofile ($$$) {
2196 my $generator=shift;
2198 $autofiles{$file}{plugin}=$plugin;
2199 $autofiles{$file}{generator}=$generator;
2202 sub sortspec_translate ($$) {
2204 my $reverse = shift;
2210 (-?) # group 1: perhaps negated
2213 \w+\([^\)]*\) # command(params)
2215 [^\s]+ # or anything else
2223 if ($word =~ m/^(\w+)\((.*)\)$/) {
2224 # command with parameters
2228 elsif ($word !~ m/^\w+$/) {
2229 error(sprintf(gettext("invalid sort type %s"), $word));
2240 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2241 if (defined $params) {
2242 push @data, $params;
2243 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2246 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2250 error(sprintf(gettext("unknown sort type %s"), $word));
2254 if (! length $code) {
2255 # undefined sorting method... sort arbitrarily
2264 return eval 'sub { '.$code.' }';
2267 sub pagespec_translate ($) {
2270 # Convert spec to perl code.
2274 \s* # ignore whitespace
2275 ( # 1: match a single word
2282 \w+\([^\)]*\) # command(params)
2284 [^\s()]+ # any other text
2286 \s* # ignore whitespace
2289 if (lc $word eq 'and') {
2292 elsif (lc $word eq 'or') {
2295 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2298 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2299 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2301 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2304 push @data, qq{unknown function in pagespec "$word"};
2305 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2310 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2314 if (! length $code) {
2315 $code="IkiWiki::FailReason->new('empty pagespec')";
2319 return eval 'sub { my $page=shift; '.$code.' }';
2322 sub pagespec_match ($$;@) {
2327 # Backwards compatability with old calling convention.
2329 unshift @params, 'location';
2332 my $sub=pagespec_translate($spec);
2333 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2335 return $sub->($page, @params);
2338 sub pagespec_match_list ($$;@) {
2343 # Backwards compatability with old calling convention.
2345 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2346 $params{list}=$page;
2347 $page=$params{location}; # ugh!
2350 my $sub=pagespec_translate($pagespec);
2351 error "syntax error in pagespec \"$pagespec\""
2353 my $sort=sortspec_translate($params{sort}, $params{reverse})
2354 if defined $params{sort};
2357 if (exists $params{list}) {
2358 @candidates=exists $params{filter}
2359 ? grep { ! $params{filter}->($_) } @{$params{list}}
2363 @candidates=exists $params{filter}
2364 ? grep { ! $params{filter}->($_) } keys %pagesources
2365 : keys %pagesources;
2368 # clear params, remainder is passed to pagespec
2369 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2370 my $num=$params{num};
2371 delete @params{qw{num deptype reverse sort filter list}};
2373 # when only the top matches will be returned, it's efficient to
2374 # sort before matching to pagespec,
2375 if (defined $num && defined $sort) {
2376 @candidates=IkiWiki::SortSpec::sort_pages(
2377 $sort, @candidates);
2383 my $accum=IkiWiki::SuccessReason->new();
2384 foreach my $p (@candidates) {
2385 my $r=$sub->($p, %params, location => $page);
2386 error(sprintf(gettext("cannot match pages: %s"), $r))
2387 if $r->isa("IkiWiki::ErrorReason");
2388 unless ($r || $r->influences_static) {
2389 $r->remove_influence($p);
2394 last if defined $num && ++$count == $num;
2398 # Add simple dependencies for accumulated influences.
2399 my $i=$accum->influences;
2400 foreach my $k (keys %$i) {
2401 $depends_simple{$page}{lc $k} |= $i->{$k};
2404 # when all matches will be returned, it's efficient to
2405 # sort after matching
2406 if (! defined $num && defined $sort) {
2407 return IkiWiki::SortSpec::sort_pages(
2415 sub pagespec_valid ($) {
2418 return defined pagespec_translate($spec);
2422 my $re=quotemeta(shift);
2428 package IkiWiki::FailReason;
2431 '""' => sub { $_[0][0] },
2433 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2434 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2435 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2439 our @ISA = 'IkiWiki::SuccessReason';
2441 package IkiWiki::SuccessReason;
2444 '""' => sub { $_[0][0] },
2446 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2447 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2448 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2455 return bless [$value, {@_}], $class;
2460 $this->[1]={@_} if @_;
2461 my %i=%{$this->[1]};
2466 sub influences_static {
2467 return ! $_[0][1]->{""};
2470 sub merge_influences {
2475 if (! $anded || (($this || %{$this->[1]}) &&
2476 ($other || %{$other->[1]}))) {
2477 foreach my $influence (keys %{$other->[1]}) {
2478 $this->[1]{$influence} |= $other->[1]{$influence};
2487 sub remove_influence {
2491 delete $this->[1]{$torm};
2494 package IkiWiki::ErrorReason;
2496 our @ISA = 'IkiWiki::FailReason';
2498 package IkiWiki::PageSpec;
2504 if ($path =~ m!^\.(/|$)!) {
2506 $from=~s#/?[^/]+$## if defined $from;
2508 $path="$from/$path" if defined $from && length $from;
2512 $path = "" unless defined $path;
2521 sub match_glob ($$;@) {
2526 $glob=derel($glob, $params{location});
2528 # Instead of converting the glob to a regex every time,
2529 # cache the compiled regex to save time.
2530 my $re=$glob_cache{$glob};
2531 unless (defined $re) {
2532 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2535 if (! IkiWiki::isinternal($page) || $params{internal}) {
2536 return IkiWiki::SuccessReason->new("$glob matches $page");
2539 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2543 return IkiWiki::FailReason->new("$glob does not match $page");
2547 sub match_internal ($$;@) {
2548 return match_glob(shift, shift, @_, internal => 1)
2551 sub match_page ($$;@) {
2553 my $match=match_glob($page, shift, @_);
2555 my $source=exists $IkiWiki::pagesources{$page} ?
2556 $IkiWiki::pagesources{$page} :
2557 $IkiWiki::delpagesources{$page};
2558 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2559 if (! defined $type) {
2560 return IkiWiki::FailReason->new("$page is not a page");
2566 sub match_link ($$;@) {
2571 $link=derel($link, $params{location});
2572 my $from=exists $params{location} ? $params{location} : '';
2573 my $linktype=$params{linktype};
2575 if (defined $linktype) {
2576 $qualifier=" with type $linktype";
2579 my $links = $IkiWiki::links{$page};
2580 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2581 unless $links && @{$links};
2582 my $bestlink = IkiWiki::bestlink($from, $link);
2583 foreach my $p (@{$links}) {
2584 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2586 if (length $bestlink) {
2587 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2588 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2592 if (match_glob($p, $link, %params)) {
2593 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2595 my ($p_rel)=$p=~/^\/?(.*)/;
2597 if (match_glob($p_rel, $link, %params)) {
2598 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2602 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2605 sub match_backlink ($$;@) {
2606 my $ret=match_link($_[1], $_[0], @_);
2607 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2611 sub match_created_before ($$;@) {
2616 $testpage=derel($testpage, $params{location});
2618 if (exists $IkiWiki::pagectime{$testpage}) {
2619 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2620 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2623 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2627 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2631 sub match_created_after ($$;@) {
2636 $testpage=derel($testpage, $params{location});
2638 if (exists $IkiWiki::pagectime{$testpage}) {
2639 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2640 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2643 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2647 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2651 sub match_creation_day ($$;@) {
2654 if ($d !~ /^\d+$/) {
2655 return IkiWiki::ErrorReason->new("invalid day $d");
2657 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2658 return IkiWiki::SuccessReason->new('creation_day matched');
2661 return IkiWiki::FailReason->new('creation_day did not match');
2665 sub match_creation_month ($$;@) {
2668 if ($m !~ /^\d+$/) {
2669 return IkiWiki::ErrorReason->new("invalid month $m");
2671 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2672 return IkiWiki::SuccessReason->new('creation_month matched');
2675 return IkiWiki::FailReason->new('creation_month did not match');
2679 sub match_creation_year ($$;@) {
2682 if ($y !~ /^\d+$/) {
2683 return IkiWiki::ErrorReason->new("invalid year $y");
2685 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2686 return IkiWiki::SuccessReason->new('creation_year matched');
2689 return IkiWiki::FailReason->new('creation_year did not match');
2693 sub match_user ($$;@) {
2698 my $regexp=IkiWiki::glob2re($user);
2700 if (! exists $params{user}) {
2701 return IkiWiki::ErrorReason->new("no user specified");
2704 if (defined $params{user} && $params{user}=~$regexp) {
2705 return IkiWiki::SuccessReason->new("user is $user");
2707 elsif (! defined $params{user}) {
2708 return IkiWiki::FailReason->new("not logged in");
2711 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2715 sub match_admin ($$;@) {
2720 if (! exists $params{user}) {
2721 return IkiWiki::ErrorReason->new("no user specified");
2724 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2725 return IkiWiki::SuccessReason->new("user is an admin");
2727 elsif (! defined $params{user}) {
2728 return IkiWiki::FailReason->new("not logged in");
2731 return IkiWiki::FailReason->new("user is not an admin");
2735 sub match_ip ($$;@) {
2740 if (! exists $params{ip}) {
2741 return IkiWiki::ErrorReason->new("no IP specified");
2744 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2745 return IkiWiki::SuccessReason->new("IP is $ip");
2748 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2752 package IkiWiki::SortSpec;
2754 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2755 # are easily available in this namespace, for cmp functions to use them.
2762 IkiWiki::pagetitle(IkiWiki::basename($a))
2764 IkiWiki::pagetitle(IkiWiki::basename($b))
2767 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2768 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }