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?",
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 => "US/Eastern",
343 description => "time zone name",
350 example => '^\.htaccess$',
351 description => "regexp of normally excluded files to include",
359 example => '^(*\.private|Makefile)$',
360 description => "regexp of files that should be skipped",
365 wiki_file_prune_regexps => {
367 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
368 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
369 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
370 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
371 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
372 description => "regexps of source files to ignore",
378 description => "specifies the characters that are allowed in source filenames",
379 default => "-[:alnum:]+/.:_",
383 wiki_file_regexp => {
385 description => "regexp of legal source files",
389 web_commit_regexp => {
391 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
392 description => "regexp to parse web commits from logs",
399 description => "run as a cgi",
403 cgi_disable_uploads => {
406 description => "whether CGI should accept file uploads",
413 description => "run as a post-commit hook",
420 description => "running in rebuild mode",
427 description => "running in setup mode",
434 description => "running in clean mode",
441 description => "running in refresh mode",
448 description => "running in receive test mode",
452 wrapper_background_command => {
455 description => "background shell command to run",
461 description => "running in gettime mode",
468 description => "running in w3mmode",
475 description => "path to the .ikiwiki directory holding ikiwiki state",
482 description => "path to setup file",
489 description => "perl class to use to dump setup file",
493 allow_symlinks_before_srcdir => {
496 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
502 sub defaultconfig () {
505 foreach my $key (keys %s) {
506 push @ret, $key, $s{$key}->{default};
511 # URL to top of wiki as a path starting with /, valid from any wiki page or
512 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
514 # URL to CGI script, similar to $local_url
518 # locale stuff; avoid LC_ALL since it overrides everything
519 if (defined $ENV{LC_ALL}) {
520 $ENV{LANG} = $ENV{LC_ALL};
523 if (defined $config{locale}) {
524 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
525 $ENV{LANG}=$config{locale};
530 if (! defined $config{wiki_file_regexp}) {
531 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
534 if (ref $config{ENV} eq 'HASH') {
535 foreach my $val (keys %{$config{ENV}}) {
536 $ENV{$val}=$config{ENV}{$val};
539 if (defined $config{timezone} && length $config{timezone}) {
540 $ENV{TZ}=$config{timezone};
543 $config{timezone}=$ENV{TZ};
546 if ($config{w3mmode}) {
547 eval q{use Cwd q{abs_path}};
549 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
550 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
551 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
552 unless $config{cgiurl} =~ m!file:///!;
553 $config{url}="file://".$config{destdir};
556 if ($config{cgi} && ! length $config{url}) {
557 error(gettext("Must specify url to wiki with --url when using --cgi"));
560 if (defined $config{url} && length $config{url}) {
562 my $baseurl = URI->new($config{url});
564 $local_url = $baseurl->path . "/";
565 $local_cgiurl = undef;
567 if (length $config{cgiurl}) {
568 my $cgiurl = URI->new($config{cgiurl});
570 $local_cgiurl = $cgiurl->path;
572 if ($cgiurl->scheme ne $baseurl->scheme or
573 $cgiurl->authority ne $baseurl->authority) {
574 # too far apart, fall back to absolute URLs
575 $local_url = "$config{url}/";
576 $local_cgiurl = $config{cgiurl};
580 $local_url =~ s{//$}{/};
583 $local_cgiurl = $config{cgiurl};
586 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
587 unless exists $config{wikistatedir} && defined $config{wikistatedir};
589 if (defined $config{umask}) {
590 umask(possibly_foolish_untaint($config{umask}));
593 run_hooks(checkconfig => sub { shift->() });
601 foreach my $dir (@INC, $config{libdir}) {
602 next unless defined $dir && length $dir;
603 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
604 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
608 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
609 next unless defined $dir && length $dir;
610 foreach my $file (glob("$dir/plugins/*")) {
611 $ret{basename($file)}=1 if -x $file;
619 if (defined $config{libdir} && length $config{libdir}) {
620 unshift @INC, possibly_foolish_untaint($config{libdir});
623 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
628 if (exists $hooks{rcs}) {
629 error(gettext("cannot use multiple rcs plugins"));
631 loadplugin($config{rcs});
633 if (! exists $hooks{rcs}) {
637 run_hooks(getopt => sub { shift->() });
638 if (grep /^-/, @ARGV) {
639 print STDERR "Unknown option (or missing parameter): $_\n"
640 foreach grep /^-/, @ARGV;
647 sub loadplugin ($;$) {
651 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
653 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
654 "$installdir/lib/ikiwiki") {
655 if (defined $dir && -x "$dir/plugins/$plugin") {
656 eval { require IkiWiki::Plugin::external };
659 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
661 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
662 $loaded_plugins{$plugin}=1;
667 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
670 error("Failed to load plugin $mod: $@");
672 $loaded_plugins{$plugin}=1;
679 log_message('err' => $message) if $config{syslog};
680 if (defined $cleaner) {
687 return unless $config{verbose};
688 return log_message(debug => @_);
692 sub log_message ($$) {
695 if ($config{syslog}) {
698 Sys::Syslog::setlogsock('unix');
699 Sys::Syslog::openlog('ikiwiki', '', 'user');
703 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
706 elsif (! $config{cgi}) {
710 return print STDERR "@_\n";
714 sub possibly_foolish_untaint ($) {
716 my ($untainted)=$tainted=~/(.*)/s;
736 return exists $pagesources{$page} &&
737 $pagesources{$page} =~ /\._([^.]+)$/;
743 if ($file =~ /\.([^.]+)$/) {
744 return $1 if exists $hooks{htmlize}{$1};
746 my $base=basename($file);
747 if (exists $hooks{htmlize}{$base} &&
748 $hooks{htmlize}{$base}{noextension}) {
759 if (exists $pagename_cache{$file}) {
760 return $pagename_cache{$file};
763 my $type=pagetype($file);
765 $page=~s/\Q.$type\E*$//
766 if defined $type && !$hooks{htmlize}{$type}{keepextension}
767 && !$hooks{htmlize}{$type}{noextension};
768 if ($config{indexpages} && $page=~/(.*)\/index$/) {
772 $pagename_cache{$file} = $page;
776 sub newpagefile ($$) {
780 if (! $config{indexpages} || $page eq 'index') {
781 return $page.".".$type;
784 return $page."/index.".$type;
788 sub targetpage ($$;$) {
793 if (defined $filename) {
794 return $page."/".$filename.".".$ext;
796 elsif (! $config{usedirs} || $page eq 'index') {
797 return $page.".".$ext;
800 return $page."/index.".$ext;
807 return targetpage($page, $config{htmlext});
814 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
815 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
816 return "$dir/$file", stat(_) if -e "$dir/$file";
818 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
823 return (srcfile_stat(@_))[0];
826 sub add_literal_underlay ($) {
829 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
830 unshift @{$config{underlaydirs}}, $dir;
834 sub add_underlay ($) {
838 $dir="$config{underlaydirbase}/$dir";
841 add_literal_underlay($dir);
842 # why does it return 1? we just don't know
846 sub readfile ($;$$) {
852 error("cannot read a symlink ($file)");
856 open (my $in, "<", $file) || error("failed to read $file: $!");
857 binmode($in) if ($binary);
858 return \*$in if $wantfd;
860 # check for invalid utf-8, and toss it back to avoid crashes
861 if (! utf8::valid($ret)) {
862 $ret=encode_utf8($ret);
864 close $in || error("failed to read $file: $!");
868 sub prep_writefile ($$) {
873 while (length $test) {
874 if (-l "$destdir/$test") {
875 error("cannot write to a symlink ($test)");
877 if (-f _ && $test ne $file) {
878 # Remove conflicting file.
879 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
880 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
882 unlink("$destdir/$test");
888 $test=dirname($test);
891 my $dir=dirname("$destdir/$file");
894 foreach my $s (split(m!/+!, $dir)) {
897 mkdir($d) || error("failed to create directory $d: $!");
905 sub writefile ($$$;$$) {
906 my $file=shift; # can include subdirs
907 my $destdir=shift; # directory to put file in
912 prep_writefile($file, $destdir);
914 my $newfile="$destdir/$file.ikiwiki-new";
916 error("cannot write to a symlink ($newfile)");
919 my $cleanup = sub { unlink($newfile) };
920 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
921 binmode($out) if ($binary);
923 $writer->(\*$out, $cleanup);
926 print $out $content or error("failed writing to $newfile: $!", $cleanup);
928 close $out || error("failed saving $newfile: $!", $cleanup);
929 rename($newfile, "$destdir/$file") ||
930 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
936 sub will_render ($$;$) {
941 # Important security check for independently created files.
942 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
943 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
944 my $from_other_page=0;
945 # Expensive, but rarely runs.
946 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
950 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
956 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
957 unless $from_other_page;
960 # If $dest exists as a directory, remove conflicting files in it
961 # rendered from other pages.
963 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
964 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
965 if (dirname($f) eq $dest) {
966 unlink("$config{destdir}/$f");
967 rmdir(dirname("$config{destdir}/$f"));
973 if (! $clear || $cleared{$page}) {
974 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
977 foreach my $old (@{$renderedfiles{$page}}) {
978 delete $destsources{$old};
980 $renderedfiles{$page}=[$dest];
983 $destsources{$dest}=$page;
993 if ($link=~s/^\/+//) {
1001 $l.="/" if length $l;
1004 if (exists $pagesources{$l}) {
1007 elsif (exists $pagecase{lc $l}) {
1008 return $pagecase{lc $l};
1010 } while $cwd=~s{/?[^/]+$}{};
1012 if (length $config{userdir}) {
1013 my $l = "$config{userdir}/".lc($link);
1014 if (exists $pagesources{$l}) {
1017 elsif (exists $pagecase{lc $l}) {
1018 return $pagecase{lc $l};
1022 #print STDERR "warning: page $page, broken link: $link\n";
1026 sub isinlinableimage ($) {
1029 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1032 sub pagetitle ($;$) {
1034 my $unescaped=shift;
1037 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1040 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1048 # support use w/o %config set
1049 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1050 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1056 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1057 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1064 my $cgiurl=$local_cgiurl;
1066 if (exists $params{cgiurl}) {
1067 $cgiurl=$params{cgiurl};
1068 delete $params{cgiurl};
1076 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1082 return $local_url if ! defined $page;
1084 $page=htmlpage($page);
1086 $page=~s/[^\/]+\//..\//g;
1094 return $url unless defined $urlbase && length $urlbase;
1097 URI->new_abs($url, $urlbase)->as_string;
1101 # Work around very innefficient behavior in File::Spec if abs2rel
1102 # is passed two relative paths. It's much faster if paths are
1103 # absolute! (Debian bug #376658; fixed in debian unstable now)
1108 my $ret=File::Spec->abs2rel($path, $base);
1109 $ret=~s/^// if defined $ret;
1113 sub displaytime ($;$$) {
1114 # Plugins can override this function to mark up the time to
1116 my $time=formattime($_[0], $_[1]);
1117 if ($config{html5}) {
1118 return '<time datetime="'.date_3339($_[0]).'"'.
1119 ($_[2] ? ' pubdate="pubdate"' : '').
1120 '>'.$time.'</time>';
1123 return '<span class="date">'.$time.'</span>';
1127 sub formattime ($;$) {
1128 # Plugins can override this function to format the time.
1131 if (! defined $format) {
1132 $format=$config{timeformat};
1135 # strftime doesn't know about encodings, so make sure
1136 # its output is properly treated as utf8
1137 return decode_utf8(POSIX::strftime($format, localtime($time)));
1143 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1144 POSIX::setlocale(&POSIX::LC_TIME, "C");
1145 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1146 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1150 sub beautify_urlpath ($) {
1153 # Ensure url is not an empty link, and if necessary,
1154 # add ./ to avoid colon confusion.
1155 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1159 if ($config{usedirs}) {
1160 $url =~ s!/index.$config{htmlext}$!/!;
1175 if (! $destsources{$to}) {
1180 return $config{url}.beautify_urlpath("/".$to);
1183 if (! defined $from) {
1184 my $u = $local_url || '';
1186 return $u.beautify_urlpath("/".$to);
1189 my $link = abs2rel($to, dirname(htmlpage($from)));
1191 return beautify_urlpath($link);
1194 sub isselflink ($$) {
1195 # Plugins can override this function to support special types
1200 return $page eq $link;
1203 sub htmllink ($$$;@) {
1204 my $lpage=shift; # the page doing the linking
1205 my $page=shift; # the page that will contain the link (different for inline)
1212 if (! $opts{forcesubpage}) {
1213 $bestlink=bestlink($lpage, $link);
1216 $bestlink="$lpage/".lc($link);
1220 if (defined $opts{linktext}) {
1221 $linktext=$opts{linktext};
1224 $linktext=pagetitle(basename($link));
1227 return "<span class=\"selflink\">$linktext</span>"
1228 if length $bestlink && isselflink($page, $bestlink) &&
1229 ! defined $opts{anchor};
1231 if (! $destsources{$bestlink}) {
1232 $bestlink=htmlpage($bestlink);
1234 if (! $destsources{$bestlink}) {
1236 if (length $config{cgiurl}) {
1237 $cgilink = "<a href=\"".
1242 )."\" rel=\"nofollow\">?</a>";
1244 return "<span class=\"createlink\">$cgilink$linktext</span>"
1248 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1249 $bestlink=beautify_urlpath($bestlink);
1251 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1252 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1255 if (defined $opts{anchor}) {
1256 $bestlink.="#".$opts{anchor};
1260 foreach my $attr (qw{rel class title}) {
1261 if (defined $opts{$attr}) {
1262 push @attrs, " $attr=\"$opts{$attr}\"";
1266 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1271 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1274 sub openiduser ($) {
1277 if (defined $user && $user =~ m!^https?://! &&
1278 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1281 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1282 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1285 # backcompat with old version
1286 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1287 $display=$oid->display;
1290 # Convert "user.somehost.com" to "user [somehost.com]"
1291 # (also "user.somehost.co.uk")
1292 if ($display !~ /\[/) {
1293 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1295 # Convert "http://somehost.com/user" to "user [somehost.com]".
1296 # (also "https://somehost.com/user/")
1297 if ($display !~ /\[/) {
1298 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1300 $display=~s!^https?://!!; # make sure this is removed
1301 eval q{use CGI 'escapeHTML'};
1303 return escapeHTML($display);
1308 sub htmlize ($$$$) {
1314 my $oneline = $content !~ /\n/;
1316 if (exists $hooks{htmlize}{$type}) {
1317 $content=$hooks{htmlize}{$type}{call}->(
1319 content => $content,
1323 error("htmlization of $type not supported");
1326 run_hooks(sanitize => sub {
1329 destpage => $destpage,
1330 content => $content,
1335 # hack to get rid of enclosing junk added by markdown
1336 # and other htmlizers/sanitizers
1337 $content=~s/^<p>//i;
1338 $content=~s/<\/p>\n*$//i;
1349 run_hooks(linkify => sub {
1352 destpage => $destpage,
1353 content => $content,
1361 our $preprocess_preview=0;
1362 sub preprocess ($$$;$$) {
1363 my $page=shift; # the page the data comes from
1364 my $destpage=shift; # the page the data will appear in (different for inline)
1369 # Using local because it needs to be set within any nested calls
1371 local $preprocess_preview=$preview if defined $preview;
1378 $params="" if ! defined $params;
1380 if (length $escape) {
1381 return "[[$prefix$command $params]]";
1383 elsif (exists $hooks{preprocess}{$command}) {
1384 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1385 # Note: preserve order of params, some plugins may
1386 # consider it significant.
1388 while ($params =~ m{
1389 (?:([-\w]+)=)? # 1: named parameter key?
1391 """(.*?)""" # 2: triple-quoted value
1393 "([^"]*?)" # 3: single-quoted value
1395 '''(.*?)''' # 4: triple-single-quote
1397 <<(?<start>[a-zA-Z]+)\n(?<heredoc>.*?)\n\k<start> # 5, 6: heredoc'd value.
1399 (\S+) # 7: unquoted value
1401 (?:\s+|$) # delimiter to next param
1411 elsif (defined $3) {
1414 elsif (defined $4) {
1417 elsif (defined $7) {
1420 elsif (defined $+{heredoc}) {
1425 push @params, $key, $val;
1428 push @params, $val, '';
1431 if ($preprocessing{$page}++ > 3) {
1432 # Avoid loops of preprocessed pages preprocessing
1433 # other pages that preprocess them, etc.
1434 return "[[!$command <span class=\"error\">".
1435 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1436 $page, $preprocessing{$page}).
1442 $hooks{preprocess}{$command}{call}->(
1445 destpage => $destpage,
1446 preview => $preprocess_preview,
1452 $ret="[[!$command <span class=\"error\">".
1453 gettext("Error").": $error"."</span>]]";
1457 # use void context during scan pass
1459 $hooks{preprocess}{$command}{call}->(
1462 destpage => $destpage,
1463 preview => $preprocess_preview,
1468 $preprocessing{$page}--;
1472 return "[[$prefix$command $params]]";
1477 if ($config{prefix_directives}) {
1480 \[\[(!) # directive open; 2: prefix
1481 ([-\w]+) # 3: command
1482 ( # 4: the parameters..
1483 \s+ # Must have space if parameters present
1485 (?:[-\w]+=)? # named parameter key?
1487 """.*?""" # triple-quoted value
1489 "[^"]*?" # single-quoted value
1491 <<(?<start>[a-zA-Z]+)\n(?<heredoc>.*?)\n\k<start> # heredoc'd value.
1493 '''.*?''' # triple-single-quoted value
1495 [^"\s\]]+ # unquoted value
1497 \s* # whitespace or end
1500 *)? # 0 or more parameters
1501 \]\] # directive closed
1507 \[\[(!?) # directive open; 2: optional prefix
1508 ([-\w]+) # 3: command
1510 ( # 4: the parameters..
1512 (?:[-\w]+=)? # named parameter key?
1514 """.*?""" # triple-quoted value
1516 "[^"]*?" # single-quoted value
1518 '''.*?''' # triple-single-quoted value
1520 <<(?<start>[a-zA-Z]+)\n(?<heredoc>.*?)\n\k<start> # heredoc'd value.
1522 [^"\s\]]+ # unquoted value
1524 \s* # whitespace or end
1527 *) # 0 or more parameters
1528 \]\] # directive closed
1532 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1541 run_hooks(filter => sub {
1542 $content=shift->(page => $page, destpage => $destpage,
1543 content => $content);
1549 sub check_canedit ($$$;$) {
1556 run_hooks(canedit => sub {
1557 return if defined $canedit;
1558 my $ret=shift->($page, $q, $session);
1563 elsif (ref $ret eq 'CODE') {
1564 $ret->() unless $nonfatal;
1567 elsif (defined $ret) {
1568 error($ret) unless $nonfatal;
1573 return defined $canedit ? $canedit : 1;
1576 sub check_content (@) {
1579 return 1 if ! exists $hooks{checkcontent}; # optimisation
1581 if (exists $pagesources{$params{page}}) {
1583 my %old=map { $_ => 1 }
1584 split("\n", readfile(srcfile($pagesources{$params{page}})));
1585 foreach my $line (split("\n", $params{content})) {
1586 push @diff, $line if ! exists $old{$line};
1588 $params{diff}=join("\n", @diff);
1592 run_hooks(checkcontent => sub {
1593 return if defined $ok;
1594 my $ret=shift->(%params);
1599 elsif (ref $ret eq 'CODE') {
1600 $ret->() unless $params{nonfatal};
1603 elsif (defined $ret) {
1604 error($ret) unless $params{nonfatal};
1610 return defined $ok ? $ok : 1;
1613 sub check_canchange (@) {
1615 my $cgi = $params{cgi};
1616 my $session = $params{session};
1617 my @changes = @{$params{changes}};
1620 foreach my $change (@changes) {
1621 # This untaint is safe because we check file_pruned and
1623 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1624 $file=possibly_foolish_untaint($file);
1625 if (! defined $file || ! length $file ||
1626 file_pruned($file)) {
1627 error(gettext("bad file name %s"), $file);
1630 my $type=pagetype($file);
1631 my $page=pagename($file) if defined $type;
1633 if ($change->{action} eq 'add') {
1637 if ($change->{action} eq 'change' ||
1638 $change->{action} eq 'add') {
1639 if (defined $page) {
1640 check_canedit($page, $cgi, $session);
1644 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1645 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1646 check_canedit($file, $cgi, $session);
1651 elsif ($change->{action} eq 'remove') {
1652 # check_canremove tests to see if the file is present
1653 # on disk. This will fail when a single commit adds a
1654 # file and then removes it again. Avoid the problem
1655 # by not testing the removal in such pairs of changes.
1656 # (The add is still tested, just to make sure that
1657 # no data is added to the repo that a web edit
1659 next if $newfiles{$file};
1661 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1662 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1663 check_canedit(defined $page ? $page : $file, $cgi, $session);
1668 error "unknown action ".$change->{action};
1671 error sprintf(gettext("you are not allowed to change %s"), $file);
1679 # Take an exclusive lock on the wiki to prevent multiple concurrent
1680 # run issues. The lock will be dropped on program exit.
1681 if (! -d $config{wikistatedir}) {
1682 mkdir($config{wikistatedir});
1684 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1685 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1686 if (! flock($wikilock, 2)) { # LOCK_EX
1687 error("failed to get lock");
1693 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1694 return close($wikilock) if $wikilock;
1700 sub commit_hook_enabled () {
1701 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1702 error("cannot write to $config{wikistatedir}/commitlock: $!");
1703 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1704 close($commitlock) || error("failed closing commitlock: $!");
1707 close($commitlock) || error("failed closing commitlock: $!");
1711 sub disable_commit_hook () {
1712 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1713 error("cannot write to $config{wikistatedir}/commitlock: $!");
1714 if (! flock($commitlock, 2)) { # LOCK_EX
1715 error("failed to get commit lock");
1720 sub enable_commit_hook () {
1721 return close($commitlock) if $commitlock;
1726 %oldrenderedfiles=%pagectime=();
1727 if (! $config{rebuild}) {
1728 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1729 %destsources=%renderedfiles=%pagecase=%pagestate=
1730 %depends_simple=%typedlinks=%oldtypedlinks=();
1733 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1734 if (-e "$config{wikistatedir}/index") {
1735 system("ikiwiki-transition", "indexdb", $config{srcdir});
1736 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1739 $config{gettime}=1; # first build
1744 my $index=Storable::fd_retrieve($in);
1745 if (! defined $index) {
1750 if (exists $index->{version} && ! ref $index->{version}) {
1751 $pages=$index->{page};
1752 %wikistate=%{$index->{state}};
1753 # Handle plugins that got disabled by loading a new setup.
1754 if (exists $config{setupfile}) {
1755 require IkiWiki::Setup;
1756 IkiWiki::Setup::disabled_plugins(
1757 grep { ! $loaded_plugins{$_} } keys %wikistate);
1765 foreach my $src (keys %$pages) {
1766 my $d=$pages->{$src};
1767 my $page=pagename($src);
1768 $pagectime{$page}=$d->{ctime};
1769 $pagesources{$page}=$src;
1770 if (! $config{rebuild}) {
1771 $pagemtime{$page}=$d->{mtime};
1772 $renderedfiles{$page}=$d->{dest};
1773 if (exists $d->{links} && ref $d->{links}) {
1774 $links{$page}=$d->{links};
1775 $oldlinks{$page}=[@{$d->{links}}];
1777 if (ref $d->{depends_simple} eq 'ARRAY') {
1779 $depends_simple{$page}={
1780 map { $_ => 1 } @{$d->{depends_simple}}
1783 elsif (exists $d->{depends_simple}) {
1784 $depends_simple{$page}=$d->{depends_simple};
1786 if (exists $d->{dependslist}) {
1789 map { $_ => $DEPEND_CONTENT }
1790 @{$d->{dependslist}}
1793 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1795 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1797 elsif (exists $d->{depends}) {
1798 $depends{$page}=$d->{depends};
1800 if (exists $d->{state}) {
1801 $pagestate{$page}=$d->{state};
1803 if (exists $d->{typedlinks}) {
1804 $typedlinks{$page}=$d->{typedlinks};
1806 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1807 next unless %$links;
1808 $oldtypedlinks{$page}{$type} = {%$links};
1812 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1814 foreach my $page (keys %pagesources) {
1815 $pagecase{lc $page}=$page;
1817 foreach my $page (keys %renderedfiles) {
1818 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1824 run_hooks(savestate => sub { shift->() });
1826 my @plugins=keys %loaded_plugins;
1828 if (! -d $config{wikistatedir}) {
1829 mkdir($config{wikistatedir});
1831 my $newfile="$config{wikistatedir}/indexdb.new";
1832 my $cleanup = sub { unlink($newfile) };
1833 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1836 foreach my $page (keys %pagemtime) {
1837 next unless $pagemtime{$page};
1838 my $src=$pagesources{$page};
1840 $index{page}{$src}={
1841 ctime => $pagectime{$page},
1842 mtime => $pagemtime{$page},
1843 dest => $renderedfiles{$page},
1844 links => $links{$page},
1847 if (exists $depends{$page}) {
1848 $index{page}{$src}{depends} = $depends{$page};
1851 if (exists $depends_simple{$page}) {
1852 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1855 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1856 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1859 if (exists $pagestate{$page}) {
1860 foreach my $id (@plugins) {
1861 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1862 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1869 foreach my $id (@plugins) {
1870 $index{state}{$id}={}; # used to detect disabled plugins
1871 foreach my $key (keys %{$wikistate{$id}}) {
1872 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1876 $index{version}="3";
1877 my $ret=Storable::nstore_fd(\%index, $out);
1878 return if ! defined $ret || ! $ret;
1879 close $out || error("failed saving to $newfile: $!", $cleanup);
1880 rename($newfile, "$config{wikistatedir}/indexdb") ||
1881 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1886 sub template_file ($) {
1889 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1891 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1892 $template=srcfile($pagesources{$tpage}, 1);
1896 $template=srcfile($tpage, 1);
1899 if (defined $template) {
1900 return $template, $tpage, 1 if wantarray;
1904 $name=~s:/::; # avoid path traversal
1905 foreach my $dir ($config{templatedir},
1906 "$installdir/share/ikiwiki/templates") {
1907 if (-e "$dir/$name") {
1908 $template="$dir/$name";
1912 if (defined $template) {
1913 return $template, $tpage if wantarray;
1921 sub template_depends ($$;@) {
1925 my ($filename, $tpage, $untrusted)=template_file($name);
1926 if (! defined $filename) {
1927 error(sprintf(gettext("template %s not found"), $name))
1930 if (defined $page && defined $tpage) {
1931 add_depends($page, $tpage);
1936 my $text_ref = shift;
1937 ${$text_ref} = decode_utf8(${$text_ref});
1939 loop_context_vars => 1,
1940 die_on_bad_params => 0,
1941 parent_global_vars => 1,
1942 filename => $filename,
1944 ($untrusted ? (no_includes => 1) : ()),
1946 return @opts if wantarray;
1948 require HTML::Template;
1949 return HTML::Template->new(@opts);
1952 sub template ($;@) {
1953 template_depends(shift, undef, @_);
1956 sub templateactions ($$) {
1962 run_hooks(pageactions => sub {
1963 push @actions, map { { action => $_ } }
1964 grep { defined } shift->(page => $page);
1966 $template->param(actions => \@actions);
1968 if ($config{cgiurl} && exists $hooks{auth}) {
1969 $template->param(prefsurl => cgiurl(do => "prefs"));
1973 if ($have_actions || @actions) {
1974 $template->param(have_actions => 1);
1981 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1982 error 'hook requires type, call, and id parameters';
1985 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1987 $hooks{$param{type}}{$param{id}}=\%param;
1991 sub run_hooks ($$) {
1992 # Calls the given sub for each hook of the given type,
1993 # passing it the hook function to call.
1997 if (exists $hooks{$type}) {
1998 my (@first, @middle, @last);
1999 foreach my $id (keys %{$hooks{$type}}) {
2000 if ($hooks{$type}{$id}{first}) {
2003 elsif ($hooks{$type}{$id}{last}) {
2010 foreach my $id (@first, @middle, @last) {
2011 $sub->($hooks{$type}{$id}{call});
2019 $hooks{rcs}{rcs_update}{call}->(@_);
2022 sub rcs_prepedit ($) {
2023 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2026 sub rcs_commit (@) {
2027 $hooks{rcs}{rcs_commit}{call}->(@_);
2030 sub rcs_commit_staged (@) {
2031 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2035 $hooks{rcs}{rcs_add}{call}->(@_);
2038 sub rcs_remove ($) {
2039 $hooks{rcs}{rcs_remove}{call}->(@_);
2042 sub rcs_rename ($$) {
2043 $hooks{rcs}{rcs_rename}{call}->(@_);
2046 sub rcs_recentchanges ($) {
2047 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2050 sub rcs_diff ($;$) {
2051 $hooks{rcs}{rcs_diff}{call}->(@_);
2054 sub rcs_getctime ($) {
2055 $hooks{rcs}{rcs_getctime}{call}->(@_);
2058 sub rcs_getmtime ($) {
2059 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2062 sub rcs_receive () {
2063 $hooks{rcs}{rcs_receive}{call}->();
2066 sub add_depends ($$;$) {
2069 my $deptype=shift || $DEPEND_CONTENT;
2071 # Is the pagespec a simple page name?
2072 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2073 $pagespec !~ /[\s*?()!]/) {
2074 $depends_simple{$page}{lc $pagespec} |= $deptype;
2078 # Add explicit dependencies for influences.
2079 my $sub=pagespec_translate($pagespec);
2080 return unless defined $sub;
2081 foreach my $p (keys %pagesources) {
2082 my $r=$sub->($p, location => $page);
2083 my $i=$r->influences;
2084 my $static=$r->influences_static;
2085 foreach my $k (keys %$i) {
2086 next unless $r || $static || $k eq $page;
2087 $depends_simple{$page}{lc $k} |= $i->{$k};
2092 $depends{$page}{$pagespec} |= $deptype;
2098 foreach my $type (@_) {
2099 if ($type eq 'presence') {
2100 $deptype |= $DEPEND_PRESENCE;
2102 elsif ($type eq 'links') {
2103 $deptype |= $DEPEND_LINKS;
2105 elsif ($type eq 'content') {
2106 $deptype |= $DEPEND_CONTENT;
2112 my $file_prune_regexp;
2113 sub file_pruned ($) {
2116 if (defined $config{include} && length $config{include}) {
2117 return 0 if $file =~ m/$config{include}/;
2120 if (! defined $file_prune_regexp) {
2121 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2122 $file_prune_regexp=qr/$file_prune_regexp/;
2124 return $file =~ m/$file_prune_regexp/;
2127 sub define_gettext () {
2128 # If translation is needed, redefine the gettext function to do it.
2129 # Otherwise, it becomes a quick no-op.
2132 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2133 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2134 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2136 $gettext_obj=eval q{
2137 use Locale::gettext q{textdomain};
2138 Locale::gettext->domain('ikiwiki')
2143 no warnings 'redefine';
2145 $getobj->() if $getobj;
2147 $gettext_obj->get(shift);
2154 $getobj->() if $getobj;
2156 $gettext_obj->nget(@_);
2159 return ($_[2] == 1 ? $_[0] : $_[1])
2177 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2181 # Injects a new function into the symbol table to replace an
2182 # exported function.
2185 # This is deep ugly perl foo, beware.
2188 if (! defined $params{parent}) {
2189 $params{parent}='::';
2190 $params{old}=\&{$params{name}};
2191 $params{name}=~s/.*:://;
2193 my $parent=$params{parent};
2194 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2195 $ns = $params{parent} . $ns;
2196 inject(%params, parent => $ns) unless $ns eq '::main::';
2197 *{$ns . $params{name}} = $params{call}
2198 if exists ${$ns}{$params{name}} &&
2199 \&{${$ns}{$params{name}}} == $params{old};
2205 sub add_link ($$;$) {
2210 push @{$links{$page}}, $link
2211 unless grep { $_ eq $link } @{$links{$page}};
2213 if (defined $type) {
2214 $typedlinks{$page}{$type}{$link} = 1;
2218 sub add_autofile ($$$) {
2221 my $generator=shift;
2223 $autofiles{$file}{plugin}=$plugin;
2224 $autofiles{$file}{generator}=$generator;
2227 sub sortspec_translate ($$) {
2229 my $reverse = shift;
2235 (-?) # group 1: perhaps negated
2238 \w+\([^\)]*\) # command(params)
2240 [^\s]+ # or anything else
2248 if ($word =~ m/^(\w+)\((.*)\)$/) {
2249 # command with parameters
2253 elsif ($word !~ m/^\w+$/) {
2254 error(sprintf(gettext("invalid sort type %s"), $word));
2265 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2266 if (defined $params) {
2267 push @data, $params;
2268 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2271 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2275 error(sprintf(gettext("unknown sort type %s"), $word));
2279 if (! length $code) {
2280 # undefined sorting method... sort arbitrarily
2289 return eval 'sub { '.$code.' }';
2292 sub pagespec_translate ($) {
2295 # Convert spec to perl code.
2299 \s* # ignore whitespace
2300 ( # 1: match a single word
2307 \w+\([^\)]*\) # command(params)
2309 [^\s()]+ # any other text
2311 \s* # ignore whitespace
2314 if (lc $word eq 'and') {
2317 elsif (lc $word eq 'or') {
2320 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2323 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2324 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2326 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2329 push @data, qq{unknown function in pagespec "$word"};
2330 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2335 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2339 if (! length $code) {
2340 $code="IkiWiki::FailReason->new('empty pagespec')";
2344 return eval 'sub { my $page=shift; '.$code.' }';
2347 sub pagespec_match ($$;@) {
2352 # Backwards compatability with old calling convention.
2354 unshift @params, 'location';
2357 my $sub=pagespec_translate($spec);
2358 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2360 return $sub->($page, @params);
2363 sub pagespec_match_list ($$;@) {
2368 # Backwards compatability with old calling convention.
2370 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2371 $params{list}=$page;
2372 $page=$params{location}; # ugh!
2375 my $sub=pagespec_translate($pagespec);
2376 error "syntax error in pagespec \"$pagespec\""
2378 my $sort=sortspec_translate($params{sort}, $params{reverse})
2379 if defined $params{sort};
2382 if (exists $params{list}) {
2383 @candidates=exists $params{filter}
2384 ? grep { ! $params{filter}->($_) } @{$params{list}}
2388 @candidates=exists $params{filter}
2389 ? grep { ! $params{filter}->($_) } keys %pagesources
2390 : keys %pagesources;
2393 # clear params, remainder is passed to pagespec
2394 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2395 my $num=$params{num};
2396 delete @params{qw{num deptype reverse sort filter list}};
2398 # when only the top matches will be returned, it's efficient to
2399 # sort before matching to pagespec,
2400 if (defined $num && defined $sort) {
2401 @candidates=IkiWiki::SortSpec::sort_pages(
2402 $sort, @candidates);
2408 my $accum=IkiWiki::SuccessReason->new();
2409 foreach my $p (@candidates) {
2410 my $r=$sub->($p, %params, location => $page);
2411 error(sprintf(gettext("cannot match pages: %s"), $r))
2412 if $r->isa("IkiWiki::ErrorReason");
2413 unless ($r || $r->influences_static) {
2414 $r->remove_influence($p);
2419 last if defined $num && ++$count == $num;
2423 # Add simple dependencies for accumulated influences.
2424 my $i=$accum->influences;
2425 foreach my $k (keys %$i) {
2426 $depends_simple{$page}{lc $k} |= $i->{$k};
2429 # when all matches will be returned, it's efficient to
2430 # sort after matching
2431 if (! defined $num && defined $sort) {
2432 return IkiWiki::SortSpec::sort_pages(
2440 sub pagespec_valid ($) {
2443 return defined pagespec_translate($spec);
2447 my $re=quotemeta(shift);
2453 package IkiWiki::FailReason;
2456 '""' => sub { $_[0][0] },
2458 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2459 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2460 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2464 our @ISA = 'IkiWiki::SuccessReason';
2466 package IkiWiki::SuccessReason;
2469 '""' => sub { $_[0][0] },
2471 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2472 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2473 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2480 return bless [$value, {@_}], $class;
2485 $this->[1]={@_} if @_;
2486 my %i=%{$this->[1]};
2491 sub influences_static {
2492 return ! $_[0][1]->{""};
2495 sub merge_influences {
2500 if (! $anded || (($this || %{$this->[1]}) &&
2501 ($other || %{$other->[1]}))) {
2502 foreach my $influence (keys %{$other->[1]}) {
2503 $this->[1]{$influence} |= $other->[1]{$influence};
2512 sub remove_influence {
2516 delete $this->[1]{$torm};
2519 package IkiWiki::ErrorReason;
2521 our @ISA = 'IkiWiki::FailReason';
2523 package IkiWiki::PageSpec;
2529 if ($path =~ m!^\.(/|$)!) {
2531 $from=~s#/?[^/]+$## if defined $from;
2533 $path="$from/$path" if defined $from && length $from;
2537 $path = "" unless defined $path;
2546 sub match_glob ($$;@) {
2551 $glob=derel($glob, $params{location});
2553 # Instead of converting the glob to a regex every time,
2554 # cache the compiled regex to save time.
2555 my $re=$glob_cache{$glob};
2556 unless (defined $re) {
2557 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2560 if (! IkiWiki::isinternal($page) || $params{internal}) {
2561 return IkiWiki::SuccessReason->new("$glob matches $page");
2564 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2568 return IkiWiki::FailReason->new("$glob does not match $page");
2572 sub match_internal ($$;@) {
2573 return match_glob(shift, shift, @_, internal => 1)
2576 sub match_page ($$;@) {
2578 my $match=match_glob($page, shift, @_);
2580 my $source=exists $IkiWiki::pagesources{$page} ?
2581 $IkiWiki::pagesources{$page} :
2582 $IkiWiki::delpagesources{$page};
2583 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2584 if (! defined $type) {
2585 return IkiWiki::FailReason->new("$page is not a page");
2591 sub match_link ($$;@) {
2596 $link=derel($link, $params{location});
2597 my $from=exists $params{location} ? $params{location} : '';
2598 my $linktype=$params{linktype};
2600 if (defined $linktype) {
2601 $qualifier=" with type $linktype";
2604 my $links = $IkiWiki::links{$page};
2605 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2606 unless $links && @{$links};
2607 my $bestlink = IkiWiki::bestlink($from, $link);
2608 foreach my $p (@{$links}) {
2609 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2611 if (length $bestlink) {
2612 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2613 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2617 if (match_glob($p, $link, %params)) {
2618 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2620 my ($p_rel)=$p=~/^\/?(.*)/;
2622 if (match_glob($p_rel, $link, %params)) {
2623 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2627 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2630 sub match_backlink ($$;@) {
2631 my $ret=match_link($_[1], $_[0], @_);
2632 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2636 sub match_created_before ($$;@) {
2641 $testpage=derel($testpage, $params{location});
2643 if (exists $IkiWiki::pagectime{$testpage}) {
2644 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2645 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2648 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2652 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2656 sub match_created_after ($$;@) {
2661 $testpage=derel($testpage, $params{location});
2663 if (exists $IkiWiki::pagectime{$testpage}) {
2664 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2665 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2668 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2672 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2676 sub match_creation_day ($$;@) {
2679 if ($d !~ /^\d+$/) {
2680 return IkiWiki::ErrorReason->new("invalid day $d");
2682 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2683 return IkiWiki::SuccessReason->new('creation_day matched');
2686 return IkiWiki::FailReason->new('creation_day did not match');
2690 sub match_creation_month ($$;@) {
2693 if ($m !~ /^\d+$/) {
2694 return IkiWiki::ErrorReason->new("invalid month $m");
2696 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2697 return IkiWiki::SuccessReason->new('creation_month matched');
2700 return IkiWiki::FailReason->new('creation_month did not match');
2704 sub match_creation_year ($$;@) {
2707 if ($y !~ /^\d+$/) {
2708 return IkiWiki::ErrorReason->new("invalid year $y");
2710 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2711 return IkiWiki::SuccessReason->new('creation_year matched');
2714 return IkiWiki::FailReason->new('creation_year did not match');
2718 sub match_user ($$;@) {
2723 my $regexp=IkiWiki::glob2re($user);
2725 if (! exists $params{user}) {
2726 return IkiWiki::ErrorReason->new("no user specified");
2729 if (defined $params{user} && $params{user}=~$regexp) {
2730 return IkiWiki::SuccessReason->new("user is $user");
2732 elsif (! defined $params{user}) {
2733 return IkiWiki::FailReason->new("not logged in");
2736 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2740 sub match_admin ($$;@) {
2745 if (! exists $params{user}) {
2746 return IkiWiki::ErrorReason->new("no user specified");
2749 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2750 return IkiWiki::SuccessReason->new("user is an admin");
2752 elsif (! defined $params{user}) {
2753 return IkiWiki::FailReason->new("not logged in");
2756 return IkiWiki::FailReason->new("user is not an admin");
2760 sub match_ip ($$;@) {
2765 if (! exists $params{ip}) {
2766 return IkiWiki::ErrorReason->new("no IP specified");
2769 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2770 return IkiWiki::SuccessReason->new("IP is $ip");
2773 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2777 package IkiWiki::SortSpec;
2779 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2780 # are easily available in this namespace, for cmp functions to use them.
2787 IkiWiki::pagetitle(IkiWiki::basename($a))
2789 IkiWiki::pagetitle(IkiWiki::basename($b))
2792 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2793 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }