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 @underlayfiles $lastrev $phase};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21 deptype add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime strftime_utf8 will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link add_autofile useragent
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
37 # Phases of processing.
38 sub PHASE_SCAN () { 0 }
39 sub PHASE_RENDER () { 1 }
45 memoize("sortspec_translate");
46 memoize("pagespec_translate");
47 memoize("template_file");
53 description => "name of the wiki",
60 example => 'me@example.com',
61 description => "contact email for wiki",
68 description => "users who are wiki admins",
75 description => "users who are banned from the wiki",
82 example => "$ENV{HOME}/wiki",
83 description => "where the source of the wiki is located",
90 example => "/var/www/wiki",
91 description => "where to build the wiki",
98 example => "http://example.com/wiki",
99 description => "base url to the wiki",
106 example => "http://example.com/wiki/ikiwiki.cgi",
107 description => "url to the ikiwiki.cgi",
114 example => "/var/www/wiki/ikiwiki.cgi",
115 description => "filename of cgi wrapper to generate",
122 description => "mode for cgi_wrapper (can safely be made suid)",
126 cgi_overload_delay => {
130 description => "number of seconds to delay CGI requests when overloaded",
134 cgi_overload_message => {
137 example => "Please wait",
138 description => "message to display when overloaded (may contain html)",
142 only_committed_changes => {
145 description => "enable optimization of only refreshing committed changes?",
152 description => "rcs backend to use",
153 safe => 0, # don't allow overriding
158 default => [qw{mdwn link inline meta htmlscrubber passwordauth
159 openid signinedit lockedit conditional
160 recentchanges parentlinks editpage
162 description => "plugins to enable by default",
169 description => "plugins to add to the default configuration",
176 description => "plugins to disable",
182 default => "$installdir/share/ikiwiki/templates",
183 description => "additional directory to search for template files",
190 default => "$installdir/share/ikiwiki/basewiki",
191 description => "base wiki source location",
198 default => "$installdir/share/ikiwiki",
199 description => "parent directory containing additional underlays",
206 description => "wrappers to generate",
213 description => "additional underlays to use",
220 description => "display verbose messages?",
227 description => "log to syslog?",
234 description => "create output files named page/index.html?",
235 safe => 0, # changing requires manual transition
238 prefix_directives => {
241 description => "use '!'-prefixed preprocessor directives?",
242 safe => 0, # changing requires manual transition
248 description => "use page/index.mdwn source files",
255 description => "enable Discussion pages?",
261 default => gettext("Discussion"),
262 description => "name of Discussion pages",
269 description => "generate HTML5?",
277 description => "only send cookies over SSL connections?",
285 description => "extension to use for new pages",
286 safe => 0, # not sanitized
292 description => "extension to use for html files",
293 safe => 0, # not sanitized
299 description => "strftime format string to display date",
307 example => "en_US.UTF-8",
308 description => "UTF-8 locale to use",
317 description => "put user pages below specified page",
324 description => "how many backlinks to show before hiding excess (0 to show all)",
331 description => "attempt to hardlink source files? (optimisation for large files)",
333 safe => 0, # paranoia
339 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
341 safe => 0, # paranoia
346 example => "ikiwiki",
347 description => "group for wrappers to run in",
349 safe => 0, # paranoia
355 example => "$ENV{HOME}/.ikiwiki/",
356 description => "extra library and plugin directory",
358 safe => 0, # directory
364 description => "environment variables",
365 safe => 0, # paranoia
371 example => "US/Eastern",
372 description => "time zone name",
379 example => '^\.htaccess$',
380 description => "regexp of normally excluded files to include",
388 example => '^(*\.private|Makefile)$',
389 description => "regexp of files that should be skipped",
394 wiki_file_prune_regexps => {
396 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
397 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
398 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
399 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
400 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
401 description => "regexps of source files to ignore",
407 description => "specifies the characters that are allowed in source filenames",
408 default => "-[:alnum:]+/.:_",
412 wiki_file_regexp => {
414 description => "regexp of legal source files",
418 web_commit_regexp => {
420 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
421 description => "regexp to parse web commits from logs",
428 description => "run as a cgi",
432 cgi_disable_uploads => {
435 description => "whether CGI should accept file uploads",
442 description => "run as a post-commit hook",
449 description => "running in rebuild mode",
456 description => "running in setup mode",
463 description => "running in clean mode",
470 description => "running in refresh mode",
477 description => "running in receive test mode",
481 wrapper_background_command => {
484 description => "background shell command to run",
490 description => "running in gettime mode",
497 description => "running in w3mmode",
504 description => "path to the .ikiwiki directory holding ikiwiki state",
511 description => "path to setup file",
518 description => "perl class to use to dump setup file",
522 allow_symlinks_before_srcdir => {
525 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
531 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
532 description => "cookie control",
533 safe => 0, # hooks into perl module internals
539 example => "Wget/1.13.4 (linux-gnu)",
540 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
546 sub defaultconfig () {
549 foreach my $key (keys %s) {
550 push @ret, $key, $s{$key}->{default};
555 # URL to top of wiki as a path starting with /, valid from any wiki page or
556 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
558 # URL to CGI script, similar to $local_url
562 # locale stuff; avoid LC_ALL since it overrides everything
563 if (defined $ENV{LC_ALL}) {
564 $ENV{LANG} = $ENV{LC_ALL};
567 if (defined $config{locale}) {
568 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
569 $ENV{LANG}=$config{locale};
574 if (! defined $config{wiki_file_regexp}) {
575 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
578 if (ref $config{ENV} eq 'HASH') {
579 foreach my $val (keys %{$config{ENV}}) {
580 $ENV{$val}=$config{ENV}{$val};
583 if (defined $config{timezone} && length $config{timezone}) {
584 $ENV{TZ}=$config{timezone};
587 $config{timezone}=$ENV{TZ};
590 if ($config{w3mmode}) {
591 eval q{use Cwd q{abs_path}};
593 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
594 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
595 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
596 unless $config{cgiurl} =~ m!file:///!;
597 $config{url}="file://".$config{destdir};
600 if ($config{cgi} && ! length $config{url}) {
601 error(gettext("Must specify url to wiki with --url when using --cgi"));
604 if (defined $config{url} && length $config{url}) {
606 my $baseurl = URI->new($config{url});
608 $local_url = $baseurl->path . "/";
609 $local_cgiurl = undef;
611 if (length $config{cgiurl}) {
612 my $cgiurl = URI->new($config{cgiurl});
614 $local_cgiurl = $cgiurl->path;
616 if ($cgiurl->scheme ne $baseurl->scheme) {
617 # too far apart, fall back to absolute URLs
618 $local_url = "$config{url}/";
619 $local_cgiurl = $config{cgiurl};
621 elsif ($cgiurl->authority ne $baseurl->authority) {
622 # slightly too far apart, fall back to
623 # protocol-relative URLs
624 $local_url = "$config{url}/";
625 $local_url =~ s{^https?://}{//};
626 $local_cgiurl = $config{cgiurl};
627 $local_cgiurl =~ s{^https?://}{//};
631 $local_url =~ s{//$}{/};
634 $local_cgiurl = $config{cgiurl};
637 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
638 unless exists $config{wikistatedir} && defined $config{wikistatedir};
640 if (defined $config{umask}) {
641 my $u = possibly_foolish_untaint($config{umask});
643 if ($u =~ m/^\d+$/) {
646 elsif ($u eq 'private') {
649 elsif ($u eq 'group') {
652 elsif ($u eq 'public') {
656 error(sprintf(gettext("unsupported umask setting %s"), $u));
660 run_hooks(checkconfig => sub { shift->() });
668 foreach my $dir (@INC, $config{libdir}) {
669 next unless defined $dir && length $dir;
670 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
671 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
675 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
676 next unless defined $dir && length $dir;
677 foreach my $file (glob("$dir/plugins/*")) {
678 $ret{basename($file)}=1 if -x $file;
686 if (defined $config{libdir} && length $config{libdir}) {
687 unshift @INC, possibly_foolish_untaint($config{libdir});
690 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
695 if (exists $hooks{rcs}) {
696 error(gettext("cannot use multiple rcs plugins"));
698 loadplugin($config{rcs});
700 if (! exists $hooks{rcs}) {
704 run_hooks(getopt => sub { shift->() });
705 if (grep /^-/, @ARGV) {
706 print STDERR "Unknown option (or missing parameter): $_\n"
707 foreach grep /^-/, @ARGV;
714 sub loadplugin ($;$) {
718 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
720 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
721 "$installdir/lib/ikiwiki") {
722 if (defined $dir && -x "$dir/plugins/$plugin") {
723 eval { require IkiWiki::Plugin::external };
726 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
728 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
729 $loaded_plugins{$plugin}=1;
734 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
737 error("Failed to load plugin $mod: $@");
739 $loaded_plugins{$plugin}=1;
746 log_message('err' => $message) if $config{syslog};
747 if (defined $cleaner) {
754 return unless $config{verbose};
755 return log_message(debug => @_);
760 sub log_message ($$) {
763 if ($config{syslog}) {
766 Sys::Syslog::setlogsock('unix');
767 Sys::Syslog::openlog('ikiwiki', '', 'user');
771 # keep a copy to avoid editing the original config repeatedly
772 my $wikiname = $config{wikiname};
773 utf8::encode($wikiname);
774 Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
777 print STDERR "failed to syslog: $@" unless $log_failed;
783 elsif (! $config{cgi}) {
787 return print STDERR "@_\n";
791 sub possibly_foolish_untaint ($) {
793 my ($untainted)=$tainted=~/(.*)/s;
813 return exists $pagesources{$page} &&
814 $pagesources{$page} =~ /\._([^.]+)$/;
820 if ($file =~ /\.([^.]+)$/) {
821 return $1 if exists $hooks{htmlize}{$1};
823 my $base=basename($file);
824 if (exists $hooks{htmlize}{$base} &&
825 $hooks{htmlize}{$base}{noextension}) {
836 if (exists $pagename_cache{$file}) {
837 return $pagename_cache{$file};
840 my $type=pagetype($file);
842 $page=~s/\Q.$type\E*$//
843 if defined $type && !$hooks{htmlize}{$type}{keepextension}
844 && !$hooks{htmlize}{$type}{noextension};
845 if ($config{indexpages} && $page=~/(.*)\/index$/) {
849 $pagename_cache{$file} = $page;
853 sub newpagefile ($$) {
857 if (! $config{indexpages} || $page eq 'index') {
858 return $page.".".$type;
861 return $page."/index.".$type;
865 sub targetpage ($$;$) {
870 if (defined $filename) {
871 return $page."/".$filename.".".$ext;
873 elsif (! $config{usedirs} || $page eq 'index') {
874 return $page.".".$ext;
877 return $page."/index.".$ext;
884 return targetpage($page, $config{htmlext});
891 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
892 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
893 return "$dir/$file", stat(_) if -e "$dir/$file";
895 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
900 return (srcfile_stat(@_))[0];
903 sub add_literal_underlay ($) {
906 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
907 unshift @{$config{underlaydirs}}, $dir;
911 sub add_underlay ($) {
915 $dir="$config{underlaydirbase}/$dir";
918 add_literal_underlay($dir);
919 # why does it return 1? we just don't know
923 sub readfile ($;$$) {
929 error("cannot read a symlink ($file)");
933 open (my $in, "<", $file) || error("failed to read $file: $!");
934 binmode($in) if ($binary);
935 return \*$in if $wantfd;
937 # check for invalid utf-8, and toss it back to avoid crashes
938 if (! utf8::valid($ret)) {
939 $ret=encode_utf8($ret);
941 close $in || error("failed to read $file: $!");
945 sub prep_writefile ($$) {
950 while (length $test) {
951 if (-l "$destdir/$test") {
952 error("cannot write to a symlink ($test)");
954 if (-f _ && $test ne $file) {
955 # Remove conflicting file.
956 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
957 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
959 unlink("$destdir/$test");
965 $test=dirname($test);
968 my $dir=dirname("$destdir/$file");
971 foreach my $s (split(m!/+!, $dir)) {
974 mkdir($d) || error("failed to create directory $d: $!");
982 sub writefile ($$$;$$) {
983 my $file=shift; # can include subdirs
984 my $destdir=shift; # directory to put file in
989 prep_writefile($file, $destdir);
991 my $newfile="$destdir/$file.ikiwiki-new";
993 error("cannot write to a symlink ($newfile)");
996 my $cleanup = sub { unlink($newfile) };
997 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
998 binmode($out) if ($binary);
1000 $writer->(\*$out, $cleanup);
1003 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1005 close $out || error("failed saving $newfile: $!", $cleanup);
1006 rename($newfile, "$destdir/$file") ||
1007 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1013 sub will_render ($$;$) {
1018 # Important security check for independently created files.
1019 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1020 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1021 my $from_other_page=0;
1022 # Expensive, but rarely runs.
1023 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1026 dirname($_) eq $dest
1027 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1033 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1034 unless $from_other_page;
1037 # If $dest exists as a directory, remove conflicting files in it
1038 # rendered from other pages.
1040 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1041 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1042 if (dirname($f) eq $dest) {
1043 unlink("$config{destdir}/$f");
1044 rmdir(dirname("$config{destdir}/$f"));
1050 if (! $clear || $cleared{$page}) {
1051 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1054 foreach my $old (@{$renderedfiles{$page}}) {
1055 delete $destsources{$old};
1057 $renderedfiles{$page}=[$dest];
1060 $destsources{$dest}=$page;
1070 if ($link=~s/^\/+//) {
1078 $l.="/" if length $l;
1081 if (exists $pagesources{$l}) {
1084 elsif (exists $pagecase{lc $l}) {
1085 return $pagecase{lc $l};
1087 } while $cwd=~s{/?[^/]+$}{};
1089 if (length $config{userdir}) {
1090 my $l = "$config{userdir}/".lc($link);
1091 if (exists $pagesources{$l}) {
1094 elsif (exists $pagecase{lc $l}) {
1095 return $pagecase{lc $l};
1099 #print STDERR "warning: page $page, broken link: $link\n";
1103 sub isinlinableimage ($) {
1106 return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1109 sub pagetitle ($;$) {
1111 my $unescaped=shift;
1114 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1117 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1125 # support use w/o %config set
1126 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1127 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1133 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1134 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1141 my $cgiurl=$local_cgiurl;
1143 if (exists $params{cgiurl}) {
1144 $cgiurl=$params{cgiurl};
1145 delete $params{cgiurl};
1153 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1156 sub cgiurl_abs (@) {
1158 URI->new_abs(cgiurl(@_), $config{cgiurl});
1164 return $local_url if ! defined $page;
1166 $page=htmlpage($page);
1168 $page=~s/[^\/]+\//..\//g;
1176 return $url unless defined $urlbase && length $urlbase;
1179 URI->new_abs($url, $urlbase)->as_string;
1183 # Work around very innefficient behavior in File::Spec if abs2rel
1184 # is passed two relative paths. It's much faster if paths are
1185 # absolute! (Debian bug #376658; fixed in debian unstable now)
1190 my $ret=File::Spec->abs2rel($path, $base);
1191 $ret=~s/^// if defined $ret;
1195 sub displaytime ($;$$) {
1196 # Plugins can override this function to mark up the time to
1198 my $time=formattime($_[0], $_[1]);
1199 if ($config{html5}) {
1200 return '<time datetime="'.date_3339($_[0]).'"'.
1201 ($_[2] ? ' pubdate="pubdate"' : '').
1202 '>'.$time.'</time>';
1205 return '<span class="date">'.$time.'</span>';
1209 sub formattime ($;$) {
1210 # Plugins can override this function to format the time.
1213 if (! defined $format) {
1214 $format=$config{timeformat};
1217 return strftime_utf8($format, localtime($time));
1220 my $strftime_encoding;
1222 # strftime doesn't know about encodings, so make sure
1223 # its output is properly treated as utf8.
1224 # Note that this does not handle utf-8 in the format string.
1225 ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1226 unless defined $strftime_encoding;
1228 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1229 : POSIX::strftime(@_);
1235 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1236 POSIX::setlocale(&POSIX::LC_TIME, "C");
1237 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1238 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1242 sub beautify_urlpath ($) {
1245 # Ensure url is not an empty link, and if necessary,
1246 # add ./ to avoid colon confusion.
1247 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1251 if ($config{usedirs}) {
1252 $url =~ s!/index.$config{htmlext}$!/!;
1267 if (! $destsources{$to}) {
1272 return $config{url}.beautify_urlpath("/".$to);
1275 if (! defined $from) {
1276 my $u = $local_url || '';
1278 return $u.beautify_urlpath("/".$to);
1281 my $link = abs2rel($to, dirname(htmlpage($from)));
1283 return beautify_urlpath($link);
1286 sub isselflink ($$) {
1287 # Plugins can override this function to support special types
1292 return $page eq $link;
1295 sub htmllink ($$$;@) {
1296 my $lpage=shift; # the page doing the linking
1297 my $page=shift; # the page that will contain the link (different for inline)
1304 if (! $opts{forcesubpage}) {
1305 $bestlink=bestlink($lpage, $link);
1308 $bestlink="$lpage/".lc($link);
1312 if (defined $opts{linktext}) {
1313 $linktext=$opts{linktext};
1316 $linktext=pagetitle(basename($link));
1319 return "<span class=\"selflink\">$linktext</span>"
1320 if length $bestlink && isselflink($page, $bestlink) &&
1321 ! defined $opts{anchor};
1323 if (! $destsources{$bestlink}) {
1324 $bestlink=htmlpage($bestlink);
1326 if (! $destsources{$bestlink}) {
1328 if (length $config{cgiurl}) {
1329 $cgilink = "<a href=\"".
1334 )."\" rel=\"nofollow\">?</a>";
1336 return "<span class=\"createlink\">$cgilink$linktext</span>"
1340 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1341 $bestlink=beautify_urlpath($bestlink);
1343 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1344 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1347 if (defined $opts{anchor}) {
1348 $bestlink.="#".$opts{anchor};
1352 foreach my $attr (qw{rel class title}) {
1353 if (defined $opts{$attr}) {
1354 push @attrs, " $attr=\"$opts{$attr}\"";
1358 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1363 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1366 sub openiduser ($) {
1369 if (defined $user && $user =~ m!^https?://! &&
1370 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1373 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1374 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1377 # backcompat with old version
1378 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1379 $display=$oid->display;
1382 # Convert "user.somehost.com" to "user [somehost.com]"
1383 # (also "user.somehost.co.uk")
1384 if ($display !~ /\[/) {
1385 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1387 # Convert "http://somehost.com/user" to "user [somehost.com]".
1388 # (also "https://somehost.com/user/")
1389 if ($display !~ /\[/) {
1390 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1392 $display=~s!^https?://!!; # make sure this is removed
1393 eval q{use CGI 'escapeHTML'};
1395 return escapeHTML($display);
1400 sub htmlize ($$$$) {
1406 my $oneline = $content !~ /\n/;
1408 if (exists $hooks{htmlize}{$type}) {
1409 $content=$hooks{htmlize}{$type}{call}->(
1411 content => $content,
1415 error("htmlization of $type not supported");
1418 run_hooks(sanitize => sub {
1421 destpage => $destpage,
1422 content => $content,
1427 # hack to get rid of enclosing junk added by markdown
1428 # and other htmlizers/sanitizers
1429 $content=~s/^<p>//i;
1430 $content=~s/<\/p>\n*$//i;
1441 run_hooks(linkify => sub {
1444 destpage => $destpage,
1445 content => $content,
1453 our $preprocess_preview=0;
1454 sub preprocess ($$$;$$) {
1455 my $page=shift; # the page the data comes from
1456 my $destpage=shift; # the page the data will appear in (different for inline)
1461 # Using local because it needs to be set within any nested calls
1463 local $preprocess_preview=$preview if defined $preview;
1470 $params="" if ! defined $params;
1472 if (length $escape) {
1473 return "[[$prefix$command $params]]";
1475 elsif (exists $hooks{preprocess}{$command}) {
1476 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1477 # Note: preserve order of params, some plugins may
1478 # consider it significant.
1480 while ($params =~ m{
1481 (?:([-.\w]+)=)? # 1: named parameter key?
1483 """(.*?)""" # 2: triple-quoted value
1485 "([^"]*?)" # 3: single-quoted value
1487 '''(.*?)''' # 4: triple-single-quote
1489 <<([a-zA-Z]+)\n # 5: heredoc start
1490 (.*?)\n\5 # 6: heredoc value
1492 (\S+) # 7: unquoted value
1494 (?:\s+|$) # delimiter to next param
1504 elsif (defined $3) {
1507 elsif (defined $4) {
1510 elsif (defined $7) {
1513 elsif (defined $6) {
1518 push @params, $key, $val;
1521 push @params, $val, '';
1524 if ($preprocessing{$page}++ > 8) {
1525 # Avoid loops of preprocessed pages preprocessing
1526 # other pages that preprocess them, etc.
1527 return "[[!$command <span class=\"error\">".
1528 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1529 $page, $preprocessing{$page}).
1535 $hooks{preprocess}{$command}{call}->(
1538 destpage => $destpage,
1539 preview => $preprocess_preview,
1545 $ret="[[!$command <span class=\"error\">".
1546 gettext("Error").": $error"."</span>]]";
1550 # use void context during scan pass
1552 $hooks{preprocess}{$command}{call}->(
1555 destpage => $destpage,
1556 preview => $preprocess_preview,
1561 $preprocessing{$page}--;
1565 return "[[$prefix$command $params]]";
1570 if ($config{prefix_directives}) {
1573 \[\[(!) # directive open; 2: prefix
1574 ([-\w]+) # 3: command
1575 ( # 4: the parameters..
1576 \s+ # Must have space if parameters present
1578 (?:[-.\w]+=)? # named parameter key?
1580 """.*?""" # triple-quoted value
1582 "[^"]*?" # single-quoted value
1584 '''.*?''' # triple-single-quote
1586 <<([a-zA-Z]+)\n # 5: heredoc start
1587 (?:.*?)\n\5 # heredoc value
1589 [^"\s\]]+ # unquoted value
1591 \s* # whitespace or end
1594 *)? # 0 or more parameters
1595 \]\] # directive closed
1601 \[\[(!?) # directive open; 2: optional prefix
1602 ([-\w]+) # 3: command
1604 ( # 4: the parameters..
1606 (?:[-.\w]+=)? # named parameter key?
1608 """.*?""" # triple-quoted value
1610 "[^"]*?" # single-quoted value
1612 '''.*?''' # triple-single-quote
1614 <<([a-zA-Z]+)\n # 5: heredoc start
1615 (?:.*?)\n\5 # heredoc value
1617 [^"\s\]]+ # unquoted value
1619 \s* # whitespace or end
1622 *) # 0 or more parameters
1623 \]\] # directive closed
1627 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1636 run_hooks(filter => sub {
1637 $content=shift->(page => $page, destpage => $destpage,
1638 content => $content);
1644 sub check_canedit ($$$;$) {
1651 run_hooks(canedit => sub {
1652 return if defined $canedit;
1653 my $ret=shift->($page, $q, $session);
1658 elsif (ref $ret eq 'CODE') {
1659 $ret->() unless $nonfatal;
1662 elsif (defined $ret) {
1663 error($ret) unless $nonfatal;
1668 return defined $canedit ? $canedit : 1;
1671 sub check_content (@) {
1674 return 1 if ! exists $hooks{checkcontent}; # optimisation
1676 if (exists $pagesources{$params{page}}) {
1678 my %old=map { $_ => 1 }
1679 split("\n", readfile(srcfile($pagesources{$params{page}})));
1680 foreach my $line (split("\n", $params{content})) {
1681 push @diff, $line if ! exists $old{$line};
1683 $params{diff}=join("\n", @diff);
1687 run_hooks(checkcontent => sub {
1688 return if defined $ok;
1689 my $ret=shift->(%params);
1694 elsif (ref $ret eq 'CODE') {
1695 $ret->() unless $params{nonfatal};
1698 elsif (defined $ret) {
1699 error($ret) unless $params{nonfatal};
1705 return defined $ok ? $ok : 1;
1708 sub check_canchange (@) {
1710 my $cgi = $params{cgi};
1711 my $session = $params{session};
1712 my @changes = @{$params{changes}};
1715 foreach my $change (@changes) {
1716 # This untaint is safe because we check file_pruned and
1718 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1719 $file=possibly_foolish_untaint($file);
1720 if (! defined $file || ! length $file ||
1721 file_pruned($file)) {
1722 error(gettext("bad file name %s"), $file);
1725 my $type=pagetype($file);
1726 my $page=pagename($file) if defined $type;
1728 if ($change->{action} eq 'add') {
1732 if ($change->{action} eq 'change' ||
1733 $change->{action} eq 'add') {
1734 if (defined $page) {
1735 check_canedit($page, $cgi, $session);
1739 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1740 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1741 check_canedit($file, $cgi, $session);
1746 elsif ($change->{action} eq 'remove') {
1747 # check_canremove tests to see if the file is present
1748 # on disk. This will fail when a single commit adds a
1749 # file and then removes it again. Avoid the problem
1750 # by not testing the removal in such pairs of changes.
1751 # (The add is still tested, just to make sure that
1752 # no data is added to the repo that a web edit
1754 next if $newfiles{$file};
1756 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1757 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1758 check_canedit(defined $page ? $page : $file, $cgi, $session);
1763 error "unknown action ".$change->{action};
1766 error sprintf(gettext("you are not allowed to change %s"), $file);
1774 # Take an exclusive lock on the wiki to prevent multiple concurrent
1775 # run issues. The lock will be dropped on program exit.
1776 if (! -d $config{wikistatedir}) {
1777 mkdir($config{wikistatedir});
1779 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1780 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1781 if (! flock($wikilock, 2)) { # LOCK_EX
1782 error("failed to get lock");
1788 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1789 return close($wikilock) if $wikilock;
1795 sub commit_hook_enabled () {
1796 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1797 error("cannot write to $config{wikistatedir}/commitlock: $!");
1798 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1799 close($commitlock) || error("failed closing commitlock: $!");
1802 close($commitlock) || error("failed closing commitlock: $!");
1806 sub disable_commit_hook () {
1807 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1808 error("cannot write to $config{wikistatedir}/commitlock: $!");
1809 if (! flock($commitlock, 2)) { # LOCK_EX
1810 error("failed to get commit lock");
1815 sub enable_commit_hook () {
1816 return close($commitlock) if $commitlock;
1821 %oldrenderedfiles=%pagectime=();
1822 my $rebuild=$config{rebuild};
1824 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1825 %destsources=%renderedfiles=%pagecase=%pagestate=
1826 %depends_simple=%typedlinks=%oldtypedlinks=();
1829 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1830 if (-e "$config{wikistatedir}/index") {
1831 system("ikiwiki-transition", "indexdb", $config{srcdir});
1832 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1835 # gettime on first build
1836 $config{gettime}=1 unless defined $config{gettime};
1841 my $index=Storable::fd_retrieve($in);
1842 if (! defined $index) {
1847 if (exists $index->{version} && ! ref $index->{version}) {
1848 $pages=$index->{page};
1849 %wikistate=%{$index->{state}};
1850 # Handle plugins that got disabled by loading a new setup.
1851 if (exists $config{setupfile}) {
1852 require IkiWiki::Setup;
1853 IkiWiki::Setup::disabled_plugins(
1854 grep { ! $loaded_plugins{$_} } keys %wikistate);
1862 foreach my $src (keys %$pages) {
1863 my $d=$pages->{$src};
1865 if (exists $d->{page} && ! $rebuild) {
1869 $page=pagename($src);
1871 $pagectime{$page}=$d->{ctime};
1872 $pagesources{$page}=$src;
1874 $pagemtime{$page}=$d->{mtime};
1875 $renderedfiles{$page}=$d->{dest};
1876 if (exists $d->{links} && ref $d->{links}) {
1877 $links{$page}=$d->{links};
1878 $oldlinks{$page}=[@{$d->{links}}];
1880 if (ref $d->{depends_simple} eq 'ARRAY') {
1882 $depends_simple{$page}={
1883 map { $_ => 1 } @{$d->{depends_simple}}
1886 elsif (exists $d->{depends_simple}) {
1887 $depends_simple{$page}=$d->{depends_simple};
1889 if (exists $d->{dependslist}) {
1892 map { $_ => $DEPEND_CONTENT }
1893 @{$d->{dependslist}}
1896 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1898 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1900 elsif (exists $d->{depends}) {
1901 $depends{$page}=$d->{depends};
1903 if (exists $d->{state}) {
1904 $pagestate{$page}=$d->{state};
1906 if (exists $d->{typedlinks}) {
1907 $typedlinks{$page}=$d->{typedlinks};
1909 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1910 next unless %$links;
1911 $oldtypedlinks{$page}{$type} = {%$links};
1915 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1917 foreach my $page (keys %pagesources) {
1918 $pagecase{lc $page}=$page;
1920 foreach my $page (keys %renderedfiles) {
1921 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1923 $lastrev=$index->{lastrev};
1924 @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1929 run_hooks(savestate => sub { shift->() });
1931 my @plugins=keys %loaded_plugins;
1933 if (! -d $config{wikistatedir}) {
1934 mkdir($config{wikistatedir});
1936 my $newfile="$config{wikistatedir}/indexdb.new";
1937 my $cleanup = sub { unlink($newfile) };
1938 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1941 foreach my $page (keys %pagemtime) {
1942 next unless $pagemtime{$page};
1943 my $src=$pagesources{$page};
1945 $index{page}{$src}={
1947 ctime => $pagectime{$page},
1948 mtime => $pagemtime{$page},
1949 dest => $renderedfiles{$page},
1950 links => $links{$page},
1953 if (exists $depends{$page}) {
1954 $index{page}{$src}{depends} = $depends{$page};
1957 if (exists $depends_simple{$page}) {
1958 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1961 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1962 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1965 if (exists $pagestate{$page}) {
1966 $index{page}{$src}{state}=$pagestate{$page};
1971 foreach my $id (@plugins) {
1972 $index{state}{$id}={}; # used to detect disabled plugins
1973 foreach my $key (keys %{$wikistate{$id}}) {
1974 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1978 $index{lastrev}=$lastrev;
1979 $index{underlayfiles}=\@underlayfiles;
1981 $index{version}="3";
1982 my $ret=Storable::nstore_fd(\%index, $out);
1983 return if ! defined $ret || ! $ret;
1984 close $out || error("failed saving to $newfile: $!", $cleanup);
1985 rename($newfile, "$config{wikistatedir}/indexdb") ||
1986 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1991 sub template_file ($) {
1994 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1996 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1997 $template=srcfile($pagesources{$tpage}, 1);
2001 $template=srcfile($tpage, 1);
2004 if (defined $template) {
2005 return $template, $tpage, 1 if wantarray;
2009 $name=~s:/::; # avoid path traversal
2010 foreach my $dir ($config{templatedir},
2011 "$installdir/share/ikiwiki/templates") {
2012 if (-e "$dir/$name") {
2013 $template="$dir/$name";
2017 if (defined $template) {
2018 return $template, $tpage if wantarray;
2026 sub template_depends ($$;@) {
2030 my ($filename, $tpage, $untrusted)=template_file($name);
2031 if (! defined $filename) {
2032 error(sprintf(gettext("template %s not found"), $name))
2035 if (defined $page && defined $tpage) {
2036 add_depends($page, $tpage);
2041 my $text_ref = shift;
2042 ${$text_ref} = decode_utf8(${$text_ref});
2043 run_hooks(readtemplate => sub {
2044 ${$text_ref} = shift->(
2047 content => ${$text_ref},
2048 untrusted => $untrusted,
2052 loop_context_vars => 1,
2053 die_on_bad_params => 0,
2054 parent_global_vars => 1,
2055 filename => $filename,
2057 ($untrusted ? (no_includes => 1) : ()),
2059 return @opts if wantarray;
2061 require HTML::Template;
2062 return HTML::Template->new(@opts);
2065 sub template ($;@) {
2066 template_depends(shift, undef, @_);
2069 sub templateactions ($$) {
2075 run_hooks(pageactions => sub {
2076 push @actions, map { { action => $_ } }
2077 grep { defined } shift->(page => $page);
2079 $template->param(actions => \@actions);
2081 if ($config{cgiurl} && exists $hooks{auth}) {
2082 $template->param(prefsurl => cgiurl(do => "prefs"));
2086 if ($have_actions || @actions) {
2087 $template->param(have_actions => 1);
2094 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2095 error 'hook requires type, call, and id parameters';
2098 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2100 $hooks{$param{type}}{$param{id}}=\%param;
2104 sub run_hooks ($$) {
2105 # Calls the given sub for each hook of the given type,
2106 # passing it the hook function to call.
2110 if (exists $hooks{$type}) {
2111 my (@first, @middle, @last);
2112 foreach my $id (keys %{$hooks{$type}}) {
2113 if ($hooks{$type}{$id}{first}) {
2116 elsif ($hooks{$type}{$id}{last}) {
2123 foreach my $id (@first, @middle, @last) {
2124 $sub->($hooks{$type}{$id}{call});
2132 $hooks{rcs}{rcs_update}{call}->(@_);
2135 sub rcs_prepedit ($) {
2136 $hooks{rcs}{rcs_prepedit}{call}->(@_);
2139 sub rcs_commit (@) {
2140 $hooks{rcs}{rcs_commit}{call}->(@_);
2143 sub rcs_commit_staged (@) {
2144 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2148 $hooks{rcs}{rcs_add}{call}->(@_);
2151 sub rcs_remove ($) {
2152 $hooks{rcs}{rcs_remove}{call}->(@_);
2155 sub rcs_rename ($$) {
2156 $hooks{rcs}{rcs_rename}{call}->(@_);
2159 sub rcs_recentchanges ($) {
2160 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2163 sub rcs_diff ($;$) {
2164 $hooks{rcs}{rcs_diff}{call}->(@_);
2167 sub rcs_getctime ($) {
2168 $hooks{rcs}{rcs_getctime}{call}->(@_);
2171 sub rcs_getmtime ($) {
2172 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2175 sub rcs_receive () {
2176 $hooks{rcs}{rcs_receive}{call}->();
2179 sub add_depends ($$;$) {
2182 my $deptype=shift || $DEPEND_CONTENT;
2184 # Is the pagespec a simple page name?
2185 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2186 $pagespec !~ /[\s*?()!]/) {
2187 $depends_simple{$page}{lc $pagespec} |= $deptype;
2191 # Add explicit dependencies for influences.
2192 my $sub=pagespec_translate($pagespec);
2193 return unless defined $sub;
2194 foreach my $p (keys %pagesources) {
2195 my $r=$sub->($p, location => $page);
2196 my $i=$r->influences;
2197 my $static=$r->influences_static;
2198 foreach my $k (keys %$i) {
2199 next unless $r || $static || $k eq $page;
2200 $depends_simple{$page}{lc $k} |= $i->{$k};
2205 $depends{$page}{$pagespec} |= $deptype;
2211 foreach my $type (@_) {
2212 if ($type eq 'presence') {
2213 $deptype |= $DEPEND_PRESENCE;
2215 elsif ($type eq 'links') {
2216 $deptype |= $DEPEND_LINKS;
2218 elsif ($type eq 'content') {
2219 $deptype |= $DEPEND_CONTENT;
2225 my $file_prune_regexp;
2226 sub file_pruned ($) {
2229 if (defined $config{include} && length $config{include}) {
2230 return 0 if $file =~ m/$config{include}/;
2233 if (! defined $file_prune_regexp) {
2234 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2235 $file_prune_regexp=qr/$file_prune_regexp/;
2237 return $file =~ m/$file_prune_regexp/;
2240 sub define_gettext () {
2241 # If translation is needed, redefine the gettext function to do it.
2242 # Otherwise, it becomes a quick no-op.
2245 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2246 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2247 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2249 $gettext_obj=eval q{
2250 use Locale::gettext q{textdomain};
2251 Locale::gettext->domain('ikiwiki')
2256 no warnings 'redefine';
2258 $getobj->() if $getobj;
2260 $gettext_obj->get(shift);
2267 $getobj->() if $getobj;
2269 $gettext_obj->nget(@_);
2272 return ($_[2] == 1 ? $_[0] : $_[1])
2290 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2294 # Injects a new function into the symbol table to replace an
2295 # exported function.
2298 # This is deep ugly perl foo, beware.
2301 if (! defined $params{parent}) {
2302 $params{parent}='::';
2303 $params{old}=\&{$params{name}};
2304 $params{name}=~s/.*:://;
2306 my $parent=$params{parent};
2307 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2308 $ns = $params{parent} . $ns;
2309 inject(%params, parent => $ns) unless $ns eq '::main::';
2310 *{$ns . $params{name}} = $params{call}
2311 if exists ${$ns}{$params{name}} &&
2312 \&{${$ns}{$params{name}}} == $params{old};
2318 sub add_link ($$;$) {
2323 push @{$links{$page}}, $link
2324 unless grep { $_ eq $link } @{$links{$page}};
2326 if (defined $type) {
2327 $typedlinks{$page}{$type}{$link} = 1;
2331 sub add_autofile ($$$) {
2334 my $generator=shift;
2336 $autofiles{$file}{plugin}=$plugin;
2337 $autofiles{$file}{generator}=$generator;
2341 return LWP::UserAgent->new(
2342 cookie_jar => $config{cookiejar},
2343 env_proxy => 1, # respect proxy env vars
2344 agent => $config{useragent},
2348 sub sortspec_translate ($$) {
2350 my $reverse = shift;
2356 (-?) # group 1: perhaps negated
2359 \w+\([^\)]*\) # command(params)
2361 [^\s]+ # or anything else
2369 if ($word =~ m/^(\w+)\((.*)\)$/) {
2370 # command with parameters
2374 elsif ($word !~ m/^\w+$/) {
2375 error(sprintf(gettext("invalid sort type %s"), $word));
2386 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2387 if (defined $params) {
2388 push @data, $params;
2389 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2392 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2396 error(sprintf(gettext("unknown sort type %s"), $word));
2400 if (! length $code) {
2401 # undefined sorting method... sort arbitrarily
2410 return eval 'sub { '.$code.' }';
2413 sub pagespec_translate ($) {
2416 # Convert spec to perl code.
2420 \s* # ignore whitespace
2421 ( # 1: match a single word
2428 \w+\([^\)]*\) # command(params)
2430 [^\s()]+ # any other text
2432 \s* # ignore whitespace
2435 if (lc $word eq 'and') {
2438 elsif (lc $word eq 'or') {
2441 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2444 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2445 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2447 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2450 push @data, qq{unknown function in pagespec "$word"};
2451 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2456 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2460 if (! length $code) {
2461 $code="IkiWiki::FailReason->new('empty pagespec')";
2465 return eval 'sub { my $page=shift; '.$code.' }';
2468 sub pagespec_match ($$;@) {
2473 # Backwards compatability with old calling convention.
2475 unshift @params, 'location';
2478 my $sub=pagespec_translate($spec);
2479 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2481 return $sub->($page, @params);
2484 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2486 # Not exported yet, but could be in future if it is generally useful.
2487 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2488 # which is "more internal".
2489 sub sort_pages ($$;@) {
2493 $sort = sortspec_translate($sort, $params{reverse});
2494 return IkiWiki::SortSpec::sort_pages($sort, @$list);
2497 sub pagespec_match_list ($$;@) {
2502 # Backwards compatability with old calling convention.
2504 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2505 $params{list}=$page;
2506 $page=$params{location}; # ugh!
2509 my $sub=pagespec_translate($pagespec);
2510 error "syntax error in pagespec \"$pagespec\""
2512 my $sort=sortspec_translate($params{sort}, $params{reverse})
2513 if defined $params{sort};
2516 if (exists $params{list}) {
2517 @candidates=exists $params{filter}
2518 ? grep { ! $params{filter}->($_) } @{$params{list}}
2522 @candidates=exists $params{filter}
2523 ? grep { ! $params{filter}->($_) } keys %pagesources
2524 : keys %pagesources;
2527 # clear params, remainder is passed to pagespec
2528 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2529 my $num=$params{num};
2530 delete @params{qw{num deptype reverse sort filter list}};
2532 # when only the top matches will be returned, it's efficient to
2533 # sort before matching to pagespec,
2534 if (defined $num && defined $sort) {
2535 @candidates=IkiWiki::SortSpec::sort_pages(
2536 $sort, @candidates);
2542 my $accum=IkiWiki::SuccessReason->new();
2543 foreach my $p (@candidates) {
2544 my $r=$sub->($p, %params, location => $page);
2545 error(sprintf(gettext("cannot match pages: %s"), $r))
2546 if $r->isa("IkiWiki::ErrorReason");
2547 unless ($r || $r->influences_static) {
2548 $r->remove_influence($p);
2553 last if defined $num && ++$count == $num;
2557 # Add simple dependencies for accumulated influences.
2558 my $i=$accum->influences;
2559 foreach my $k (keys %$i) {
2560 $depends_simple{$page}{lc $k} |= $i->{$k};
2563 # when all matches will be returned, it's efficient to
2564 # sort after matching
2565 if (! defined $num && defined $sort) {
2566 return IkiWiki::SortSpec::sort_pages(
2574 sub pagespec_valid ($) {
2577 return defined pagespec_translate($spec);
2581 my $re=quotemeta(shift);
2587 package IkiWiki::FailReason;
2590 '""' => sub { $_[0][0] },
2592 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2593 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2594 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2598 our @ISA = 'IkiWiki::SuccessReason';
2600 package IkiWiki::SuccessReason;
2602 # A blessed array-ref:
2604 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2606 # - if absent or false, the influences of this evaluation are "static",
2607 # see the influences_static method
2608 # - if true, they are dynamic (not static)
2609 # [1]{any other key}:
2610 # the dependency types of influences, as returned by the influences method
2613 # in string context, it's the human-readable reason
2614 '""' => sub { $_[0][0] },
2615 # in boolean context, SuccessReason is 1 and FailReason is 0
2617 # negating a result gives the opposite result with the same influences
2618 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2619 # A & B = (A ? B : A) with the influences of both
2620 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2621 # A | B = (A ? A : B) with the influences of both
2622 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2626 # SuccessReason->new("human-readable reason", page => deptype, ...)
2631 return bless [$value, {@_}], $class;
2634 # influences(): return a reference to a copy of the hash
2635 # { page => dependency type } describing the pages that indirectly influenced
2636 # this result, but would not cause a dependency through ikiwiki's core
2639 # See [[todo/dependency_types]] for extensive discussion of what this means.
2641 # influences(page => deptype, ...): remove all influences, replace them
2642 # with the arguments, and return a reference to a copy of the new influences.
2646 $this->[1]={@_} if @_;
2647 my %i=%{$this->[1]};
2652 # True if this result has the same influences whichever page it matches,
2653 # For instance, whether bar matches backlink(foo) is influenced only by
2654 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2655 # which does not mention bar anywhere.
2657 # False if this result would have different influences when matching
2658 # different pages. For instance, when testing whether link(foo) matches bar,
2659 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2660 # bar's links could change the outcome; so its influences are not the same
2661 # as when testing whether link(foo) matches baz.
2663 # Static influences are one of the things that make pagespec_match_list
2664 # more efficient than repeated calls to pagespec_match.
2666 sub influences_static {
2667 return ! $_[0][1]->{""};
2670 # Change the influences of $this to be the influences of "$this & $other"
2671 # or "$this | $other".
2673 # If both $this and $other are either successful or have influences,
2674 # or this is an "or" operation, the result has all the influences from
2675 # either of the arguments. It has dynamic influences if either argument
2676 # has dynamic influences.
2678 # If this is an "and" operation, and at least one argument is a
2679 # FailReason with no influences, the result has no influences, and they
2680 # are not dynamic. For instance, link(foo) matching bar is influenced
2681 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2682 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2683 # bar, because it would be false however often you edit bar.
2685 sub merge_influences {
2690 # This "if" is odd because it needs to avoid negating $this
2691 # or $other, which would alter the objects in-place. Be careful.
2692 if (! $anded || (($this || %{$this->[1]}) &&
2693 ($other || %{$other->[1]}))) {
2694 foreach my $influence (keys %{$other->[1]}) {
2695 $this->[1]{$influence} |= $other->[1]{$influence};
2704 # Change $this so it is not considered to be influenced by $torm.
2706 sub remove_influence {
2710 delete $this->[1]{$torm};
2713 package IkiWiki::ErrorReason;
2715 our @ISA = 'IkiWiki::FailReason';
2717 package IkiWiki::PageSpec;
2723 if ($path =~ m!^\.(/|$)!) {
2725 $from=~s#/?[^/]+$## if defined $from;
2727 $path="$from/$path" if defined $from && length $from;
2731 $path = "" unless defined $path;
2740 sub match_glob ($$;@) {
2745 $glob=derel($glob, $params{location});
2747 # Instead of converting the glob to a regex every time,
2748 # cache the compiled regex to save time.
2749 my $re=$glob_cache{$glob};
2750 unless (defined $re) {
2751 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2754 if (! IkiWiki::isinternal($page) || $params{internal}) {
2755 return IkiWiki::SuccessReason->new("$glob matches $page");
2758 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2762 return IkiWiki::FailReason->new("$glob does not match $page");
2766 sub match_internal ($$;@) {
2767 return match_glob(shift, shift, @_, internal => 1)
2770 sub match_page ($$;@) {
2772 my $match=match_glob($page, shift, @_);
2774 my $source=exists $IkiWiki::pagesources{$page} ?
2775 $IkiWiki::pagesources{$page} :
2776 $IkiWiki::delpagesources{$page};
2777 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2778 if (! defined $type) {
2779 return IkiWiki::FailReason->new("$page is not a page");
2785 sub match_link ($$;@) {
2790 $link=derel($link, $params{location});
2791 my $from=exists $params{location} ? $params{location} : '';
2792 my $linktype=$params{linktype};
2794 if (defined $linktype) {
2795 $qualifier=" with type $linktype";
2798 my $links = $IkiWiki::links{$page};
2799 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2800 unless $links && @{$links};
2801 my $bestlink = IkiWiki::bestlink($from, $link);
2802 foreach my $p (@{$links}) {
2803 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2805 if (length $bestlink) {
2806 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2807 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2811 if (match_glob($p, $link, %params)) {
2812 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2814 my ($p_rel)=$p=~/^\/?(.*)/;
2816 if (match_glob($p_rel, $link, %params)) {
2817 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2821 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2824 sub match_backlink ($$;@) {
2828 if ($testpage eq '.') {
2829 $testpage = $params{'location'}
2831 my $ret=match_link($testpage, $page, @_);
2832 $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2836 sub match_created_before ($$;@) {
2841 $testpage=derel($testpage, $params{location});
2843 if (exists $IkiWiki::pagectime{$testpage}) {
2844 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2845 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2848 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2852 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2856 sub match_created_after ($$;@) {
2861 $testpage=derel($testpage, $params{location});
2863 if (exists $IkiWiki::pagectime{$testpage}) {
2864 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2865 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2868 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2872 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2876 sub match_creation_day ($$;@) {
2879 if ($d !~ /^\d+$/) {
2880 return IkiWiki::ErrorReason->new("invalid day $d");
2882 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2883 return IkiWiki::SuccessReason->new('creation_day matched');
2886 return IkiWiki::FailReason->new('creation_day did not match');
2890 sub match_creation_month ($$;@) {
2893 if ($m !~ /^\d+$/) {
2894 return IkiWiki::ErrorReason->new("invalid month $m");
2896 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2897 return IkiWiki::SuccessReason->new('creation_month matched');
2900 return IkiWiki::FailReason->new('creation_month did not match');
2904 sub match_creation_year ($$;@) {
2907 if ($y !~ /^\d+$/) {
2908 return IkiWiki::ErrorReason->new("invalid year $y");
2910 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2911 return IkiWiki::SuccessReason->new('creation_year matched');
2914 return IkiWiki::FailReason->new('creation_year did not match');
2918 sub match_user ($$;@) {
2923 if (! exists $params{user}) {
2924 return IkiWiki::ErrorReason->new("no user specified");
2927 my $regexp=IkiWiki::glob2re($user);
2929 if (defined $params{user} && $params{user}=~$regexp) {
2930 return IkiWiki::SuccessReason->new("user is $user");
2932 elsif (! defined $params{user}) {
2933 return IkiWiki::FailReason->new("not logged in");
2936 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2940 sub match_admin ($$;@) {
2945 if (! exists $params{user}) {
2946 return IkiWiki::ErrorReason->new("no user specified");
2949 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2950 return IkiWiki::SuccessReason->new("user is an admin");
2952 elsif (! defined $params{user}) {
2953 return IkiWiki::FailReason->new("not logged in");
2956 return IkiWiki::FailReason->new("user is not an admin");
2960 sub match_ip ($$;@) {
2965 if (! exists $params{ip}) {
2966 return IkiWiki::ErrorReason->new("no IP specified");
2969 my $regexp=IkiWiki::glob2re(lc $ip);
2971 if (defined $params{ip} && lc $params{ip}=~$regexp) {
2972 return IkiWiki::SuccessReason->new("IP is $ip");
2975 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2979 package IkiWiki::SortSpec;
2981 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2982 # are easily available in this namespace, for cmp functions to use them.
2989 IkiWiki::pagetitle(IkiWiki::basename($a))
2991 IkiWiki::pagetitle(IkiWiki::basename($b))
2994 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2995 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2996 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }