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 $test=dirname($test);
829 my $dir=dirname("$destdir/$file");
832 foreach my $s (split(m!/+!, $dir)) {
835 mkdir($d) || error("failed to create directory $d: $!");
843 sub writefile ($$$;$$) {
844 my $file=shift; # can include subdirs
845 my $destdir=shift; # directory to put file in
850 prep_writefile($file, $destdir);
852 my $newfile="$destdir/$file.ikiwiki-new";
854 error("cannot write to a symlink ($newfile)");
857 my $cleanup = sub { unlink($newfile) };
858 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
859 binmode($out) if ($binary);
861 $writer->(\*$out, $cleanup);
864 print $out $content or error("failed writing to $newfile: $!", $cleanup);
866 close $out || error("failed saving $newfile: $!", $cleanup);
867 rename($newfile, "$destdir/$file") ||
868 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
874 sub will_render ($$;$) {
879 # Important security check.
880 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
881 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
882 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
885 if (! $clear || $cleared{$page}) {
886 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
889 foreach my $old (@{$renderedfiles{$page}}) {
890 delete $destsources{$old};
892 $renderedfiles{$page}=[$dest];
895 $destsources{$dest}=$page;
905 if ($link=~s/^\/+//) {
913 $l.="/" if length $l;
916 if (exists $pagesources{$l}) {
919 elsif (exists $pagecase{lc $l}) {
920 return $pagecase{lc $l};
922 } while $cwd=~s{/?[^/]+$}{};
924 if (length $config{userdir}) {
925 my $l = "$config{userdir}/".lc($link);
926 if (exists $pagesources{$l}) {
929 elsif (exists $pagecase{lc $l}) {
930 return $pagecase{lc $l};
934 #print STDERR "warning: page $page, broken link: $link\n";
938 sub isinlinableimage ($) {
941 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
944 sub pagetitle ($;$) {
949 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
952 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
960 # support use w/o %config set
961 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
962 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
968 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
969 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
976 my $cgiurl=$config{cgiurl};
977 if (exists $params{cgiurl}) {
978 $cgiurl=$params{cgiurl};
979 delete $params{cgiurl};
982 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
988 return "$config{url}/" if ! defined $page;
990 $page=htmlpage($page);
992 $page=~s/[^\/]+\//..\//g;
997 # Work around very innefficient behavior in File::Spec if abs2rel
998 # is passed two relative paths. It's much faster if paths are
999 # absolute! (Debian bug #376658; fixed in debian unstable now)
1004 my $ret=File::Spec->abs2rel($path, $base);
1005 $ret=~s/^// if defined $ret;
1009 sub displaytime ($;$$) {
1010 # Plugins can override this function to mark up the time to
1012 my $time=formattime($_[0], $_[1]);
1013 if ($config{html5}) {
1014 return '<time datetime="'.date_3339($_[0]).'"'.
1015 ($_[2] ? ' pubdate="pubdate"' : '').
1016 '>'.$time.'</time>';
1019 return '<span class="date">'.$time.'</span>';
1023 sub formattime ($;$) {
1024 # Plugins can override this function to format the time.
1027 if (! defined $format) {
1028 $format=$config{timeformat};
1031 # strftime doesn't know about encodings, so make sure
1032 # its output is properly treated as utf8
1033 return decode_utf8(POSIX::strftime($format, localtime($time)));
1039 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1040 POSIX::setlocale(&POSIX::LC_TIME, "C");
1041 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1042 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1046 sub beautify_urlpath ($) {
1049 # Ensure url is not an empty link, and if necessary,
1050 # add ./ to avoid colon confusion.
1051 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1055 if ($config{usedirs}) {
1056 $url =~ s!/index.$config{htmlext}$!/!;
1068 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1071 if (! $destsources{$to}) {
1076 return $config{url}.beautify_urlpath("/".$to);
1079 my $link = abs2rel($to, dirname(htmlpage($from)));
1081 return beautify_urlpath($link);
1084 sub htmllink ($$$;@) {
1085 my $lpage=shift; # the page doing the linking
1086 my $page=shift; # the page that will contain the link (different for inline)
1093 if (! $opts{forcesubpage}) {
1094 $bestlink=bestlink($lpage, $link);
1097 $bestlink="$lpage/".lc($link);
1101 if (defined $opts{linktext}) {
1102 $linktext=$opts{linktext};
1105 $linktext=pagetitle(basename($link));
1108 return "<span class=\"selflink\">$linktext</span>"
1109 if length $bestlink && $page eq $bestlink &&
1110 ! defined $opts{anchor};
1112 if (! $destsources{$bestlink}) {
1113 $bestlink=htmlpage($bestlink);
1115 if (! $destsources{$bestlink}) {
1117 if (length $config{cgiurl}) {
1118 $cgilink = "<a href=\"".
1123 )."\" rel=\"nofollow\">?</a>";
1125 return "<span class=\"createlink\">$cgilink$linktext</span>"
1129 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1130 $bestlink=beautify_urlpath($bestlink);
1132 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1133 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1136 if (defined $opts{anchor}) {
1137 $bestlink.="#".$opts{anchor};
1141 foreach my $attr (qw{rel class title}) {
1142 if (defined $opts{$attr}) {
1143 push @attrs, " $attr=\"$opts{$attr}\"";
1147 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1152 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1155 sub openiduser ($) {
1158 if ($user =~ m!^https?://! &&
1159 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1162 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1163 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1166 # backcompat with old version
1167 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1168 $display=$oid->display;
1171 # Convert "user.somehost.com" to "user [somehost.com]"
1172 # (also "user.somehost.co.uk")
1173 if ($display !~ /\[/) {
1174 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1176 # Convert "http://somehost.com/user" to "user [somehost.com]".
1177 # (also "https://somehost.com/user/")
1178 if ($display !~ /\[/) {
1179 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1181 $display=~s!^https?://!!; # make sure this is removed
1182 eval q{use CGI 'escapeHTML'};
1184 return escapeHTML($display);
1189 sub htmlize ($$$$) {
1195 my $oneline = $content !~ /\n/;
1197 if (exists $hooks{htmlize}{$type}) {
1198 $content=$hooks{htmlize}{$type}{call}->(
1200 content => $content,
1204 error("htmlization of $type not supported");
1207 run_hooks(sanitize => sub {
1210 destpage => $destpage,
1211 content => $content,
1216 # hack to get rid of enclosing junk added by markdown
1217 # and other htmlizers/sanitizers
1218 $content=~s/^<p>//i;
1219 $content=~s/<\/p>\n*$//i;
1230 run_hooks(linkify => sub {
1233 destpage => $destpage,
1234 content => $content,
1242 our $preprocess_preview=0;
1243 sub preprocess ($$$;$$) {
1244 my $page=shift; # the page the data comes from
1245 my $destpage=shift; # the page the data will appear in (different for inline)
1250 # Using local because it needs to be set within any nested calls
1252 local $preprocess_preview=$preview if defined $preview;
1259 $params="" if ! defined $params;
1261 if (length $escape) {
1262 return "[[$prefix$command $params]]";
1264 elsif (exists $hooks{preprocess}{$command}) {
1265 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1266 # Note: preserve order of params, some plugins may
1267 # consider it significant.
1269 while ($params =~ m{
1270 (?:([-\w]+)=)? # 1: named parameter key?
1272 """(.*?)""" # 2: triple-quoted value
1274 "([^"]*?)" # 3: single-quoted value
1276 (\S+) # 4: unquoted value
1278 (?:\s+|$) # delimiter to next param
1288 elsif (defined $3) {
1291 elsif (defined $4) {
1296 push @params, $key, $val;
1299 push @params, $val, '';
1302 if ($preprocessing{$page}++ > 3) {
1303 # Avoid loops of preprocessed pages preprocessing
1304 # other pages that preprocess them, etc.
1305 return "[[!$command <span class=\"error\">".
1306 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1307 $page, $preprocessing{$page}).
1313 $hooks{preprocess}{$command}{call}->(
1316 destpage => $destpage,
1317 preview => $preprocess_preview,
1323 $ret="[[!$command <span class=\"error\">".
1324 gettext("Error").": $error"."</span>]]";
1328 # use void context during scan pass
1330 $hooks{preprocess}{$command}{call}->(
1333 destpage => $destpage,
1334 preview => $preprocess_preview,
1339 $preprocessing{$page}--;
1343 return "[[$prefix$command $params]]";
1348 if ($config{prefix_directives}) {
1351 \[\[(!) # directive open; 2: prefix
1352 ([-\w]+) # 3: command
1353 ( # 4: the parameters..
1354 \s+ # Must have space if parameters present
1356 (?:[-\w]+=)? # named parameter key?
1358 """.*?""" # triple-quoted value
1360 "[^"]*?" # single-quoted value
1362 [^"\s\]]+ # unquoted value
1364 \s* # whitespace or end
1367 *)? # 0 or more parameters
1368 \]\] # directive closed
1374 \[\[(!?) # directive open; 2: optional prefix
1375 ([-\w]+) # 3: command
1377 ( # 4: the parameters..
1379 (?:[-\w]+=)? # named parameter key?
1381 """.*?""" # triple-quoted value
1383 "[^"]*?" # single-quoted value
1385 [^"\s\]]+ # unquoted value
1387 \s* # whitespace or end
1390 *) # 0 or more parameters
1391 \]\] # directive closed
1395 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1404 run_hooks(filter => sub {
1405 $content=shift->(page => $page, destpage => $destpage,
1406 content => $content);
1412 sub check_canedit ($$$;$) {
1419 run_hooks(canedit => sub {
1420 return if defined $canedit;
1421 my $ret=shift->($page, $q, $session);
1426 elsif (ref $ret eq 'CODE') {
1427 $ret->() unless $nonfatal;
1430 elsif (defined $ret) {
1431 error($ret) unless $nonfatal;
1436 return defined $canedit ? $canedit : 1;
1439 sub check_content (@) {
1442 return 1 if ! exists $hooks{checkcontent}; # optimisation
1444 if (exists $pagesources{$params{page}}) {
1446 my %old=map { $_ => 1 }
1447 split("\n", readfile(srcfile($pagesources{$params{page}})));
1448 foreach my $line (split("\n", $params{content})) {
1449 push @diff, $line if ! exists $old{$line};
1451 $params{diff}=join("\n", @diff);
1455 run_hooks(checkcontent => sub {
1456 return if defined $ok;
1457 my $ret=shift->(%params);
1462 elsif (ref $ret eq 'CODE') {
1463 $ret->() unless $params{nonfatal};
1466 elsif (defined $ret) {
1467 error($ret) unless $params{nonfatal};
1473 return defined $ok ? $ok : 1;
1479 # Take an exclusive lock on the wiki to prevent multiple concurrent
1480 # run issues. The lock will be dropped on program exit.
1481 if (! -d $config{wikistatedir}) {
1482 mkdir($config{wikistatedir});
1484 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1485 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1486 if (! flock($wikilock, 2)) { # LOCK_EX
1487 error("failed to get lock");
1493 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1494 return close($wikilock) if $wikilock;
1500 sub commit_hook_enabled () {
1501 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1502 error("cannot write to $config{wikistatedir}/commitlock: $!");
1503 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1504 close($commitlock) || error("failed closing commitlock: $!");
1507 close($commitlock) || error("failed closing commitlock: $!");
1511 sub disable_commit_hook () {
1512 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1513 error("cannot write to $config{wikistatedir}/commitlock: $!");
1514 if (! flock($commitlock, 2)) { # LOCK_EX
1515 error("failed to get commit lock");
1520 sub enable_commit_hook () {
1521 return close($commitlock) if $commitlock;
1526 %oldrenderedfiles=%pagectime=();
1527 if (! $config{rebuild}) {
1528 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1529 %destsources=%renderedfiles=%pagecase=%pagestate=
1530 %depends_simple=%typedlinks=%oldtypedlinks=();
1533 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1534 if (-e "$config{wikistatedir}/index") {
1535 system("ikiwiki-transition", "indexdb", $config{srcdir});
1536 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1539 $config{gettime}=1; # first build
1544 my $index=Storable::fd_retrieve($in);
1545 if (! defined $index) {
1550 if (exists $index->{version} && ! ref $index->{version}) {
1551 $pages=$index->{page};
1552 %wikistate=%{$index->{state}};
1559 foreach my $src (keys %$pages) {
1560 my $d=$pages->{$src};
1561 my $page=pagename($src);
1562 $pagectime{$page}=$d->{ctime};
1563 $pagesources{$page}=$src;
1564 if (! $config{rebuild}) {
1565 $pagemtime{$page}=$d->{mtime};
1566 $renderedfiles{$page}=$d->{dest};
1567 if (exists $d->{links} && ref $d->{links}) {
1568 $links{$page}=$d->{links};
1569 $oldlinks{$page}=[@{$d->{links}}];
1571 if (ref $d->{depends_simple} eq 'ARRAY') {
1573 $depends_simple{$page}={
1574 map { $_ => 1 } @{$d->{depends_simple}}
1577 elsif (exists $d->{depends_simple}) {
1578 $depends_simple{$page}=$d->{depends_simple};
1580 if (exists $d->{dependslist}) {
1583 map { $_ => $DEPEND_CONTENT }
1584 @{$d->{dependslist}}
1587 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1589 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1591 elsif (exists $d->{depends}) {
1592 $depends{$page}=$d->{depends};
1594 if (exists $d->{state}) {
1595 $pagestate{$page}=$d->{state};
1597 if (exists $d->{typedlinks}) {
1598 $typedlinks{$page}=$d->{typedlinks};
1600 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1601 next unless %$links;
1602 $oldtypedlinks{$page}{$type} = {%$links};
1606 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1608 foreach my $page (keys %pagesources) {
1609 $pagecase{lc $page}=$page;
1611 foreach my $page (keys %renderedfiles) {
1612 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1618 run_hooks(savestate => sub { shift->() });
1621 foreach my $type (keys %hooks) {
1622 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1624 my @hookids=keys %hookids;
1626 if (! -d $config{wikistatedir}) {
1627 mkdir($config{wikistatedir});
1629 my $newfile="$config{wikistatedir}/indexdb.new";
1630 my $cleanup = sub { unlink($newfile) };
1631 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1634 foreach my $page (keys %pagemtime) {
1635 next unless $pagemtime{$page};
1636 my $src=$pagesources{$page};
1638 $index{page}{$src}={
1639 ctime => $pagectime{$page},
1640 mtime => $pagemtime{$page},
1641 dest => $renderedfiles{$page},
1642 links => $links{$page},
1645 if (exists $depends{$page}) {
1646 $index{page}{$src}{depends} = $depends{$page};
1649 if (exists $depends_simple{$page}) {
1650 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1653 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1654 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1657 if (exists $pagestate{$page}) {
1658 foreach my $id (@hookids) {
1659 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1660 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1667 foreach my $id (@hookids) {
1668 foreach my $key (keys %{$wikistate{$id}}) {
1669 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1673 $index{version}="3";
1674 my $ret=Storable::nstore_fd(\%index, $out);
1675 return if ! defined $ret || ! $ret;
1676 close $out || error("failed saving to $newfile: $!", $cleanup);
1677 rename($newfile, "$config{wikistatedir}/indexdb") ||
1678 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1683 sub template_file ($) {
1686 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1687 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1688 $tpage=$pagesources{$tpage};
1692 my $template=srcfile($tpage, 1);
1693 if (defined $template) {
1694 return $template, $tpage, 1 if wantarray;
1698 $name=~s:/::; # avoid path traversal
1699 foreach my $dir ($config{templatedir},
1700 "$installdir/share/ikiwiki/templates") {
1701 if (-e "$dir/$name") {
1702 $template="$dir/$name";
1706 if (defined $template) {
1707 return $template, $tpage if wantarray;
1715 sub template_depends ($$;@) {
1719 my ($filename, $tpage, $untrusted)=template_file($name);
1720 if (defined $page && defined $tpage) {
1721 add_depends($page, $tpage);
1724 return unless defined $filename;
1728 my $text_ref = shift;
1729 ${$text_ref} = decode_utf8(${$text_ref});
1731 loop_context_vars => 1,
1732 die_on_bad_params => 0,
1733 filename => $filename,
1735 ($untrusted ? (no_includes => 1) : ()),
1737 return @opts if wantarray;
1739 require HTML::Template;
1740 return HTML::Template->new(@opts);
1743 sub template ($;@) {
1744 template_depends(shift, undef, @_);
1747 sub misctemplate ($$;@) {
1752 my $template=template("page.tmpl");
1755 if (exists $params{page}) {
1756 $page=delete $params{page};
1758 run_hooks(pagetemplate => sub {
1762 template => $template,
1765 templateactions($template, "");
1770 wikiname => $config{wikiname},
1771 content => $content,
1772 baseurl => baseurl(),
1773 html5 => $config{html5},
1777 return $template->output;
1780 sub templateactions ($$) {
1786 run_hooks(pageactions => sub {
1787 push @actions, map { { action => $_ } }
1788 grep { defined } shift->(page => $page);
1790 $template->param(actions => \@actions);
1792 if ($config{cgiurl} && exists $hooks{auth}) {
1793 $template->param(prefsurl => cgiurl(do => "prefs"));
1797 if ($have_actions || @actions) {
1798 $template->param(have_actions => 1);
1805 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1806 error 'hook requires type, call, and id parameters';
1809 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1811 $hooks{$param{type}}{$param{id}}=\%param;
1815 sub run_hooks ($$) {
1816 # Calls the given sub for each hook of the given type,
1817 # passing it the hook function to call.
1821 if (exists $hooks{$type}) {
1822 my (@first, @middle, @last);
1823 foreach my $id (keys %{$hooks{$type}}) {
1824 if ($hooks{$type}{$id}{first}) {
1827 elsif ($hooks{$type}{$id}{last}) {
1834 foreach my $id (@first, @middle, @last) {
1835 $sub->($hooks{$type}{$id}{call});
1843 $hooks{rcs}{rcs_update}{call}->(@_);
1846 sub rcs_prepedit ($) {
1847 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1850 sub rcs_commit (@) {
1851 $hooks{rcs}{rcs_commit}{call}->(@_);
1854 sub rcs_commit_staged (@) {
1855 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1859 $hooks{rcs}{rcs_add}{call}->(@_);
1862 sub rcs_remove ($) {
1863 $hooks{rcs}{rcs_remove}{call}->(@_);
1866 sub rcs_rename ($$) {
1867 $hooks{rcs}{rcs_rename}{call}->(@_);
1870 sub rcs_recentchanges ($) {
1871 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1875 $hooks{rcs}{rcs_diff}{call}->(@_);
1878 sub rcs_getctime ($) {
1879 $hooks{rcs}{rcs_getctime}{call}->(@_);
1882 sub rcs_getmtime ($) {
1883 $hooks{rcs}{rcs_getmtime}{call}->(@_);
1886 sub rcs_receive () {
1887 $hooks{rcs}{rcs_receive}{call}->();
1890 sub add_depends ($$;$) {
1893 my $deptype=shift || $DEPEND_CONTENT;
1895 # Is the pagespec a simple page name?
1896 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1897 $pagespec !~ /[\s*?()!]/) {
1898 $depends_simple{$page}{lc $pagespec} |= $deptype;
1902 # Add explicit dependencies for influences.
1903 my $sub=pagespec_translate($pagespec);
1904 return unless defined $sub;
1905 foreach my $p (keys %pagesources) {
1906 my $r=$sub->($p, location => $page);
1907 my $i=$r->influences;
1908 my $static=$r->influences_static;
1909 foreach my $k (keys %$i) {
1910 next unless $r || $static || $k eq $page;
1911 $depends_simple{$page}{lc $k} |= $i->{$k};
1916 $depends{$page}{$pagespec} |= $deptype;
1922 foreach my $type (@_) {
1923 if ($type eq 'presence') {
1924 $deptype |= $DEPEND_PRESENCE;
1926 elsif ($type eq 'links') {
1927 $deptype |= $DEPEND_LINKS;
1929 elsif ($type eq 'content') {
1930 $deptype |= $DEPEND_CONTENT;
1936 my $file_prune_regexp;
1937 sub file_pruned ($) {
1940 if (defined $config{include} && length $config{include}) {
1941 return 0 if $file =~ m/$config{include}/;
1944 if (! defined $file_prune_regexp) {
1945 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1946 $file_prune_regexp=qr/$file_prune_regexp/;
1948 return $file =~ m/$file_prune_regexp/;
1951 sub define_gettext () {
1952 # If translation is needed, redefine the gettext function to do it.
1953 # Otherwise, it becomes a quick no-op.
1956 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1957 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1958 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1960 $gettext_obj=eval q{
1961 use Locale::gettext q{textdomain};
1962 Locale::gettext->domain('ikiwiki')
1967 no warnings 'redefine';
1969 $getobj->() if $getobj;
1971 $gettext_obj->get(shift);
1978 $getobj->() if $getobj;
1980 $gettext_obj->nget(@_);
1983 return ($_[2] == 1 ? $_[0] : $_[1])
2001 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2005 # Injects a new function into the symbol table to replace an
2006 # exported function.
2009 # This is deep ugly perl foo, beware.
2012 if (! defined $params{parent}) {
2013 $params{parent}='::';
2014 $params{old}=\&{$params{name}};
2015 $params{name}=~s/.*:://;
2017 my $parent=$params{parent};
2018 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2019 $ns = $params{parent} . $ns;
2020 inject(%params, parent => $ns) unless $ns eq '::main::';
2021 *{$ns . $params{name}} = $params{call}
2022 if exists ${$ns}{$params{name}} &&
2023 \&{${$ns}{$params{name}}} == $params{old};
2029 sub add_link ($$;$) {
2034 push @{$links{$page}}, $link
2035 unless grep { $_ eq $link } @{$links{$page}};
2037 if (defined $type) {
2038 $typedlinks{$page}{$type}{$link} = 1;
2042 sub add_autofile ($$$) {
2045 my $generator=shift;
2047 $autofiles{$file}{plugin}=$plugin;
2048 $autofiles{$file}{generator}=$generator;
2051 sub sortspec_translate ($$) {
2053 my $reverse = shift;
2059 (-?) # group 1: perhaps negated
2062 \w+\([^\)]*\) # command(params)
2064 [^\s]+ # or anything else
2072 if ($word =~ m/^(\w+)\((.*)\)$/) {
2073 # command with parameters
2077 elsif ($word !~ m/^\w+$/) {
2078 error(sprintf(gettext("invalid sort type %s"), $word));
2089 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2090 if (defined $params) {
2091 push @data, $params;
2092 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2095 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2099 error(sprintf(gettext("unknown sort type %s"), $word));
2103 if (! length $code) {
2104 # undefined sorting method... sort arbitrarily
2113 return eval 'sub { '.$code.' }';
2116 sub pagespec_translate ($) {
2119 # Convert spec to perl code.
2123 \s* # ignore whitespace
2124 ( # 1: match a single word
2131 \w+\([^\)]*\) # command(params)
2133 [^\s()]+ # any other text
2135 \s* # ignore whitespace
2138 if (lc $word eq 'and') {
2141 elsif (lc $word eq 'or') {
2144 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2147 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2148 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2150 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2153 push @data, qq{unknown function in pagespec "$word"};
2154 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2159 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2163 if (! length $code) {
2164 $code="IkiWiki::FailReason->new('empty pagespec')";
2168 return eval 'sub { my $page=shift; '.$code.' }';
2171 sub pagespec_match ($$;@) {
2176 # Backwards compatability with old calling convention.
2178 unshift @params, 'location';
2181 my $sub=pagespec_translate($spec);
2182 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2184 return $sub->($page, @params);
2187 sub pagespec_match_list ($$;@) {
2192 # Backwards compatability with old calling convention.
2194 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2195 $params{list}=$page;
2196 $page=$params{location}; # ugh!
2199 my $sub=pagespec_translate($pagespec);
2200 error "syntax error in pagespec \"$pagespec\""
2202 my $sort=sortspec_translate($params{sort}, $params{reverse})
2203 if defined $params{sort};
2206 if (exists $params{list}) {
2207 @candidates=exists $params{filter}
2208 ? grep { ! $params{filter}->($_) } @{$params{list}}
2212 @candidates=exists $params{filter}
2213 ? grep { ! $params{filter}->($_) } keys %pagesources
2214 : keys %pagesources;
2217 # clear params, remainder is passed to pagespec
2218 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2219 my $num=$params{num};
2220 delete @params{qw{num deptype reverse sort filter list}};
2222 # when only the top matches will be returned, it's efficient to
2223 # sort before matching to pagespec,
2224 if (defined $num && defined $sort) {
2225 @candidates=IkiWiki::SortSpec::sort_pages(
2226 $sort, @candidates);
2232 my $accum=IkiWiki::SuccessReason->new();
2233 foreach my $p (@candidates) {
2234 my $r=$sub->($p, %params, location => $page);
2235 error(sprintf(gettext("cannot match pages: %s"), $r))
2236 if $r->isa("IkiWiki::ErrorReason");
2237 unless ($r || $r->influences_static) {
2238 $r->remove_influence($p);
2243 last if defined $num && ++$count == $num;
2247 # Add simple dependencies for accumulated influences.
2248 my $i=$accum->influences;
2249 foreach my $k (keys %$i) {
2250 $depends_simple{$page}{lc $k} |= $i->{$k};
2253 # when all matches will be returned, it's efficient to
2254 # sort after matching
2255 if (! defined $num && defined $sort) {
2256 return IkiWiki::SortSpec::sort_pages(
2264 sub pagespec_valid ($) {
2267 return defined pagespec_translate($spec);
2271 my $re=quotemeta(shift);
2277 package IkiWiki::FailReason;
2280 '""' => sub { $_[0][0] },
2282 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2283 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2284 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2288 our @ISA = 'IkiWiki::SuccessReason';
2290 package IkiWiki::SuccessReason;
2293 '""' => sub { $_[0][0] },
2295 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2296 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2297 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2304 return bless [$value, {@_}], $class;
2309 $this->[1]={@_} if @_;
2310 my %i=%{$this->[1]};
2315 sub influences_static {
2316 return ! $_[0][1]->{""};
2319 sub merge_influences {
2324 if (! $anded || (($this || %{$this->[1]}) &&
2325 ($other || %{$other->[1]}))) {
2326 foreach my $influence (keys %{$other->[1]}) {
2327 $this->[1]{$influence} |= $other->[1]{$influence};
2336 sub remove_influence {
2340 delete $this->[1]{$torm};
2343 package IkiWiki::ErrorReason;
2345 our @ISA = 'IkiWiki::FailReason';
2347 package IkiWiki::PageSpec;
2353 if ($path =~ m!^\./!) {
2354 $from=~s#/?[^/]+$## if defined $from;
2356 $path="$from/$path" if defined $from && length $from;
2362 sub match_glob ($$;@) {
2367 $glob=derel($glob, $params{location});
2369 my $regexp=IkiWiki::glob2re($glob);
2370 if ($page=~/^$regexp$/i) {
2371 if (! IkiWiki::isinternal($page) || $params{internal}) {
2372 return IkiWiki::SuccessReason->new("$glob matches $page");
2375 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2379 return IkiWiki::FailReason->new("$glob does not match $page");
2383 sub match_internal ($$;@) {
2384 return match_glob(shift, shift, @_, internal => 1)
2387 sub match_page ($$;@) {
2389 my $match=match_glob($page, shift, @_);
2390 if ($match && ! (exists $IkiWiki::pagesources{$page}
2391 && defined IkiWiki::pagetype($IkiWiki::pagesources{$page}))) {
2392 return IkiWiki::FailReason->new("$page is not a page");
2399 sub match_link ($$;@) {
2404 $link=derel($link, $params{location});
2405 my $from=exists $params{location} ? $params{location} : '';
2406 my $linktype=$params{linktype};
2408 if (defined $linktype) {
2409 $qualifier=" with type $linktype";
2412 my $links = $IkiWiki::links{$page};
2413 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2414 unless $links && @{$links};
2415 my $bestlink = IkiWiki::bestlink($from, $link);
2416 foreach my $p (@{$links}) {
2417 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2419 if (length $bestlink) {
2420 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2421 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2425 if (match_glob($p, $link, %params)) {
2426 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2428 my ($p_rel)=$p=~/^\/?(.*)/;
2430 if (match_glob($p_rel, $link, %params)) {
2431 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2435 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2438 sub match_backlink ($$;@) {
2439 my $ret=match_link($_[1], $_[0], @_);
2440 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2444 sub match_created_before ($$;@) {
2449 $testpage=derel($testpage, $params{location});
2451 if (exists $IkiWiki::pagectime{$testpage}) {
2452 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2453 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2456 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2460 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2464 sub match_created_after ($$;@) {
2469 $testpage=derel($testpage, $params{location});
2471 if (exists $IkiWiki::pagectime{$testpage}) {
2472 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2473 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2476 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2480 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2484 sub match_creation_day ($$;@) {
2485 if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2486 return IkiWiki::SuccessReason->new('creation_day matched');
2489 return IkiWiki::FailReason->new('creation_day did not match');
2493 sub match_creation_month ($$;@) {
2494 if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2495 return IkiWiki::SuccessReason->new('creation_month matched');
2498 return IkiWiki::FailReason->new('creation_month did not match');
2502 sub match_creation_year ($$;@) {
2503 if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2504 return IkiWiki::SuccessReason->new('creation_year matched');
2507 return IkiWiki::FailReason->new('creation_year did not match');
2511 sub match_user ($$;@) {
2516 my $regexp=IkiWiki::glob2re($user);
2518 if (! exists $params{user}) {
2519 return IkiWiki::ErrorReason->new("no user specified");
2522 if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2523 return IkiWiki::SuccessReason->new("user is $user");
2525 elsif (! defined $params{user}) {
2526 return IkiWiki::FailReason->new("not logged in");
2529 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2533 sub match_admin ($$;@) {
2538 if (! exists $params{user}) {
2539 return IkiWiki::ErrorReason->new("no user specified");
2542 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2543 return IkiWiki::SuccessReason->new("user is an admin");
2545 elsif (! defined $params{user}) {
2546 return IkiWiki::FailReason->new("not logged in");
2549 return IkiWiki::FailReason->new("user is not an admin");
2553 sub match_ip ($$;@) {
2558 if (! exists $params{ip}) {
2559 return IkiWiki::ErrorReason->new("no IP specified");
2562 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2563 return IkiWiki::SuccessReason->new("IP is $ip");
2566 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2570 package IkiWiki::SortSpec;
2572 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2573 # are easily available in this namespace, for cmp functions to use them.
2580 IkiWiki::pagetitle(IkiWiki::basename($a))
2582 IkiWiki::pagetitle(IkiWiki::basename($b))
2585 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2586 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }