8 use URI::Escape q{uri_escape_utf8};
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14 %pagestate %wikistate %renderedfiles %oldrenderedfiles
15 %pagesources %delpagesources %destsources %depends %depends_simple
16 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17 %oldtypedlinks %autofiles};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21 deptype add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link add_autofile
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
40 memoize("sortspec_translate");
41 memoize("pagespec_translate");
42 memoize("template_file");
48 description => "name of the wiki",
55 example => 'me@example.com',
56 description => "contact email for wiki",
63 description => "users who are wiki admins",
70 description => "users who are banned from the wiki",
77 example => "$ENV{HOME}/wiki",
78 description => "where the source of the wiki is located",
85 example => "/var/www/wiki",
86 description => "where to build the wiki",
93 example => "http://example.com/wiki",
94 description => "base url to the wiki",
101 example => "http://example.com/wiki/ikiwiki.cgi",
102 description => "url to the ikiwiki.cgi",
109 example => "/var/www/wiki/ikiwiki.cgi",
110 description => "filename of cgi wrapper to generate",
117 description => "mode for cgi_wrapper (can safely be made suid)",
124 description => "rcs backend to use",
125 safe => 0, # don't allow overriding
130 default => [qw{mdwn link inline meta htmlscrubber passwordauth
131 openid signinedit lockedit conditional
132 recentchanges parentlinks editpage}],
133 description => "plugins to enable by default",
140 description => "plugins to add to the default configuration",
147 description => "plugins to disable",
153 default => "$installdir/share/ikiwiki/templates",
154 description => "additional directory to search for template files",
161 default => "$installdir/share/ikiwiki/basewiki",
162 description => "base wiki source location",
169 default => "$installdir/share/ikiwiki",
170 description => "parent directory containing additional underlays",
177 description => "wrappers to generate",
184 description => "additional underlays to use",
191 description => "display verbose messages?",
198 description => "log to syslog?",
205 description => "create output files named page/index.html?",
206 safe => 0, # changing requires manual transition
209 prefix_directives => {
212 description => "use '!'-prefixed preprocessor directives?",
213 safe => 0, # changing requires manual transition
219 description => "use page/index.mdwn source files",
226 description => "enable Discussion pages?",
232 default => gettext("Discussion"),
233 description => "name of Discussion pages",
240 description => "generate HTML5? (experimental)",
248 description => "only send cookies over SSL connections?",
256 description => "extension to use for new pages",
257 safe => 0, # not sanitized
263 description => "extension to use for html files",
264 safe => 0, # not sanitized
270 description => "strftime format string to display date",
278 example => "en_US.UTF-8",
279 description => "UTF-8 locale to use",
288 description => "put user pages below specified page",
295 description => "how many backlinks to show before hiding excess (0 to show all)",
302 description => "attempt to hardlink source files? (optimisation for large files)",
304 safe => 0, # paranoia
310 description => "force ikiwiki to use a particular umask",
312 safe => 0, # paranoia
317 example => "ikiwiki",
318 description => "group for wrappers to run in",
320 safe => 0, # paranoia
326 example => "$ENV{HOME}/.ikiwiki/",
327 description => "extra library and plugin directory",
329 safe => 0, # directory
335 description => "environment variables",
336 safe => 0, # paranoia
342 example => '^\.htaccess$',
343 description => "regexp of normally excluded files to include",
351 example => '^(*\.private|Makefile)$',
352 description => "regexp of files that should be skipped",
357 wiki_file_prune_regexps => {
359 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
360 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
361 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
362 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
363 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
364 description => "regexps of source files to ignore",
370 description => "specifies the characters that are allowed in source filenames",
371 default => "-[:alnum:]+/.:_",
375 wiki_file_regexp => {
377 description => "regexp of legal source files",
381 web_commit_regexp => {
383 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
384 description => "regexp to parse web commits from logs",
391 description => "run as a cgi",
395 cgi_disable_uploads => {
398 description => "whether CGI should accept file uploads",
405 description => "run as a post-commit hook",
412 description => "running in rebuild mode",
419 description => "running in setup mode",
426 description => "running in clean mode",
433 description => "running in refresh mode",
440 description => "running in receive test mode",
444 wrapper_background_command => {
447 description => "background shell command to run",
453 description => "running in gettime mode",
460 description => "running in w3mmode",
467 description => "path to the .ikiwiki directory holding ikiwiki state",
474 description => "path to setup file",
480 default => "Standard",
481 description => "perl class to use to dump setup file",
485 allow_symlinks_before_srcdir => {
488 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
494 sub defaultconfig () {
497 foreach my $key (keys %s) {
498 push @ret, $key, $s{$key}->{default};
505 # locale stuff; avoid LC_ALL since it overrides everything
506 if (defined $ENV{LC_ALL}) {
507 $ENV{LANG} = $ENV{LC_ALL};
510 if (defined $config{locale}) {
511 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
512 $ENV{LANG}=$config{locale};
517 if (! defined $config{wiki_file_regexp}) {
518 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
521 if (ref $config{ENV} eq 'HASH') {
522 foreach my $val (keys %{$config{ENV}}) {
523 $ENV{$val}=$config{ENV}{$val};
527 if ($config{w3mmode}) {
528 eval q{use Cwd q{abs_path}};
530 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
531 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
532 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
533 unless $config{cgiurl} =~ m!file:///!;
534 $config{url}="file://".$config{destdir};
537 if ($config{cgi} && ! length $config{url}) {
538 error(gettext("Must specify url to wiki with --url when using --cgi"));
541 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
542 unless exists $config{wikistatedir} && defined $config{wikistatedir};
544 if (defined $config{umask}) {
545 umask(possibly_foolish_untaint($config{umask}));
548 run_hooks(checkconfig => sub { shift->() });
556 foreach my $dir (@INC, $config{libdir}) {
557 next unless defined $dir && length $dir;
558 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
559 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
563 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
564 next unless defined $dir && length $dir;
565 foreach my $file (glob("$dir/plugins/*")) {
566 $ret{basename($file)}=1 if -x $file;
574 if (defined $config{libdir} && length $config{libdir}) {
575 unshift @INC, possibly_foolish_untaint($config{libdir});
578 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
583 if (exists $hooks{rcs}) {
584 error(gettext("cannot use multiple rcs plugins"));
586 loadplugin($config{rcs});
588 if (! exists $hooks{rcs}) {
592 run_hooks(getopt => sub { shift->() });
593 if (grep /^-/, @ARGV) {
594 print STDERR "Unknown option (or missing parameter): $_\n"
595 foreach grep /^-/, @ARGV;
602 sub loadplugin ($;$) {
606 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
608 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
609 "$installdir/lib/ikiwiki") {
610 if (defined $dir && -x "$dir/plugins/$plugin") {
611 eval { require IkiWiki::Plugin::external };
614 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
616 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
617 $loaded_plugins{$plugin}=1;
622 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
625 error("Failed to load plugin $mod: $@");
627 $loaded_plugins{$plugin}=1;
634 log_message('err' => $message) if $config{syslog};
635 if (defined $cleaner) {
642 return unless $config{verbose};
643 return log_message(debug => @_);
647 sub log_message ($$) {
650 if ($config{syslog}) {
653 Sys::Syslog::setlogsock('unix');
654 Sys::Syslog::openlog('ikiwiki', '', 'user');
658 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
661 elsif (! $config{cgi}) {
665 return print STDERR "@_\n";
669 sub possibly_foolish_untaint ($) {
671 my ($untainted)=$tainted=~/(.*)/s;
691 return exists $pagesources{$page} &&
692 $pagesources{$page} =~ /\._([^.]+)$/;
698 if ($file =~ /\.([^.]+)$/) {
699 return $1 if exists $hooks{htmlize}{$1};
701 my $base=basename($file);
702 if (exists $hooks{htmlize}{$base} &&
703 $hooks{htmlize}{$base}{noextension}) {
714 if (exists $pagename_cache{$file}) {
715 return $pagename_cache{$file};
718 my $type=pagetype($file);
720 $page=~s/\Q.$type\E*$//
721 if defined $type && !$hooks{htmlize}{$type}{keepextension}
722 && !$hooks{htmlize}{$type}{noextension};
723 if ($config{indexpages} && $page=~/(.*)\/index$/) {
727 $pagename_cache{$file} = $page;
731 sub newpagefile ($$) {
735 if (! $config{indexpages} || $page eq 'index') {
736 return $page.".".$type;
739 return $page."/index.".$type;
743 sub targetpage ($$;$) {
748 if (defined $filename) {
749 return $page."/".$filename.".".$ext;
751 elsif (! $config{usedirs} || $page eq 'index') {
752 return $page.".".$ext;
755 return $page."/index.".$ext;
762 return targetpage($page, $config{htmlext});
769 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
770 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
771 return "$dir/$file", stat(_) if -e "$dir/$file";
773 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
778 return (srcfile_stat(@_))[0];
781 sub add_underlay ($) {
785 $dir="$config{underlaydirbase}/$dir";
788 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
789 unshift @{$config{underlaydirs}}, $dir;
795 sub readfile ($;$$) {
801 error("cannot read a symlink ($file)");
805 open (my $in, "<", $file) || error("failed to read $file: $!");
806 binmode($in) if ($binary);
807 return \*$in if $wantfd;
809 # check for invalid utf-8, and toss it back to avoid crashes
810 if (! utf8::valid($ret)) {
811 $ret=encode_utf8($ret);
813 close $in || error("failed to read $file: $!");
817 sub prep_writefile ($$) {
822 while (length $test) {
823 if (-l "$destdir/$test") {
824 error("cannot write to a symlink ($test)");
826 if (-f _ && $test ne $file) {
827 # Remove conflicting file.
828 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
829 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
831 unlink("$destdir/$test");
837 $test=dirname($test);
840 my $dir=dirname("$destdir/$file");
843 foreach my $s (split(m!/+!, $dir)) {
846 mkdir($d) || error("failed to create directory $d: $!");
854 sub writefile ($$$;$$) {
855 my $file=shift; # can include subdirs
856 my $destdir=shift; # directory to put file in
861 prep_writefile($file, $destdir);
863 my $newfile="$destdir/$file.ikiwiki-new";
865 error("cannot write to a symlink ($newfile)");
868 my $cleanup = sub { unlink($newfile) };
869 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
870 binmode($out) if ($binary);
872 $writer->(\*$out, $cleanup);
875 print $out $content or error("failed writing to $newfile: $!", $cleanup);
877 close $out || error("failed saving $newfile: $!", $cleanup);
878 rename($newfile, "$destdir/$file") ||
879 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
885 sub will_render ($$;$) {
890 # Important security check for independently created files.
891 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
892 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
893 my $from_other_page=0;
894 # Expensive, but rarely runs.
895 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
899 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
905 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
906 unless $from_other_page;
909 # If $dest exists as a directory, remove conflicting files in it
910 # rendered from other pages.
912 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
913 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
914 if (dirname($f) eq $dest) {
915 unlink("$config{destdir}/$f");
916 rmdir(dirname("$config{destdir}/$f"));
922 if (! $clear || $cleared{$page}) {
923 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
926 foreach my $old (@{$renderedfiles{$page}}) {
927 delete $destsources{$old};
929 $renderedfiles{$page}=[$dest];
932 $destsources{$dest}=$page;
942 if ($link=~s/^\/+//) {
950 $l.="/" if length $l;
953 if (exists $pagesources{$l}) {
956 elsif (exists $pagecase{lc $l}) {
957 return $pagecase{lc $l};
959 } while $cwd=~s{/?[^/]+$}{};
961 if (length $config{userdir}) {
962 my $l = "$config{userdir}/".lc($link);
963 if (exists $pagesources{$l}) {
966 elsif (exists $pagecase{lc $l}) {
967 return $pagecase{lc $l};
971 #print STDERR "warning: page $page, broken link: $link\n";
975 sub isinlinableimage ($) {
978 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
981 sub pagetitle ($;$) {
986 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
989 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
997 # support use w/o %config set
998 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
999 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1005 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1006 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1013 my $cgiurl=$config{cgiurl};
1014 if (exists $params{cgiurl}) {
1015 $cgiurl=$params{cgiurl};
1016 delete $params{cgiurl};
1019 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1025 return "$config{url}/" if ! defined $page;
1027 $page=htmlpage($page);
1029 $page=~s/[^\/]+\//..\//g;
1034 # Work around very innefficient behavior in File::Spec if abs2rel
1035 # is passed two relative paths. It's much faster if paths are
1036 # absolute! (Debian bug #376658; fixed in debian unstable now)
1041 my $ret=File::Spec->abs2rel($path, $base);
1042 $ret=~s/^// if defined $ret;
1046 sub displaytime ($;$$) {
1047 # Plugins can override this function to mark up the time to
1049 my $time=formattime($_[0], $_[1]);
1050 if ($config{html5}) {
1051 return '<time datetime="'.date_3339($_[0]).'"'.
1052 ($_[2] ? ' pubdate="pubdate"' : '').
1053 '>'.$time.'</time>';
1056 return '<span class="date">'.$time.'</span>';
1060 sub formattime ($;$) {
1061 # Plugins can override this function to format the time.
1064 if (! defined $format) {
1065 $format=$config{timeformat};
1068 # strftime doesn't know about encodings, so make sure
1069 # its output is properly treated as utf8
1070 return decode_utf8(POSIX::strftime($format, localtime($time)));
1076 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1077 POSIX::setlocale(&POSIX::LC_TIME, "C");
1078 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1079 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1083 sub beautify_urlpath ($) {
1086 # Ensure url is not an empty link, and if necessary,
1087 # add ./ to avoid colon confusion.
1088 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1092 if ($config{usedirs}) {
1093 $url =~ s!/index.$config{htmlext}$!/!;
1105 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1108 if (! $destsources{$to}) {
1113 return $config{url}.beautify_urlpath("/".$to);
1116 my $link = abs2rel($to, dirname(htmlpage($from)));
1118 return beautify_urlpath($link);
1121 sub isselflink ($$) {
1122 # Plugins can override this function to support special types
1127 return $page eq $link;
1130 sub htmllink ($$$;@) {
1131 my $lpage=shift; # the page doing the linking
1132 my $page=shift; # the page that will contain the link (different for inline)
1139 if (! $opts{forcesubpage}) {
1140 $bestlink=bestlink($lpage, $link);
1143 $bestlink="$lpage/".lc($link);
1147 if (defined $opts{linktext}) {
1148 $linktext=$opts{linktext};
1151 $linktext=pagetitle(basename($link));
1154 return "<span class=\"selflink\">$linktext</span>"
1155 if length $bestlink && isselflink($page, $bestlink) &&
1156 ! defined $opts{anchor};
1158 if (! $destsources{$bestlink}) {
1159 $bestlink=htmlpage($bestlink);
1161 if (! $destsources{$bestlink}) {
1163 if (length $config{cgiurl}) {
1164 $cgilink = "<a href=\"".
1169 )."\" rel=\"nofollow\">?</a>";
1171 return "<span class=\"createlink\">$cgilink$linktext</span>"
1175 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1176 $bestlink=beautify_urlpath($bestlink);
1178 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1179 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1182 if (defined $opts{anchor}) {
1183 $bestlink.="#".$opts{anchor};
1187 foreach my $attr (qw{rel class title}) {
1188 if (defined $opts{$attr}) {
1189 push @attrs, " $attr=\"$opts{$attr}\"";
1193 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1198 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1201 sub openiduser ($) {
1204 if ($user =~ m!^https?://! &&
1205 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1208 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1209 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1212 # backcompat with old version
1213 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1214 $display=$oid->display;
1217 # Convert "user.somehost.com" to "user [somehost.com]"
1218 # (also "user.somehost.co.uk")
1219 if ($display !~ /\[/) {
1220 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1222 # Convert "http://somehost.com/user" to "user [somehost.com]".
1223 # (also "https://somehost.com/user/")
1224 if ($display !~ /\[/) {
1225 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1227 $display=~s!^https?://!!; # make sure this is removed
1228 eval q{use CGI 'escapeHTML'};
1230 return escapeHTML($display);
1235 sub htmlize ($$$$) {
1241 my $oneline = $content !~ /\n/;
1243 if (exists $hooks{htmlize}{$type}) {
1244 $content=$hooks{htmlize}{$type}{call}->(
1246 content => $content,
1250 error("htmlization of $type not supported");
1253 run_hooks(sanitize => sub {
1256 destpage => $destpage,
1257 content => $content,
1262 # hack to get rid of enclosing junk added by markdown
1263 # and other htmlizers/sanitizers
1264 $content=~s/^<p>//i;
1265 $content=~s/<\/p>\n*$//i;
1276 run_hooks(linkify => sub {
1279 destpage => $destpage,
1280 content => $content,
1288 our $preprocess_preview=0;
1289 sub preprocess ($$$;$$) {
1290 my $page=shift; # the page the data comes from
1291 my $destpage=shift; # the page the data will appear in (different for inline)
1296 # Using local because it needs to be set within any nested calls
1298 local $preprocess_preview=$preview if defined $preview;
1305 $params="" if ! defined $params;
1307 if (length $escape) {
1308 return "[[$prefix$command $params]]";
1310 elsif (exists $hooks{preprocess}{$command}) {
1311 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1312 # Note: preserve order of params, some plugins may
1313 # consider it significant.
1315 while ($params =~ m{
1316 (?:([-\w]+)=)? # 1: named parameter key?
1318 """(.*?)""" # 2: triple-quoted value
1320 "([^"]*?)" # 3: single-quoted value
1322 (\S+) # 4: unquoted value
1324 (?:\s+|$) # delimiter to next param
1334 elsif (defined $3) {
1337 elsif (defined $4) {
1342 push @params, $key, $val;
1345 push @params, $val, '';
1348 if ($preprocessing{$page}++ > 3) {
1349 # Avoid loops of preprocessed pages preprocessing
1350 # other pages that preprocess them, etc.
1351 return "[[!$command <span class=\"error\">".
1352 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1353 $page, $preprocessing{$page}).
1359 $hooks{preprocess}{$command}{call}->(
1362 destpage => $destpage,
1363 preview => $preprocess_preview,
1369 $ret="[[!$command <span class=\"error\">".
1370 gettext("Error").": $error"."</span>]]";
1374 # use void context during scan pass
1376 $hooks{preprocess}{$command}{call}->(
1379 destpage => $destpage,
1380 preview => $preprocess_preview,
1385 $preprocessing{$page}--;
1389 return "[[$prefix$command $params]]";
1394 if ($config{prefix_directives}) {
1397 \[\[(!) # directive open; 2: prefix
1398 ([-\w]+) # 3: command
1399 ( # 4: the parameters..
1400 \s+ # Must have space if parameters present
1402 (?:[-\w]+=)? # named parameter key?
1404 """.*?""" # triple-quoted value
1406 "[^"]*?" # single-quoted value
1408 [^"\s\]]+ # unquoted value
1410 \s* # whitespace or end
1413 *)? # 0 or more parameters
1414 \]\] # directive closed
1420 \[\[(!?) # directive open; 2: optional prefix
1421 ([-\w]+) # 3: command
1423 ( # 4: the parameters..
1425 (?:[-\w]+=)? # named parameter key?
1427 """.*?""" # triple-quoted value
1429 "[^"]*?" # single-quoted value
1431 [^"\s\]]+ # unquoted value
1433 \s* # whitespace or end
1436 *) # 0 or more parameters
1437 \]\] # directive closed
1441 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1450 run_hooks(filter => sub {
1451 $content=shift->(page => $page, destpage => $destpage,
1452 content => $content);
1458 sub check_canedit ($$$;$) {
1465 run_hooks(canedit => sub {
1466 return if defined $canedit;
1467 my $ret=shift->($page, $q, $session);
1472 elsif (ref $ret eq 'CODE') {
1473 $ret->() unless $nonfatal;
1476 elsif (defined $ret) {
1477 error($ret) unless $nonfatal;
1482 return defined $canedit ? $canedit : 1;
1485 sub check_content (@) {
1488 return 1 if ! exists $hooks{checkcontent}; # optimisation
1490 if (exists $pagesources{$params{page}}) {
1492 my %old=map { $_ => 1 }
1493 split("\n", readfile(srcfile($pagesources{$params{page}})));
1494 foreach my $line (split("\n", $params{content})) {
1495 push @diff, $line if ! exists $old{$line};
1497 $params{diff}=join("\n", @diff);
1501 run_hooks(checkcontent => sub {
1502 return if defined $ok;
1503 my $ret=shift->(%params);
1508 elsif (ref $ret eq 'CODE') {
1509 $ret->() unless $params{nonfatal};
1512 elsif (defined $ret) {
1513 error($ret) unless $params{nonfatal};
1519 return defined $ok ? $ok : 1;
1525 # Take an exclusive lock on the wiki to prevent multiple concurrent
1526 # run issues. The lock will be dropped on program exit.
1527 if (! -d $config{wikistatedir}) {
1528 mkdir($config{wikistatedir});
1530 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1531 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1532 if (! flock($wikilock, 2)) { # LOCK_EX
1533 error("failed to get lock");
1539 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1540 return close($wikilock) if $wikilock;
1546 sub commit_hook_enabled () {
1547 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1548 error("cannot write to $config{wikistatedir}/commitlock: $!");
1549 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1550 close($commitlock) || error("failed closing commitlock: $!");
1553 close($commitlock) || error("failed closing commitlock: $!");
1557 sub disable_commit_hook () {
1558 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1559 error("cannot write to $config{wikistatedir}/commitlock: $!");
1560 if (! flock($commitlock, 2)) { # LOCK_EX
1561 error("failed to get commit lock");
1566 sub enable_commit_hook () {
1567 return close($commitlock) if $commitlock;
1572 %oldrenderedfiles=%pagectime=();
1573 if (! $config{rebuild}) {
1574 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1575 %destsources=%renderedfiles=%pagecase=%pagestate=
1576 %depends_simple=%typedlinks=%oldtypedlinks=();
1579 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1580 if (-e "$config{wikistatedir}/index") {
1581 system("ikiwiki-transition", "indexdb", $config{srcdir});
1582 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1585 $config{gettime}=1; # first build
1590 my $index=Storable::fd_retrieve($in);
1591 if (! defined $index) {
1596 if (exists $index->{version} && ! ref $index->{version}) {
1597 $pages=$index->{page};
1598 %wikistate=%{$index->{state}};
1599 # Handle plugins that got disabled by loading a new setup.
1600 if (exists $config{setupfile}) {
1601 require IkiWiki::Setup;
1602 IkiWiki::Setup::disabled_plugins(
1603 grep { ! $loaded_plugins{$_} } keys %wikistate);
1611 foreach my $src (keys %$pages) {
1612 my $d=$pages->{$src};
1613 my $page=pagename($src);
1614 $pagectime{$page}=$d->{ctime};
1615 $pagesources{$page}=$src;
1616 if (! $config{rebuild}) {
1617 $pagemtime{$page}=$d->{mtime};
1618 $renderedfiles{$page}=$d->{dest};
1619 if (exists $d->{links} && ref $d->{links}) {
1620 $links{$page}=$d->{links};
1621 $oldlinks{$page}=[@{$d->{links}}];
1623 if (ref $d->{depends_simple} eq 'ARRAY') {
1625 $depends_simple{$page}={
1626 map { $_ => 1 } @{$d->{depends_simple}}
1629 elsif (exists $d->{depends_simple}) {
1630 $depends_simple{$page}=$d->{depends_simple};
1632 if (exists $d->{dependslist}) {
1635 map { $_ => $DEPEND_CONTENT }
1636 @{$d->{dependslist}}
1639 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1641 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1643 elsif (exists $d->{depends}) {
1644 $depends{$page}=$d->{depends};
1646 if (exists $d->{state}) {
1647 $pagestate{$page}=$d->{state};
1649 if (exists $d->{typedlinks}) {
1650 $typedlinks{$page}=$d->{typedlinks};
1652 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1653 next unless %$links;
1654 $oldtypedlinks{$page}{$type} = {%$links};
1658 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1660 foreach my $page (keys %pagesources) {
1661 $pagecase{lc $page}=$page;
1663 foreach my $page (keys %renderedfiles) {
1664 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1670 run_hooks(savestate => sub { shift->() });
1672 my @plugins=keys %loaded_plugins;
1674 if (! -d $config{wikistatedir}) {
1675 mkdir($config{wikistatedir});
1677 my $newfile="$config{wikistatedir}/indexdb.new";
1678 my $cleanup = sub { unlink($newfile) };
1679 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1682 foreach my $page (keys %pagemtime) {
1683 next unless $pagemtime{$page};
1684 my $src=$pagesources{$page};
1686 $index{page}{$src}={
1687 ctime => $pagectime{$page},
1688 mtime => $pagemtime{$page},
1689 dest => $renderedfiles{$page},
1690 links => $links{$page},
1693 if (exists $depends{$page}) {
1694 $index{page}{$src}{depends} = $depends{$page};
1697 if (exists $depends_simple{$page}) {
1698 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1701 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1702 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1705 if (exists $pagestate{$page}) {
1706 foreach my $id (@plugins) {
1707 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1708 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1715 foreach my $id (@plugins) {
1716 $index{state}{$id}={}; # used to detect disabled plugins
1717 foreach my $key (keys %{$wikistate{$id}}) {
1718 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1722 $index{version}="3";
1723 my $ret=Storable::nstore_fd(\%index, $out);
1724 return if ! defined $ret || ! $ret;
1725 close $out || error("failed saving to $newfile: $!", $cleanup);
1726 rename($newfile, "$config{wikistatedir}/indexdb") ||
1727 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1732 sub template_file ($) {
1735 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1737 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1738 $template=srcfile($pagesources{$tpage}, 1);
1742 $template=srcfile($tpage, 1);
1745 if (defined $template) {
1746 return $template, $tpage, 1 if wantarray;
1750 $name=~s:/::; # avoid path traversal
1751 foreach my $dir ($config{templatedir},
1752 "$installdir/share/ikiwiki/templates") {
1753 if (-e "$dir/$name") {
1754 $template="$dir/$name";
1758 if (defined $template) {
1759 return $template, $tpage if wantarray;
1767 sub template_depends ($$;@) {
1771 my ($filename, $tpage, $untrusted)=template_file($name);
1772 if (! defined $filename) {
1773 error(sprintf(gettext("template %s not found"), $name))
1776 if (defined $page && defined $tpage) {
1777 add_depends($page, $tpage);
1782 my $text_ref = shift;
1783 ${$text_ref} = decode_utf8(${$text_ref});
1785 loop_context_vars => 1,
1786 die_on_bad_params => 0,
1787 filename => $filename,
1789 ($untrusted ? (no_includes => 1) : ()),
1791 return @opts if wantarray;
1793 require HTML::Template;
1794 return HTML::Template->new(@opts);
1797 sub template ($;@) {
1798 template_depends(shift, undef, @_);
1801 sub misctemplate ($$;@) {
1806 my $template=template("page.tmpl");
1809 if (exists $params{page}) {
1810 $page=delete $params{page};
1812 run_hooks(pagetemplate => sub {
1816 template => $template,
1819 templateactions($template, "");
1824 wikiname => $config{wikiname},
1825 content => $content,
1826 baseurl => baseurl(),
1827 html5 => $config{html5},
1831 return $template->output;
1834 sub templateactions ($$) {
1840 run_hooks(pageactions => sub {
1841 push @actions, map { { action => $_ } }
1842 grep { defined } shift->(page => $page);
1844 $template->param(actions => \@actions);
1846 if ($config{cgiurl} && exists $hooks{auth}) {
1847 $template->param(prefsurl => cgiurl(do => "prefs"));
1851 if ($have_actions || @actions) {
1852 $template->param(have_actions => 1);
1859 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1860 error 'hook requires type, call, and id parameters';
1863 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1865 $hooks{$param{type}}{$param{id}}=\%param;
1869 sub run_hooks ($$) {
1870 # Calls the given sub for each hook of the given type,
1871 # passing it the hook function to call.
1875 if (exists $hooks{$type}) {
1876 my (@first, @middle, @last);
1877 foreach my $id (keys %{$hooks{$type}}) {
1878 if ($hooks{$type}{$id}{first}) {
1881 elsif ($hooks{$type}{$id}{last}) {
1888 foreach my $id (@first, @middle, @last) {
1889 $sub->($hooks{$type}{$id}{call});
1897 $hooks{rcs}{rcs_update}{call}->(@_);
1900 sub rcs_prepedit ($) {
1901 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1904 sub rcs_commit (@) {
1905 $hooks{rcs}{rcs_commit}{call}->(@_);
1908 sub rcs_commit_staged (@) {
1909 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1913 $hooks{rcs}{rcs_add}{call}->(@_);
1916 sub rcs_remove ($) {
1917 $hooks{rcs}{rcs_remove}{call}->(@_);
1920 sub rcs_rename ($$) {
1921 $hooks{rcs}{rcs_rename}{call}->(@_);
1924 sub rcs_recentchanges ($) {
1925 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1929 $hooks{rcs}{rcs_diff}{call}->(@_);
1932 sub rcs_getctime ($) {
1933 $hooks{rcs}{rcs_getctime}{call}->(@_);
1936 sub rcs_getmtime ($) {
1937 $hooks{rcs}{rcs_getmtime}{call}->(@_);
1940 sub rcs_receive () {
1941 $hooks{rcs}{rcs_receive}{call}->();
1944 sub rcs_preprevert (@) {
1945 $hooks{rcs}{rcs_preprevert}{call}->(@_);
1948 sub rcs_revert (@) {
1949 $hooks{rcs}{rcs_revert}{call}->(@_);
1952 sub rcs_showpatch (@) {
1953 $hooks{rcs}{rcs_showpatch}{call}->(@_);
1956 sub add_depends ($$;$) {
1959 my $deptype=shift || $DEPEND_CONTENT;
1961 # Is the pagespec a simple page name?
1962 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1963 $pagespec !~ /[\s*?()!]/) {
1964 $depends_simple{$page}{lc $pagespec} |= $deptype;
1968 # Add explicit dependencies for influences.
1969 my $sub=pagespec_translate($pagespec);
1970 return unless defined $sub;
1971 foreach my $p (keys %pagesources) {
1972 my $r=$sub->($p, location => $page);
1973 my $i=$r->influences;
1974 my $static=$r->influences_static;
1975 foreach my $k (keys %$i) {
1976 next unless $r || $static || $k eq $page;
1977 $depends_simple{$page}{lc $k} |= $i->{$k};
1982 $depends{$page}{$pagespec} |= $deptype;
1988 foreach my $type (@_) {
1989 if ($type eq 'presence') {
1990 $deptype |= $DEPEND_PRESENCE;
1992 elsif ($type eq 'links') {
1993 $deptype |= $DEPEND_LINKS;
1995 elsif ($type eq 'content') {
1996 $deptype |= $DEPEND_CONTENT;
2002 my $file_prune_regexp;
2003 sub file_pruned ($) {
2006 if (defined $config{include} && length $config{include}) {
2007 return 0 if $file =~ m/$config{include}/;
2010 if (! defined $file_prune_regexp) {
2011 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2012 $file_prune_regexp=qr/$file_prune_regexp/;
2014 return $file =~ m/$file_prune_regexp/;
2017 sub define_gettext () {
2018 # If translation is needed, redefine the gettext function to do it.
2019 # Otherwise, it becomes a quick no-op.
2022 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2023 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2024 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2026 $gettext_obj=eval q{
2027 use Locale::gettext q{textdomain};
2028 Locale::gettext->domain('ikiwiki')
2033 no warnings 'redefine';
2035 $getobj->() if $getobj;
2037 $gettext_obj->get(shift);
2044 $getobj->() if $getobj;
2046 $gettext_obj->nget(@_);
2049 return ($_[2] == 1 ? $_[0] : $_[1])
2067 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2071 # Injects a new function into the symbol table to replace an
2072 # exported function.
2075 # This is deep ugly perl foo, beware.
2078 if (! defined $params{parent}) {
2079 $params{parent}='::';
2080 $params{old}=\&{$params{name}};
2081 $params{name}=~s/.*:://;
2083 my $parent=$params{parent};
2084 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2085 $ns = $params{parent} . $ns;
2086 inject(%params, parent => $ns) unless $ns eq '::main::';
2087 *{$ns . $params{name}} = $params{call}
2088 if exists ${$ns}{$params{name}} &&
2089 \&{${$ns}{$params{name}}} == $params{old};
2095 sub add_link ($$;$) {
2100 push @{$links{$page}}, $link
2101 unless grep { $_ eq $link } @{$links{$page}};
2103 if (defined $type) {
2104 $typedlinks{$page}{$type}{$link} = 1;
2108 sub add_autofile ($$$) {
2111 my $generator=shift;
2113 $autofiles{$file}{plugin}=$plugin;
2114 $autofiles{$file}{generator}=$generator;
2117 sub sortspec_translate ($$) {
2119 my $reverse = shift;
2125 (-?) # group 1: perhaps negated
2128 \w+\([^\)]*\) # command(params)
2130 [^\s]+ # or anything else
2138 if ($word =~ m/^(\w+)\((.*)\)$/) {
2139 # command with parameters
2143 elsif ($word !~ m/^\w+$/) {
2144 error(sprintf(gettext("invalid sort type %s"), $word));
2155 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2156 if (defined $params) {
2157 push @data, $params;
2158 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2161 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2165 error(sprintf(gettext("unknown sort type %s"), $word));
2169 if (! length $code) {
2170 # undefined sorting method... sort arbitrarily
2179 return eval 'sub { '.$code.' }';
2182 sub pagespec_translate ($) {
2185 # Convert spec to perl code.
2189 \s* # ignore whitespace
2190 ( # 1: match a single word
2197 \w+\([^\)]*\) # command(params)
2199 [^\s()]+ # any other text
2201 \s* # ignore whitespace
2204 if (lc $word eq 'and') {
2207 elsif (lc $word eq 'or') {
2210 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2213 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2214 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2216 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2219 push @data, qq{unknown function in pagespec "$word"};
2220 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2225 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2229 if (! length $code) {
2230 $code="IkiWiki::FailReason->new('empty pagespec')";
2234 return eval 'sub { my $page=shift; '.$code.' }';
2237 sub pagespec_match ($$;@) {
2242 # Backwards compatability with old calling convention.
2244 unshift @params, 'location';
2247 my $sub=pagespec_translate($spec);
2248 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2250 return $sub->($page, @params);
2253 sub pagespec_match_list ($$;@) {
2258 # Backwards compatability with old calling convention.
2260 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2261 $params{list}=$page;
2262 $page=$params{location}; # ugh!
2265 my $sub=pagespec_translate($pagespec);
2266 error "syntax error in pagespec \"$pagespec\""
2268 my $sort=sortspec_translate($params{sort}, $params{reverse})
2269 if defined $params{sort};
2272 if (exists $params{list}) {
2273 @candidates=exists $params{filter}
2274 ? grep { ! $params{filter}->($_) } @{$params{list}}
2278 @candidates=exists $params{filter}
2279 ? grep { ! $params{filter}->($_) } keys %pagesources
2280 : keys %pagesources;
2283 # clear params, remainder is passed to pagespec
2284 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2285 my $num=$params{num};
2286 delete @params{qw{num deptype reverse sort filter list}};
2288 # when only the top matches will be returned, it's efficient to
2289 # sort before matching to pagespec,
2290 if (defined $num && defined $sort) {
2291 @candidates=IkiWiki::SortSpec::sort_pages(
2292 $sort, @candidates);
2298 my $accum=IkiWiki::SuccessReason->new();
2299 foreach my $p (@candidates) {
2300 my $r=$sub->($p, %params, location => $page);
2301 error(sprintf(gettext("cannot match pages: %s"), $r))
2302 if $r->isa("IkiWiki::ErrorReason");
2303 unless ($r || $r->influences_static) {
2304 $r->remove_influence($p);
2309 last if defined $num && ++$count == $num;
2313 # Add simple dependencies for accumulated influences.
2314 my $i=$accum->influences;
2315 foreach my $k (keys %$i) {
2316 $depends_simple{$page}{lc $k} |= $i->{$k};
2319 # when all matches will be returned, it's efficient to
2320 # sort after matching
2321 if (! defined $num && defined $sort) {
2322 return IkiWiki::SortSpec::sort_pages(
2330 sub pagespec_valid ($) {
2333 return defined pagespec_translate($spec);
2337 my $re=quotemeta(shift);
2343 package IkiWiki::FailReason;
2346 '""' => sub { $_[0][0] },
2348 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2349 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2350 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2354 our @ISA = 'IkiWiki::SuccessReason';
2356 package IkiWiki::SuccessReason;
2359 '""' => sub { $_[0][0] },
2361 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2362 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2363 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2370 return bless [$value, {@_}], $class;
2375 $this->[1]={@_} if @_;
2376 my %i=%{$this->[1]};
2381 sub influences_static {
2382 return ! $_[0][1]->{""};
2385 sub merge_influences {
2390 if (! $anded || (($this || %{$this->[1]}) &&
2391 ($other || %{$other->[1]}))) {
2392 foreach my $influence (keys %{$other->[1]}) {
2393 $this->[1]{$influence} |= $other->[1]{$influence};
2402 sub remove_influence {
2406 delete $this->[1]{$torm};
2409 package IkiWiki::ErrorReason;
2411 our @ISA = 'IkiWiki::FailReason';
2413 package IkiWiki::PageSpec;
2419 if ($path =~ m!^\.(/|$)!) {
2421 $from=~s#/?[^/]+$## if defined $from;
2423 $path="$from/$path" if defined $from && length $from;
2427 $path = "" unless defined $path;
2434 sub match_glob ($$;@) {
2439 $glob=derel($glob, $params{location});
2441 my $regexp=IkiWiki::glob2re($glob);
2442 if ($page=~/^$regexp$/i) {
2443 if (! IkiWiki::isinternal($page) || $params{internal}) {
2444 return IkiWiki::SuccessReason->new("$glob matches $page");
2447 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2451 return IkiWiki::FailReason->new("$glob does not match $page");
2455 sub match_internal ($$;@) {
2456 return match_glob(shift, shift, @_, internal => 1)
2459 sub match_page ($$;@) {
2461 my $match=match_glob($page, shift, @_);
2463 my $source=exists $IkiWiki::pagesources{$page} ?
2464 $IkiWiki::pagesources{$page} :
2465 $IkiWiki::delpagesources{$page};
2466 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2467 if (! defined $type) {
2468 return IkiWiki::FailReason->new("$page is not a page");
2474 sub match_link ($$;@) {
2479 $link=derel($link, $params{location});
2480 my $from=exists $params{location} ? $params{location} : '';
2481 my $linktype=$params{linktype};
2483 if (defined $linktype) {
2484 $qualifier=" with type $linktype";
2487 my $links = $IkiWiki::links{$page};
2488 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2489 unless $links && @{$links};
2490 my $bestlink = IkiWiki::bestlink($from, $link);
2491 foreach my $p (@{$links}) {
2492 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2494 if (length $bestlink) {
2495 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2496 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2500 if (match_glob($p, $link, %params)) {
2501 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2503 my ($p_rel)=$p=~/^\/?(.*)/;
2505 if (match_glob($p_rel, $link, %params)) {
2506 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2510 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2513 sub match_backlink ($$;@) {
2514 my $ret=match_link($_[1], $_[0], @_);
2515 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2519 sub match_created_before ($$;@) {
2524 $testpage=derel($testpage, $params{location});
2526 if (exists $IkiWiki::pagectime{$testpage}) {
2527 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2528 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2531 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2535 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2539 sub match_created_after ($$;@) {
2544 $testpage=derel($testpage, $params{location});
2546 if (exists $IkiWiki::pagectime{$testpage}) {
2547 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2548 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2551 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2555 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2559 sub match_creation_day ($$;@) {
2560 if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2561 return IkiWiki::SuccessReason->new('creation_day matched');
2564 return IkiWiki::FailReason->new('creation_day did not match');
2568 sub match_creation_month ($$;@) {
2569 if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2570 return IkiWiki::SuccessReason->new('creation_month matched');
2573 return IkiWiki::FailReason->new('creation_month did not match');
2577 sub match_creation_year ($$;@) {
2578 if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2579 return IkiWiki::SuccessReason->new('creation_year matched');
2582 return IkiWiki::FailReason->new('creation_year did not match');
2586 sub match_user ($$;@) {
2591 my $regexp=IkiWiki::glob2re($user);
2593 if (! exists $params{user}) {
2594 return IkiWiki::ErrorReason->new("no user specified");
2597 if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2598 return IkiWiki::SuccessReason->new("user is $user");
2600 elsif (! defined $params{user}) {
2601 return IkiWiki::FailReason->new("not logged in");
2604 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2608 sub match_admin ($$;@) {
2613 if (! exists $params{user}) {
2614 return IkiWiki::ErrorReason->new("no user specified");
2617 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2618 return IkiWiki::SuccessReason->new("user is an admin");
2620 elsif (! defined $params{user}) {
2621 return IkiWiki::FailReason->new("not logged in");
2624 return IkiWiki::FailReason->new("user is not an admin");
2628 sub match_ip ($$;@) {
2633 if (! exists $params{ip}) {
2634 return IkiWiki::ErrorReason->new("no IP specified");
2637 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2638 return IkiWiki::SuccessReason->new("IP is $ip");
2641 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2645 package IkiWiki::SortSpec;
2647 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2648 # are easily available in this namespace, for cmp functions to use them.
2655 IkiWiki::pagetitle(IkiWiki::basename($a))
2657 IkiWiki::pagetitle(IkiWiki::basename($b))
2660 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2661 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }