8 use URI::Escape q{uri_escape_utf8};
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14 %pagestate %wikistate %renderedfiles %oldrenderedfiles
15 %pagesources %delpagesources %destsources %depends %depends_simple
16 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17 %oldtypedlinks %autofiles};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21 deptype add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime strftime_utf8 will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link add_autofile
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
40 memoize("sortspec_translate");
41 memoize("pagespec_translate");
42 memoize("template_file");
48 description => "name of the wiki",
55 example => 'me@example.com',
56 description => "contact email for wiki",
63 description => "users who are wiki admins",
70 description => "users who are banned from the wiki",
77 example => "$ENV{HOME}/wiki",
78 description => "where the source of the wiki is located",
85 example => "/var/www/wiki",
86 description => "where to build the wiki",
93 example => "http://example.com/wiki",
94 description => "base url to the wiki",
101 example => "http://example.com/wiki/ikiwiki.cgi",
102 description => "url to the ikiwiki.cgi",
109 example => "/var/www/wiki/ikiwiki.cgi",
110 description => "filename of cgi wrapper to generate",
117 description => "mode for cgi_wrapper (can safely be made suid)",
121 cgi_overload_delay => {
125 description => "number of seconds to delay CGI requests when overloaded",
132 description => "rcs backend to use",
133 safe => 0, # don't allow overriding
138 default => [qw{mdwn link inline meta htmlscrubber passwordauth
139 openid signinedit lockedit conditional
140 recentchanges parentlinks editpage}],
141 description => "plugins to enable by default",
148 description => "plugins to add to the default configuration",
155 description => "plugins to disable",
161 default => "$installdir/share/ikiwiki/templates",
162 description => "additional directory to search for template files",
169 default => "$installdir/share/ikiwiki/basewiki",
170 description => "base wiki source location",
177 default => "$installdir/share/ikiwiki",
178 description => "parent directory containing additional underlays",
185 description => "wrappers to generate",
192 description => "additional underlays to use",
199 description => "display verbose messages?",
206 description => "log to syslog?",
213 description => "create output files named page/index.html?",
214 safe => 0, # changing requires manual transition
217 prefix_directives => {
220 description => "use '!'-prefixed preprocessor directives?",
221 safe => 0, # changing requires manual transition
227 description => "use page/index.mdwn source files",
234 description => "enable Discussion pages?",
240 default => gettext("Discussion"),
241 description => "name of Discussion pages",
248 description => "generate HTML5?",
256 description => "only send cookies over SSL connections?",
264 description => "extension to use for new pages",
265 safe => 0, # not sanitized
271 description => "extension to use for html files",
272 safe => 0, # not sanitized
278 description => "strftime format string to display date",
286 example => "en_US.UTF-8",
287 description => "UTF-8 locale to use",
296 description => "put user pages below specified page",
303 description => "how many backlinks to show before hiding excess (0 to show all)",
310 description => "attempt to hardlink source files? (optimisation for large files)",
312 safe => 0, # paranoia
318 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
320 safe => 0, # paranoia
325 example => "ikiwiki",
326 description => "group for wrappers to run in",
328 safe => 0, # paranoia
334 example => "$ENV{HOME}/.ikiwiki/",
335 description => "extra library and plugin directory",
337 safe => 0, # directory
343 description => "environment variables",
344 safe => 0, # paranoia
350 example => "US/Eastern",
351 description => "time zone name",
358 example => '^\.htaccess$',
359 description => "regexp of normally excluded files to include",
367 example => '^(*\.private|Makefile)$',
368 description => "regexp of files that should be skipped",
373 wiki_file_prune_regexps => {
375 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
376 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
377 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
378 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
379 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
380 description => "regexps of source files to ignore",
386 description => "specifies the characters that are allowed in source filenames",
387 default => "-[:alnum:]+/.:_",
391 wiki_file_regexp => {
393 description => "regexp of legal source files",
397 web_commit_regexp => {
399 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
400 description => "regexp to parse web commits from logs",
407 description => "run as a cgi",
411 cgi_disable_uploads => {
414 description => "whether CGI should accept file uploads",
421 description => "run as a post-commit hook",
428 description => "running in rebuild mode",
435 description => "running in setup mode",
442 description => "running in clean mode",
449 description => "running in refresh mode",
456 description => "running in receive test mode",
460 wrapper_background_command => {
463 description => "background shell command to run",
469 description => "running in gettime mode",
476 description => "running in w3mmode",
483 description => "path to the .ikiwiki directory holding ikiwiki state",
490 description => "path to setup file",
497 description => "perl class to use to dump setup file",
501 allow_symlinks_before_srcdir => {
504 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
510 sub defaultconfig () {
513 foreach my $key (keys %s) {
514 push @ret, $key, $s{$key}->{default};
519 # URL to top of wiki as a path starting with /, valid from any wiki page or
520 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
522 # URL to CGI script, similar to $local_url
526 # locale stuff; avoid LC_ALL since it overrides everything
527 if (defined $ENV{LC_ALL}) {
528 $ENV{LANG} = $ENV{LC_ALL};
531 if (defined $config{locale}) {
532 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
533 $ENV{LANG}=$config{locale};
538 if (! defined $config{wiki_file_regexp}) {
539 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
542 if (ref $config{ENV} eq 'HASH') {
543 foreach my $val (keys %{$config{ENV}}) {
544 $ENV{$val}=$config{ENV}{$val};
547 if (defined $config{timezone} && length $config{timezone}) {
548 $ENV{TZ}=$config{timezone};
551 $config{timezone}=$ENV{TZ};
554 if ($config{w3mmode}) {
555 eval q{use Cwd q{abs_path}};
557 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
558 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
559 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
560 unless $config{cgiurl} =~ m!file:///!;
561 $config{url}="file://".$config{destdir};
564 if ($config{cgi} && ! length $config{url}) {
565 error(gettext("Must specify url to wiki with --url when using --cgi"));
568 if (defined $config{url} && length $config{url}) {
570 my $baseurl = URI->new($config{url});
572 $local_url = $baseurl->path . "/";
573 $local_cgiurl = undef;
575 if (length $config{cgiurl}) {
576 my $cgiurl = URI->new($config{cgiurl});
578 $local_cgiurl = $cgiurl->path;
580 if ($cgiurl->scheme ne $baseurl->scheme or
581 $cgiurl->authority ne $baseurl->authority) {
582 # too far apart, fall back to absolute URLs
583 $local_url = "$config{url}/";
584 $local_cgiurl = $config{cgiurl};
588 $local_url =~ s{//$}{/};
591 $local_cgiurl = $config{cgiurl};
594 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
595 unless exists $config{wikistatedir} && defined $config{wikistatedir};
597 if (defined $config{umask}) {
598 my $u = possibly_foolish_untaint($config{umask});
600 if ($u =~ m/^\d+$/) {
603 elsif ($u eq 'private') {
606 elsif ($u eq 'group') {
609 elsif ($u eq 'public') {
613 error(sprintf(gettext("unsupported umask setting %s"), $u));
617 run_hooks(checkconfig => sub { shift->() });
625 foreach my $dir (@INC, $config{libdir}) {
626 next unless defined $dir && length $dir;
627 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
628 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
632 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
633 next unless defined $dir && length $dir;
634 foreach my $file (glob("$dir/plugins/*")) {
635 $ret{basename($file)}=1 if -x $file;
643 if (defined $config{libdir} && length $config{libdir}) {
644 unshift @INC, possibly_foolish_untaint($config{libdir});
647 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
652 if (exists $hooks{rcs}) {
653 error(gettext("cannot use multiple rcs plugins"));
655 loadplugin($config{rcs});
657 if (! exists $hooks{rcs}) {
661 run_hooks(getopt => sub { shift->() });
662 if (grep /^-/, @ARGV) {
663 print STDERR "Unknown option (or missing parameter): $_\n"
664 foreach grep /^-/, @ARGV;
671 sub loadplugin ($;$) {
675 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
677 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
678 "$installdir/lib/ikiwiki") {
679 if (defined $dir && -x "$dir/plugins/$plugin") {
680 eval { require IkiWiki::Plugin::external };
683 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
685 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
686 $loaded_plugins{$plugin}=1;
691 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
694 error("Failed to load plugin $mod: $@");
696 $loaded_plugins{$plugin}=1;
703 log_message('err' => $message) if $config{syslog};
704 if (defined $cleaner) {
711 return unless $config{verbose};
712 return log_message(debug => @_);
716 sub log_message ($$) {
719 if ($config{syslog}) {
722 Sys::Syslog::setlogsock('unix');
723 Sys::Syslog::openlog('ikiwiki', '', 'user');
727 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
730 elsif (! $config{cgi}) {
734 return print STDERR "@_\n";
738 sub possibly_foolish_untaint ($) {
740 my ($untainted)=$tainted=~/(.*)/s;
760 return exists $pagesources{$page} &&
761 $pagesources{$page} =~ /\._([^.]+)$/;
767 if ($file =~ /\.([^.]+)$/) {
768 return $1 if exists $hooks{htmlize}{$1};
770 my $base=basename($file);
771 if (exists $hooks{htmlize}{$base} &&
772 $hooks{htmlize}{$base}{noextension}) {
783 if (exists $pagename_cache{$file}) {
784 return $pagename_cache{$file};
787 my $type=pagetype($file);
789 $page=~s/\Q.$type\E*$//
790 if defined $type && !$hooks{htmlize}{$type}{keepextension}
791 && !$hooks{htmlize}{$type}{noextension};
792 if ($config{indexpages} && $page=~/(.*)\/index$/) {
796 $pagename_cache{$file} = $page;
800 sub newpagefile ($$) {
804 if (! $config{indexpages} || $page eq 'index') {
805 return $page.".".$type;
808 return $page."/index.".$type;
812 sub targetpage ($$;$) {
817 if (defined $filename) {
818 return $page."/".$filename.".".$ext;
820 elsif (! $config{usedirs} || $page eq 'index') {
821 return $page.".".$ext;
824 return $page."/index.".$ext;
831 return targetpage($page, $config{htmlext});
838 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
839 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
840 return "$dir/$file", stat(_) if -e "$dir/$file";
842 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
847 return (srcfile_stat(@_))[0];
850 sub add_literal_underlay ($) {
853 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
854 unshift @{$config{underlaydirs}}, $dir;
858 sub add_underlay ($) {
862 $dir="$config{underlaydirbase}/$dir";
865 add_literal_underlay($dir);
866 # why does it return 1? we just don't know
870 sub readfile ($;$$) {
876 error("cannot read a symlink ($file)");
880 open (my $in, "<", $file) || error("failed to read $file: $!");
881 binmode($in) if ($binary);
882 return \*$in if $wantfd;
884 # check for invalid utf-8, and toss it back to avoid crashes
885 if (! utf8::valid($ret)) {
886 $ret=encode_utf8($ret);
888 close $in || error("failed to read $file: $!");
892 sub prep_writefile ($$) {
897 while (length $test) {
898 if (-l "$destdir/$test") {
899 error("cannot write to a symlink ($test)");
901 if (-f _ && $test ne $file) {
902 # Remove conflicting file.
903 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
904 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
906 unlink("$destdir/$test");
912 $test=dirname($test);
915 my $dir=dirname("$destdir/$file");
918 foreach my $s (split(m!/+!, $dir)) {
921 mkdir($d) || error("failed to create directory $d: $!");
929 sub writefile ($$$;$$) {
930 my $file=shift; # can include subdirs
931 my $destdir=shift; # directory to put file in
936 prep_writefile($file, $destdir);
938 my $newfile="$destdir/$file.ikiwiki-new";
940 error("cannot write to a symlink ($newfile)");
943 my $cleanup = sub { unlink($newfile) };
944 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
945 binmode($out) if ($binary);
947 $writer->(\*$out, $cleanup);
950 print $out $content or error("failed writing to $newfile: $!", $cleanup);
952 close $out || error("failed saving $newfile: $!", $cleanup);
953 rename($newfile, "$destdir/$file") ||
954 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
960 sub will_render ($$;$) {
965 # Important security check for independently created files.
966 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
967 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
968 my $from_other_page=0;
969 # Expensive, but rarely runs.
970 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
974 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
980 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
981 unless $from_other_page;
984 # If $dest exists as a directory, remove conflicting files in it
985 # rendered from other pages.
987 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
988 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
989 if (dirname($f) eq $dest) {
990 unlink("$config{destdir}/$f");
991 rmdir(dirname("$config{destdir}/$f"));
997 if (! $clear || $cleared{$page}) {
998 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1001 foreach my $old (@{$renderedfiles{$page}}) {
1002 delete $destsources{$old};
1004 $renderedfiles{$page}=[$dest];
1007 $destsources{$dest}=$page;
1017 if ($link=~s/^\/+//) {
1025 $l.="/" if length $l;
1028 if (exists $pagesources{$l}) {
1031 elsif (exists $pagecase{lc $l}) {
1032 return $pagecase{lc $l};
1034 } while $cwd=~s{/?[^/]+$}{};
1036 if (length $config{userdir}) {
1037 my $l = "$config{userdir}/".lc($link);
1038 if (exists $pagesources{$l}) {
1041 elsif (exists $pagecase{lc $l}) {
1042 return $pagecase{lc $l};
1046 #print STDERR "warning: page $page, broken link: $link\n";
1050 sub isinlinableimage ($) {
1053 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1056 sub pagetitle ($;$) {
1058 my $unescaped=shift;
1061 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1064 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1072 # support use w/o %config set
1073 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1074 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1080 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1081 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1088 my $cgiurl=$local_cgiurl;
1090 if (exists $params{cgiurl}) {
1091 $cgiurl=$params{cgiurl};
1092 delete $params{cgiurl};
1100 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1103 sub cgiurl_abs (@) {
1105 URI->new_abs(cgiurl(@_), $config{cgiurl});
1111 return $local_url if ! defined $page;
1113 $page=htmlpage($page);
1115 $page=~s/[^\/]+\//..\//g;
1123 return $url unless defined $urlbase && length $urlbase;
1126 URI->new_abs($url, $urlbase)->as_string;
1130 # Work around very innefficient behavior in File::Spec if abs2rel
1131 # is passed two relative paths. It's much faster if paths are
1132 # absolute! (Debian bug #376658; fixed in debian unstable now)
1137 my $ret=File::Spec->abs2rel($path, $base);
1138 $ret=~s/^// if defined $ret;
1142 sub displaytime ($;$$) {
1143 # Plugins can override this function to mark up the time to
1145 my $time=formattime($_[0], $_[1]);
1146 if ($config{html5}) {
1147 return '<time datetime="'.date_3339($_[0]).'"'.
1148 ($_[2] ? ' pubdate="pubdate"' : '').
1149 '>'.$time.'</time>';
1152 return '<span class="date">'.$time.'</span>';
1156 sub formattime ($;$) {
1157 # Plugins can override this function to format the time.
1160 if (! defined $format) {
1161 $format=$config{timeformat};
1164 return strftime_utf8($format, localtime($time));
1167 my $strftime_encoding;
1169 # strftime doesn't know about encodings, so make sure
1170 # its output is properly treated as utf8.
1171 # Note that this does not handle utf-8 in the format string.
1172 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1173 unless defined $strftime_encoding;
1175 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1176 : POSIX::strftime(@_);
1182 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1183 POSIX::setlocale(&POSIX::LC_TIME, "C");
1184 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1185 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1189 sub beautify_urlpath ($) {
1192 # Ensure url is not an empty link, and if necessary,
1193 # add ./ to avoid colon confusion.
1194 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1198 if ($config{usedirs}) {
1199 $url =~ s!/index.$config{htmlext}$!/!;
1214 if (! $destsources{$to}) {
1219 return $config{url}.beautify_urlpath("/".$to);
1222 if (! defined $from) {
1223 my $u = $local_url || '';
1225 return $u.beautify_urlpath("/".$to);
1228 my $link = abs2rel($to, dirname(htmlpage($from)));
1230 return beautify_urlpath($link);
1233 sub isselflink ($$) {
1234 # Plugins can override this function to support special types
1239 return $page eq $link;
1242 sub htmllink ($$$;@) {
1243 my $lpage=shift; # the page doing the linking
1244 my $page=shift; # the page that will contain the link (different for inline)
1251 if (! $opts{forcesubpage}) {
1252 $bestlink=bestlink($lpage, $link);
1255 $bestlink="$lpage/".lc($link);
1259 if (defined $opts{linktext}) {
1260 $linktext=$opts{linktext};
1263 $linktext=pagetitle(basename($link));
1266 return "<span class=\"selflink\">$linktext</span>"
1267 if length $bestlink && isselflink($page, $bestlink) &&
1268 ! defined $opts{anchor};
1270 if (! $destsources{$bestlink}) {
1271 $bestlink=htmlpage($bestlink);
1273 if (! $destsources{$bestlink}) {
1275 if (length $config{cgiurl}) {
1276 $cgilink = "<a href=\"".
1281 )."\" rel=\"nofollow\">?</a>";
1283 return "<span class=\"createlink\">$cgilink$linktext</span>"
1287 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1288 $bestlink=beautify_urlpath($bestlink);
1290 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1291 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1294 if (defined $opts{anchor}) {
1295 $bestlink.="#".$opts{anchor};
1299 foreach my $attr (qw{rel class title}) {
1300 if (defined $opts{$attr}) {
1301 push @attrs, " $attr=\"$opts{$attr}\"";
1305 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1310 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1313 sub openiduser ($) {
1316 if (defined $user && $user =~ m!^https?://! &&
1317 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1320 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1321 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1324 # backcompat with old version
1325 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1326 $display=$oid->display;
1329 # Convert "user.somehost.com" to "user [somehost.com]"
1330 # (also "user.somehost.co.uk")
1331 if ($display !~ /\[/) {
1332 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1334 # Convert "http://somehost.com/user" to "user [somehost.com]".
1335 # (also "https://somehost.com/user/")
1336 if ($display !~ /\[/) {
1337 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1339 $display=~s!^https?://!!; # make sure this is removed
1340 eval q{use CGI 'escapeHTML'};
1342 return escapeHTML($display);
1347 sub htmlize ($$$$) {
1353 my $oneline = $content !~ /\n/;
1355 if (exists $hooks{htmlize}{$type}) {
1356 $content=$hooks{htmlize}{$type}{call}->(
1358 content => $content,
1362 error("htmlization of $type not supported");
1365 run_hooks(sanitize => sub {
1368 destpage => $destpage,
1369 content => $content,
1374 # hack to get rid of enclosing junk added by markdown
1375 # and other htmlizers/sanitizers
1376 $content=~s/^<p>//i;
1377 $content=~s/<\/p>\n*$//i;
1388 run_hooks(linkify => sub {
1391 destpage => $destpage,
1392 content => $content,
1400 our $preprocess_preview=0;
1401 sub preprocess ($$$;$$) {
1402 my $page=shift; # the page the data comes from
1403 my $destpage=shift; # the page the data will appear in (different for inline)
1408 # Using local because it needs to be set within any nested calls
1410 local $preprocess_preview=$preview if defined $preview;
1417 $params="" if ! defined $params;
1419 if (length $escape) {
1420 return "[[$prefix$command $params]]";
1422 elsif (exists $hooks{preprocess}{$command}) {
1423 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1424 # Note: preserve order of params, some plugins may
1425 # consider it significant.
1427 while ($params =~ m{
1428 (?:([-\w]+)=)? # 1: named parameter key?
1430 """(.*?)""" # 2: triple-quoted value
1432 "([^"]*?)" # 3: single-quoted value
1434 '''(.*?)''' # 4: triple-single-quote
1436 <<([a-zA-Z]+)\n # 5: heredoc start
1437 (.*?)\n\5 # 6: heredoc value
1439 (\S+) # 7: unquoted value
1441 (?:\s+|$) # delimiter to next param
1451 elsif (defined $3) {
1454 elsif (defined $4) {
1457 elsif (defined $7) {
1460 elsif (defined $6) {
1465 push @params, $key, $val;
1468 push @params, $val, '';
1471 if ($preprocessing{$page}++ > 3) {
1472 # Avoid loops of preprocessed pages preprocessing
1473 # other pages that preprocess them, etc.
1474 return "[[!$command <span class=\"error\">".
1475 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1476 $page, $preprocessing{$page}).
1482 $hooks{preprocess}{$command}{call}->(
1485 destpage => $destpage,
1486 preview => $preprocess_preview,
1492 $ret="[[!$command <span class=\"error\">".
1493 gettext("Error").": $error"."</span>]]";
1497 # use void context during scan pass
1499 $hooks{preprocess}{$command}{call}->(
1502 destpage => $destpage,
1503 preview => $preprocess_preview,
1508 $preprocessing{$page}--;
1512 return "[[$prefix$command $params]]";
1517 if ($config{prefix_directives}) {
1520 \[\[(!) # directive open; 2: prefix
1521 ([-\w]+) # 3: command
1522 ( # 4: the parameters..
1523 \s+ # Must have space if parameters present
1525 (?:[-\w]+=)? # named parameter key?
1527 """.*?""" # triple-quoted value
1529 "[^"]*?" # single-quoted value
1531 '''.*?''' # triple-single-quote
1533 <<([a-zA-Z]+)\n # 5: heredoc start
1534 (?:.*?)\n\5 # heredoc value
1536 [^"\s\]]+ # unquoted value
1538 \s* # whitespace or end
1541 *)? # 0 or more parameters
1542 \]\] # directive closed
1548 \[\[(!?) # directive open; 2: optional prefix
1549 ([-\w]+) # 3: command
1551 ( # 4: the parameters..
1553 (?:[-\w]+=)? # named parameter key?
1555 """.*?""" # triple-quoted value
1557 "[^"]*?" # single-quoted value
1559 '''.*?''' # triple-single-quote
1561 <<([a-zA-Z]+)\n # 5: heredoc start
1562 (?:.*?)\n\5 # heredoc value
1564 [^"\s\]]+ # unquoted value
1566 \s* # whitespace or end
1569 *) # 0 or more parameters
1570 \]\] # directive closed
1574 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1583 run_hooks(filter => sub {
1584 $content=shift->(page => $page, destpage => $destpage,
1585 content => $content);
1591 sub check_canedit ($$$;$) {
1598 run_hooks(canedit => sub {
1599 return if defined $canedit;
1600 my $ret=shift->($page, $q, $session);
1605 elsif (ref $ret eq 'CODE') {
1606 $ret->() unless $nonfatal;
1609 elsif (defined $ret) {
1610 error($ret) unless $nonfatal;
1615 return defined $canedit ? $canedit : 1;
1618 sub check_content (@) {
1621 return 1 if ! exists $hooks{checkcontent}; # optimisation
1623 if (exists $pagesources{$params{page}}) {
1625 my %old=map { $_ => 1 }
1626 split("\n", readfile(srcfile($pagesources{$params{page}})));
1627 foreach my $line (split("\n", $params{content})) {
1628 push @diff, $line if ! exists $old{$line};
1630 $params{diff}=join("\n", @diff);
1634 run_hooks(checkcontent => sub {
1635 return if defined $ok;
1636 my $ret=shift->(%params);
1641 elsif (ref $ret eq 'CODE') {
1642 $ret->() unless $params{nonfatal};
1645 elsif (defined $ret) {
1646 error($ret) unless $params{nonfatal};
1652 return defined $ok ? $ok : 1;
1655 sub check_canchange (@) {
1657 my $cgi = $params{cgi};
1658 my $session = $params{session};
1659 my @changes = @{$params{changes}};
1662 foreach my $change (@changes) {
1663 # This untaint is safe because we check file_pruned and
1665 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1666 $file=possibly_foolish_untaint($file);
1667 if (! defined $file || ! length $file ||
1668 file_pruned($file)) {
1669 error(gettext("bad file name %s"), $file);
1672 my $type=pagetype($file);
1673 my $page=pagename($file) if defined $type;
1675 if ($change->{action} eq 'add') {
1679 if ($change->{action} eq 'change' ||
1680 $change->{action} eq 'add') {
1681 if (defined $page) {
1682 check_canedit($page, $cgi, $session);
1686 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1687 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1688 check_canedit($file, $cgi, $session);
1693 elsif ($change->{action} eq 'remove') {
1694 # check_canremove tests to see if the file is present
1695 # on disk. This will fail when a single commit adds a
1696 # file and then removes it again. Avoid the problem
1697 # by not testing the removal in such pairs of changes.
1698 # (The add is still tested, just to make sure that
1699 # no data is added to the repo that a web edit
1701 next if $newfiles{$file};
1703 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1704 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1705 check_canedit(defined $page ? $page : $file, $cgi, $session);
1710 error "unknown action ".$change->{action};
1713 error sprintf(gettext("you are not allowed to change %s"), $file);
1721 # Take an exclusive lock on the wiki to prevent multiple concurrent
1722 # run issues. The lock will be dropped on program exit.
1723 if (! -d $config{wikistatedir}) {
1724 mkdir($config{wikistatedir});
1726 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1727 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1728 if (! flock($wikilock, 2)) { # LOCK_EX
1729 error("failed to get lock");
1735 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1736 return close($wikilock) if $wikilock;
1742 sub commit_hook_enabled () {
1743 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1744 error("cannot write to $config{wikistatedir}/commitlock: $!");
1745 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1746 close($commitlock) || error("failed closing commitlock: $!");
1749 close($commitlock) || error("failed closing commitlock: $!");
1753 sub disable_commit_hook () {
1754 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1755 error("cannot write to $config{wikistatedir}/commitlock: $!");
1756 if (! flock($commitlock, 2)) { # LOCK_EX
1757 error("failed to get commit lock");
1762 sub enable_commit_hook () {
1763 return close($commitlock) if $commitlock;
1768 %oldrenderedfiles=%pagectime=();
1769 if (! $config{rebuild}) {
1770 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1771 %destsources=%renderedfiles=%pagecase=%pagestate=
1772 %depends_simple=%typedlinks=%oldtypedlinks=();
1775 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1776 if (-e "$config{wikistatedir}/index") {
1777 system("ikiwiki-transition", "indexdb", $config{srcdir});
1778 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1781 $config{gettime}=1; # first build
1786 my $index=Storable::fd_retrieve($in);
1787 if (! defined $index) {
1792 if (exists $index->{version} && ! ref $index->{version}) {
1793 $pages=$index->{page};
1794 %wikistate=%{$index->{state}};
1795 # Handle plugins that got disabled by loading a new setup.
1796 if (exists $config{setupfile}) {
1797 require IkiWiki::Setup;
1798 IkiWiki::Setup::disabled_plugins(
1799 grep { ! $loaded_plugins{$_} } keys %wikistate);
1807 foreach my $src (keys %$pages) {
1808 my $d=$pages->{$src};
1809 my $page=pagename($src);
1810 $pagectime{$page}=$d->{ctime};
1811 $pagesources{$page}=$src;
1812 if (! $config{rebuild}) {
1813 $pagemtime{$page}=$d->{mtime};
1814 $renderedfiles{$page}=$d->{dest};
1815 if (exists $d->{links} && ref $d->{links}) {
1816 $links{$page}=$d->{links};
1817 $oldlinks{$page}=[@{$d->{links}}];
1819 if (ref $d->{depends_simple} eq 'ARRAY') {
1821 $depends_simple{$page}={
1822 map { $_ => 1 } @{$d->{depends_simple}}
1825 elsif (exists $d->{depends_simple}) {
1826 $depends_simple{$page}=$d->{depends_simple};
1828 if (exists $d->{dependslist}) {
1831 map { $_ => $DEPEND_CONTENT }
1832 @{$d->{dependslist}}
1835 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1837 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1839 elsif (exists $d->{depends}) {
1840 $depends{$page}=$d->{depends};
1842 if (exists $d->{state}) {
1843 $pagestate{$page}=$d->{state};
1845 if (exists $d->{typedlinks}) {
1846 $typedlinks{$page}=$d->{typedlinks};
1848 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1849 next unless %$links;
1850 $oldtypedlinks{$page}{$type} = {%$links};
1854 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1856 foreach my $page (keys %pagesources) {
1857 $pagecase{lc $page}=$page;
1859 foreach my $page (keys %renderedfiles) {
1860 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1866 run_hooks(savestate => sub { shift->() });
1868 my @plugins=keys %loaded_plugins;
1870 if (! -d $config{wikistatedir}) {
1871 mkdir($config{wikistatedir});
1873 my $newfile="$config{wikistatedir}/indexdb.new";
1874 my $cleanup = sub { unlink($newfile) };
1875 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1878 foreach my $page (keys %pagemtime) {
1879 next unless $pagemtime{$page};
1880 my $src=$pagesources{$page};
1882 $index{page}{$src}={
1883 ctime => $pagectime{$page},
1884 mtime => $pagemtime{$page},
1885 dest => $renderedfiles{$page},
1886 links => $links{$page},
1889 if (exists $depends{$page}) {
1890 $index{page}{$src}{depends} = $depends{$page};
1893 if (exists $depends_simple{$page}) {
1894 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1897 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1898 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1901 if (exists $pagestate{$page}) {
1902 foreach my $id (@plugins) {
1903 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1904 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1911 foreach my $id (@plugins) {
1912 $index{state}{$id}={}; # used to detect disabled plugins
1913 foreach my $key (keys %{$wikistate{$id}}) {
1914 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1918 $index{version}="3";
1919 my $ret=Storable::nstore_fd(\%index, $out);
1920 return if ! defined $ret || ! $ret;
1921 close $out || error("failed saving to $newfile: $!", $cleanup);
1922 rename($newfile, "$config{wikistatedir}/indexdb") ||
1923 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1928 sub template_file ($) {
1931 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1933 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1934 $template=srcfile($pagesources{$tpage}, 1);
1938 $template=srcfile($tpage, 1);
1941 if (defined $template) {
1942 return $template, $tpage, 1 if wantarray;
1946 $name=~s:/::; # avoid path traversal
1947 foreach my $dir ($config{templatedir},
1948 "$installdir/share/ikiwiki/templates") {
1949 if (-e "$dir/$name") {
1950 $template="$dir/$name";
1954 if (defined $template) {
1955 return $template, $tpage if wantarray;
1963 sub template_depends ($$;@) {
1967 my ($filename, $tpage, $untrusted)=template_file($name);
1968 if (! defined $filename) {
1969 error(sprintf(gettext("template %s not found"), $name))
1972 if (defined $page && defined $tpage) {
1973 add_depends($page, $tpage);
1978 my $text_ref = shift;
1979 ${$text_ref} = decode_utf8(${$text_ref});
1981 loop_context_vars => 1,
1982 die_on_bad_params => 0,
1983 parent_global_vars => 1,
1984 filename => $filename,
1986 ($untrusted ? (no_includes => 1) : ()),
1988 return @opts if wantarray;
1990 require HTML::Template;
1991 return HTML::Template->new(@opts);
1994 sub template ($;@) {
1995 template_depends(shift, undef, @_);
1998 sub templateactions ($$) {
2004 run_hooks(pageactions => sub {
2005 push @actions, map { { action => $_ } }
2006 grep { defined } shift->(page => $page);
2008 $template->param(actions => \@actions);
2010 if ($config{cgiurl} && exists $hooks{auth}) {
2011 $template->param(prefsurl => cgiurl(do => "prefs"));
2015 if ($have_actions || @actions) {
2016 $template->param(have_actions => 1);
2023 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2024 error 'hook requires type, call, and id parameters';
2027 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2029 $hooks{$param{type}}{$param{id}}=\%param;
2033 sub run_hooks ($$) {
2034 # Calls the given sub for each hook of the given type,
2035 # passing it the hook function to call.
2039 if (exists $hooks{$type}) {
2040 my (@first, @middle, @last);
2041 foreach my $id (keys %{$hooks{$type}}) {
2042 if ($hooks{$type}{$id}{first}) {
2045 elsif ($hooks{$type}{$id}{last}) {
2052 foreach my $id (@first, @middle, @last) {
2053 $sub->($hooks{$type}{$id}{call});
2061 $hooks{rcs}{rcs_update}{call}->(@_);
2064 sub rcs_prepedit ($) {
2065 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2068 sub rcs_commit (@) {
2069 $hooks{rcs}{rcs_commit}{call}->(@_);
2072 sub rcs_commit_staged (@) {
2073 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2077 $hooks{rcs}{rcs_add}{call}->(@_);
2080 sub rcs_remove ($) {
2081 $hooks{rcs}{rcs_remove}{call}->(@_);
2084 sub rcs_rename ($$) {
2085 $hooks{rcs}{rcs_rename}{call}->(@_);
2088 sub rcs_recentchanges ($) {
2089 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2092 sub rcs_diff ($;$) {
2093 $hooks{rcs}{rcs_diff}{call}->(@_);
2096 sub rcs_getctime ($) {
2097 $hooks{rcs}{rcs_getctime}{call}->(@_);
2100 sub rcs_getmtime ($) {
2101 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2104 sub rcs_receive () {
2105 $hooks{rcs}{rcs_receive}{call}->();
2108 sub add_depends ($$;$) {
2111 my $deptype=shift || $DEPEND_CONTENT;
2113 # Is the pagespec a simple page name?
2114 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2115 $pagespec !~ /[\s*?()!]/) {
2116 $depends_simple{$page}{lc $pagespec} |= $deptype;
2120 # Add explicit dependencies for influences.
2121 my $sub=pagespec_translate($pagespec);
2122 return unless defined $sub;
2123 foreach my $p (keys %pagesources) {
2124 my $r=$sub->($p, location => $page);
2125 my $i=$r->influences;
2126 my $static=$r->influences_static;
2127 foreach my $k (keys %$i) {
2128 next unless $r || $static || $k eq $page;
2129 $depends_simple{$page}{lc $k} |= $i->{$k};
2134 $depends{$page}{$pagespec} |= $deptype;
2140 foreach my $type (@_) {
2141 if ($type eq 'presence') {
2142 $deptype |= $DEPEND_PRESENCE;
2144 elsif ($type eq 'links') {
2145 $deptype |= $DEPEND_LINKS;
2147 elsif ($type eq 'content') {
2148 $deptype |= $DEPEND_CONTENT;
2154 my $file_prune_regexp;
2155 sub file_pruned ($) {
2158 if (defined $config{include} && length $config{include}) {
2159 return 0 if $file =~ m/$config{include}/;
2162 if (! defined $file_prune_regexp) {
2163 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2164 $file_prune_regexp=qr/$file_prune_regexp/;
2166 return $file =~ m/$file_prune_regexp/;
2169 sub define_gettext () {
2170 # If translation is needed, redefine the gettext function to do it.
2171 # Otherwise, it becomes a quick no-op.
2174 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2175 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2176 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2178 $gettext_obj=eval q{
2179 use Locale::gettext q{textdomain};
2180 Locale::gettext->domain('ikiwiki')
2185 no warnings 'redefine';
2187 $getobj->() if $getobj;
2189 $gettext_obj->get(shift);
2196 $getobj->() if $getobj;
2198 $gettext_obj->nget(@_);
2201 return ($_[2] == 1 ? $_[0] : $_[1])
2219 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2223 # Injects a new function into the symbol table to replace an
2224 # exported function.
2227 # This is deep ugly perl foo, beware.
2230 if (! defined $params{parent}) {
2231 $params{parent}='::';
2232 $params{old}=\&{$params{name}};
2233 $params{name}=~s/.*:://;
2235 my $parent=$params{parent};
2236 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2237 $ns = $params{parent} . $ns;
2238 inject(%params, parent => $ns) unless $ns eq '::main::';
2239 *{$ns . $params{name}} = $params{call}
2240 if exists ${$ns}{$params{name}} &&
2241 \&{${$ns}{$params{name}}} == $params{old};
2247 sub add_link ($$;$) {
2252 push @{$links{$page}}, $link
2253 unless grep { $_ eq $link } @{$links{$page}};
2255 if (defined $type) {
2256 $typedlinks{$page}{$type}{$link} = 1;
2260 sub add_autofile ($$$) {
2263 my $generator=shift;
2265 $autofiles{$file}{plugin}=$plugin;
2266 $autofiles{$file}{generator}=$generator;
2269 sub sortspec_translate ($$) {
2271 my $reverse = shift;
2277 (-?) # group 1: perhaps negated
2280 \w+\([^\)]*\) # command(params)
2282 [^\s]+ # or anything else
2290 if ($word =~ m/^(\w+)\((.*)\)$/) {
2291 # command with parameters
2295 elsif ($word !~ m/^\w+$/) {
2296 error(sprintf(gettext("invalid sort type %s"), $word));
2307 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2308 if (defined $params) {
2309 push @data, $params;
2310 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2313 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2317 error(sprintf(gettext("unknown sort type %s"), $word));
2321 if (! length $code) {
2322 # undefined sorting method... sort arbitrarily
2331 return eval 'sub { '.$code.' }';
2334 sub pagespec_translate ($) {
2337 # Convert spec to perl code.
2341 \s* # ignore whitespace
2342 ( # 1: match a single word
2349 \w+\([^\)]*\) # command(params)
2351 [^\s()]+ # any other text
2353 \s* # ignore whitespace
2356 if (lc $word eq 'and') {
2359 elsif (lc $word eq 'or') {
2362 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2365 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2366 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2368 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2371 push @data, qq{unknown function in pagespec "$word"};
2372 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2377 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2381 if (! length $code) {
2382 $code="IkiWiki::FailReason->new('empty pagespec')";
2386 return eval 'sub { my $page=shift; '.$code.' }';
2389 sub pagespec_match ($$;@) {
2394 # Backwards compatability with old calling convention.
2396 unshift @params, 'location';
2399 my $sub=pagespec_translate($spec);
2400 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2402 return $sub->($page, @params);
2405 sub pagespec_match_list ($$;@) {
2410 # Backwards compatability with old calling convention.
2412 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2413 $params{list}=$page;
2414 $page=$params{location}; # ugh!
2417 my $sub=pagespec_translate($pagespec);
2418 error "syntax error in pagespec \"$pagespec\""
2420 my $sort=sortspec_translate($params{sort}, $params{reverse})
2421 if defined $params{sort};
2424 if (exists $params{list}) {
2425 @candidates=exists $params{filter}
2426 ? grep { ! $params{filter}->($_) } @{$params{list}}
2430 @candidates=exists $params{filter}
2431 ? grep { ! $params{filter}->($_) } keys %pagesources
2432 : keys %pagesources;
2435 # clear params, remainder is passed to pagespec
2436 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2437 my $num=$params{num};
2438 delete @params{qw{num deptype reverse sort filter list}};
2440 # when only the top matches will be returned, it's efficient to
2441 # sort before matching to pagespec,
2442 if (defined $num && defined $sort) {
2443 @candidates=IkiWiki::SortSpec::sort_pages(
2444 $sort, @candidates);
2450 my $accum=IkiWiki::SuccessReason->new();
2451 foreach my $p (@candidates) {
2452 my $r=$sub->($p, %params, location => $page);
2453 error(sprintf(gettext("cannot match pages: %s"), $r))
2454 if $r->isa("IkiWiki::ErrorReason");
2455 unless ($r || $r->influences_static) {
2456 $r->remove_influence($p);
2461 last if defined $num && ++$count == $num;
2465 # Add simple dependencies for accumulated influences.
2466 my $i=$accum->influences;
2467 foreach my $k (keys %$i) {
2468 $depends_simple{$page}{lc $k} |= $i->{$k};
2471 # when all matches will be returned, it's efficient to
2472 # sort after matching
2473 if (! defined $num && defined $sort) {
2474 return IkiWiki::SortSpec::sort_pages(
2482 sub pagespec_valid ($) {
2485 return defined pagespec_translate($spec);
2489 my $re=quotemeta(shift);
2495 package IkiWiki::FailReason;
2498 '""' => sub { $_[0][0] },
2500 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2501 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2502 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2506 our @ISA = 'IkiWiki::SuccessReason';
2508 package IkiWiki::SuccessReason;
2511 '""' => sub { $_[0][0] },
2513 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2514 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2515 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2522 return bless [$value, {@_}], $class;
2527 $this->[1]={@_} if @_;
2528 my %i=%{$this->[1]};
2533 sub influences_static {
2534 return ! $_[0][1]->{""};
2537 sub merge_influences {
2542 if (! $anded || (($this || %{$this->[1]}) &&
2543 ($other || %{$other->[1]}))) {
2544 foreach my $influence (keys %{$other->[1]}) {
2545 $this->[1]{$influence} |= $other->[1]{$influence};
2554 sub remove_influence {
2558 delete $this->[1]{$torm};
2561 package IkiWiki::ErrorReason;
2563 our @ISA = 'IkiWiki::FailReason';
2565 package IkiWiki::PageSpec;
2571 if ($path =~ m!^\.(/|$)!) {
2573 $from=~s#/?[^/]+$## if defined $from;
2575 $path="$from/$path" if defined $from && length $from;
2579 $path = "" unless defined $path;
2588 sub match_glob ($$;@) {
2593 $glob=derel($glob, $params{location});
2595 # Instead of converting the glob to a regex every time,
2596 # cache the compiled regex to save time.
2597 my $re=$glob_cache{$glob};
2598 unless (defined $re) {
2599 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2602 if (! IkiWiki::isinternal($page) || $params{internal}) {
2603 return IkiWiki::SuccessReason->new("$glob matches $page");
2606 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2610 return IkiWiki::FailReason->new("$glob does not match $page");
2614 sub match_internal ($$;@) {
2615 return match_glob(shift, shift, @_, internal => 1)
2618 sub match_page ($$;@) {
2620 my $match=match_glob($page, shift, @_);
2622 my $source=exists $IkiWiki::pagesources{$page} ?
2623 $IkiWiki::pagesources{$page} :
2624 $IkiWiki::delpagesources{$page};
2625 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2626 if (! defined $type) {
2627 return IkiWiki::FailReason->new("$page is not a page");
2633 sub match_link ($$;@) {
2638 $link=derel($link, $params{location});
2639 my $from=exists $params{location} ? $params{location} : '';
2640 my $linktype=$params{linktype};
2642 if (defined $linktype) {
2643 $qualifier=" with type $linktype";
2646 my $links = $IkiWiki::links{$page};
2647 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2648 unless $links && @{$links};
2649 my $bestlink = IkiWiki::bestlink($from, $link);
2650 foreach my $p (@{$links}) {
2651 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2653 if (length $bestlink) {
2654 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2655 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2659 if (match_glob($p, $link, %params)) {
2660 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2662 my ($p_rel)=$p=~/^\/?(.*)/;
2664 if (match_glob($p_rel, $link, %params)) {
2665 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2669 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2672 sub match_backlink ($$;@) {
2676 if ($testpage eq '.') {
2677 $testpage = $params{'location'}
2679 my $ret=match_link($testpage, $page, @_);
2680 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2684 sub match_created_before ($$;@) {
2689 $testpage=derel($testpage, $params{location});
2691 if (exists $IkiWiki::pagectime{$testpage}) {
2692 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2693 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2696 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2700 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2704 sub match_created_after ($$;@) {
2709 $testpage=derel($testpage, $params{location});
2711 if (exists $IkiWiki::pagectime{$testpage}) {
2712 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2713 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2716 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2720 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2724 sub match_creation_day ($$;@) {
2727 if ($d !~ /^\d+$/) {
2728 return IkiWiki::ErrorReason->new("invalid day $d");
2730 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2731 return IkiWiki::SuccessReason->new('creation_day matched');
2734 return IkiWiki::FailReason->new('creation_day did not match');
2738 sub match_creation_month ($$;@) {
2741 if ($m !~ /^\d+$/) {
2742 return IkiWiki::ErrorReason->new("invalid month $m");
2744 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2745 return IkiWiki::SuccessReason->new('creation_month matched');
2748 return IkiWiki::FailReason->new('creation_month did not match');
2752 sub match_creation_year ($$;@) {
2755 if ($y !~ /^\d+$/) {
2756 return IkiWiki::ErrorReason->new("invalid year $y");
2758 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2759 return IkiWiki::SuccessReason->new('creation_year matched');
2762 return IkiWiki::FailReason->new('creation_year did not match');
2766 sub match_user ($$;@) {
2771 my $regexp=IkiWiki::glob2re($user);
2773 if (! exists $params{user}) {
2774 return IkiWiki::ErrorReason->new("no user specified");
2777 if (defined $params{user} && $params{user}=~$regexp) {
2778 return IkiWiki::SuccessReason->new("user is $user");
2780 elsif (! defined $params{user}) {
2781 return IkiWiki::FailReason->new("not logged in");
2784 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2788 sub match_admin ($$;@) {
2793 if (! exists $params{user}) {
2794 return IkiWiki::ErrorReason->new("no user specified");
2797 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2798 return IkiWiki::SuccessReason->new("user is an admin");
2800 elsif (! defined $params{user}) {
2801 return IkiWiki::FailReason->new("not logged in");
2804 return IkiWiki::FailReason->new("user is not an admin");
2808 sub match_ip ($$;@) {
2813 if (! exists $params{ip}) {
2814 return IkiWiki::ErrorReason->new("no IP specified");
2817 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2818 return IkiWiki::SuccessReason->new("IP is $ip");
2821 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2825 package IkiWiki::SortSpec;
2827 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2828 # are easily available in this namespace, for cmp functions to use them.
2835 IkiWiki::pagetitle(IkiWiki::basename($a))
2837 IkiWiki::pagetitle(IkiWiki::basename($b))
2840 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2841 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2842 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }