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",
446 description => "running in gettime mode",
453 description => "running in w3mmode",
460 description => "path to the .ikiwiki directory holding ikiwiki state",
467 description => "path to setup file",
473 default => "Standard",
474 description => "perl class to use to dump setup file",
478 allow_symlinks_before_srcdir => {
481 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
487 sub defaultconfig () {
490 foreach my $key (keys %s) {
491 push @ret, $key, $s{$key}->{default};
498 # locale stuff; avoid LC_ALL since it overrides everything
499 if (defined $ENV{LC_ALL}) {
500 $ENV{LANG} = $ENV{LC_ALL};
503 if (defined $config{locale}) {
504 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
505 $ENV{LANG}=$config{locale};
510 if (! defined $config{wiki_file_regexp}) {
511 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
514 if (ref $config{ENV} eq 'HASH') {
515 foreach my $val (keys %{$config{ENV}}) {
516 $ENV{$val}=$config{ENV}{$val};
520 if ($config{w3mmode}) {
521 eval q{use Cwd q{abs_path}};
523 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
524 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
525 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
526 unless $config{cgiurl} =~ m!file:///!;
527 $config{url}="file://".$config{destdir};
530 if ($config{cgi} && ! length $config{url}) {
531 error(gettext("Must specify url to wiki with --url when using --cgi"));
534 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
535 unless exists $config{wikistatedir} && defined $config{wikistatedir};
537 if (defined $config{umask}) {
538 umask(possibly_foolish_untaint($config{umask}));
541 run_hooks(checkconfig => sub { shift->() });
549 foreach my $dir (@INC, $config{libdir}) {
550 next unless defined $dir && length $dir;
551 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
552 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
556 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
557 next unless defined $dir && length $dir;
558 foreach my $file (glob("$dir/plugins/*")) {
559 $ret{basename($file)}=1 if -x $file;
567 if (defined $config{libdir} && length $config{libdir}) {
568 unshift @INC, possibly_foolish_untaint($config{libdir});
571 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
576 if (exists $hooks{rcs}) {
577 error(gettext("cannot use multiple rcs plugins"));
579 loadplugin($config{rcs});
581 if (! exists $hooks{rcs}) {
585 run_hooks(getopt => sub { shift->() });
586 if (grep /^-/, @ARGV) {
587 print STDERR "Unknown option (or missing parameter): $_\n"
588 foreach grep /^-/, @ARGV;
598 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
600 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
601 "$installdir/lib/ikiwiki") {
602 if (defined $dir && -x "$dir/plugins/$plugin") {
603 eval { require IkiWiki::Plugin::external };
606 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
608 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
609 $loaded_plugins{$plugin}=1;
614 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
617 error("Failed to load plugin $mod: $@");
619 $loaded_plugins{$plugin}=1;
626 log_message('err' => $message) if $config{syslog};
627 if (defined $cleaner) {
634 return unless $config{verbose};
635 return log_message(debug => @_);
639 sub log_message ($$) {
642 if ($config{syslog}) {
645 Sys::Syslog::setlogsock('unix');
646 Sys::Syslog::openlog('ikiwiki', '', 'user');
650 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
653 elsif (! $config{cgi}) {
657 return print STDERR "@_\n";
661 sub possibly_foolish_untaint ($) {
663 my ($untainted)=$tainted=~/(.*)/s;
683 return exists $pagesources{$page} &&
684 $pagesources{$page} =~ /\._([^.]+)$/;
690 if ($file =~ /\.([^.]+)$/) {
691 return $1 if exists $hooks{htmlize}{$1};
693 my $base=basename($file);
694 if (exists $hooks{htmlize}{$base} &&
695 $hooks{htmlize}{$base}{noextension}) {
706 if (exists $pagename_cache{$file}) {
707 return $pagename_cache{$file};
710 my $type=pagetype($file);
712 $page=~s/\Q.$type\E*$//
713 if defined $type && !$hooks{htmlize}{$type}{keepextension}
714 && !$hooks{htmlize}{$type}{noextension};
715 if ($config{indexpages} && $page=~/(.*)\/index$/) {
719 $pagename_cache{$file} = $page;
723 sub newpagefile ($$) {
727 if (! $config{indexpages} || $page eq 'index') {
728 return $page.".".$type;
731 return $page."/index.".$type;
735 sub targetpage ($$;$) {
740 if (defined $filename) {
741 return $page."/".$filename.".".$ext;
743 elsif (! $config{usedirs} || $page eq 'index') {
744 return $page.".".$ext;
747 return $page."/index.".$ext;
754 return targetpage($page, $config{htmlext});
761 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
762 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
763 return "$dir/$file", stat(_) if -e "$dir/$file";
765 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
770 return (srcfile_stat(@_))[0];
773 sub add_underlay ($) {
777 $dir="$config{underlaydirbase}/$dir";
780 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
781 unshift @{$config{underlaydirs}}, $dir;
787 sub readfile ($;$$) {
793 error("cannot read a symlink ($file)");
797 open (my $in, "<", $file) || error("failed to read $file: $!");
798 binmode($in) if ($binary);
799 return \*$in if $wantfd;
801 # check for invalid utf-8, and toss it back to avoid crashes
802 if (! utf8::valid($ret)) {
803 $ret=encode_utf8($ret);
805 close $in || error("failed to read $file: $!");
809 sub prep_writefile ($$) {
814 while (length $test) {
815 if (-l "$destdir/$test") {
816 error("cannot write to a symlink ($test)");
818 $test=dirname($test);
821 my $dir=dirname("$destdir/$file");
824 foreach my $s (split(m!/+!, $dir)) {
827 mkdir($d) || error("failed to create directory $d: $!");
835 sub writefile ($$$;$$) {
836 my $file=shift; # can include subdirs
837 my $destdir=shift; # directory to put file in
842 prep_writefile($file, $destdir);
844 my $newfile="$destdir/$file.ikiwiki-new";
846 error("cannot write to a symlink ($newfile)");
849 my $cleanup = sub { unlink($newfile) };
850 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
851 binmode($out) if ($binary);
853 $writer->(\*$out, $cleanup);
856 print $out $content or error("failed writing to $newfile: $!", $cleanup);
858 close $out || error("failed saving $newfile: $!", $cleanup);
859 rename($newfile, "$destdir/$file") ||
860 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
866 sub will_render ($$;$) {
871 # Important security check.
872 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
873 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
874 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
877 if (! $clear || $cleared{$page}) {
878 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
881 foreach my $old (@{$renderedfiles{$page}}) {
882 delete $destsources{$old};
884 $renderedfiles{$page}=[$dest];
887 $destsources{$dest}=$page;
897 if ($link=~s/^\/+//) {
905 $l.="/" if length $l;
908 if (exists $pagesources{$l}) {
911 elsif (exists $pagecase{lc $l}) {
912 return $pagecase{lc $l};
914 } while $cwd=~s{/?[^/]+$}{};
916 if (length $config{userdir}) {
917 my $l = "$config{userdir}/".lc($link);
918 if (exists $pagesources{$l}) {
921 elsif (exists $pagecase{lc $l}) {
922 return $pagecase{lc $l};
926 #print STDERR "warning: page $page, broken link: $link\n";
930 sub isinlinableimage ($) {
933 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
936 sub pagetitle ($;$) {
941 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
944 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
952 # support use w/o %config set
953 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
954 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
960 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
961 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
968 my $cgiurl=$config{cgiurl};
969 if (exists $params{cgiurl}) {
970 $cgiurl=$params{cgiurl};
971 delete $params{cgiurl};
974 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
980 return "$config{url}/" if ! defined $page;
982 $page=htmlpage($page);
984 $page=~s/[^\/]+\//..\//g;
989 # Work around very innefficient behavior in File::Spec if abs2rel
990 # is passed two relative paths. It's much faster if paths are
991 # absolute! (Debian bug #376658; fixed in debian unstable now)
996 my $ret=File::Spec->abs2rel($path, $base);
997 $ret=~s/^// if defined $ret;
1001 sub displaytime ($;$$) {
1002 # Plugins can override this function to mark up the time to
1004 my $time=formattime($_[0], $_[1]);
1005 if ($config{html5}) {
1006 return '<time datetime="'.date_3339($_[0]).'"'.
1007 ($_[2] ? ' pubdate="pubdate"' : '').
1008 '>'.$time.'</time>';
1011 return '<span class="date">'.$time.'</span>';
1015 sub formattime ($;$) {
1016 # Plugins can override this function to format the time.
1019 if (! defined $format) {
1020 $format=$config{timeformat};
1023 # strftime doesn't know about encodings, so make sure
1024 # its output is properly treated as utf8
1025 return decode_utf8(POSIX::strftime($format, localtime($time)));
1031 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1032 POSIX::setlocale(&POSIX::LC_TIME, "C");
1033 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1034 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1038 sub beautify_urlpath ($) {
1041 # Ensure url is not an empty link, and if necessary,
1042 # add ./ to avoid colon confusion.
1043 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1047 if ($config{usedirs}) {
1048 $url =~ s!/index.$config{htmlext}$!/!;
1060 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1063 if (! $destsources{$to}) {
1068 return $config{url}.beautify_urlpath("/".$to);
1071 my $link = abs2rel($to, dirname(htmlpage($from)));
1073 return beautify_urlpath($link);
1076 sub htmllink ($$$;@) {
1077 my $lpage=shift; # the page doing the linking
1078 my $page=shift; # the page that will contain the link (different for inline)
1085 if (! $opts{forcesubpage}) {
1086 $bestlink=bestlink($lpage, $link);
1089 $bestlink="$lpage/".lc($link);
1093 if (defined $opts{linktext}) {
1094 $linktext=$opts{linktext};
1097 $linktext=pagetitle(basename($link));
1100 return "<span class=\"selflink\">$linktext</span>"
1101 if length $bestlink && $page eq $bestlink &&
1102 ! defined $opts{anchor};
1104 if (! $destsources{$bestlink}) {
1105 $bestlink=htmlpage($bestlink);
1107 if (! $destsources{$bestlink}) {
1109 if (length $config{cgiurl}) {
1110 $cgilink = "<a href=\"".
1115 )."\" rel=\"nofollow\">?</a>";
1117 return "<span class=\"createlink\">$cgilink$linktext</span>"
1121 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1122 $bestlink=beautify_urlpath($bestlink);
1124 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1125 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1128 if (defined $opts{anchor}) {
1129 $bestlink.="#".$opts{anchor};
1133 foreach my $attr (qw{rel class title}) {
1134 if (defined $opts{$attr}) {
1135 push @attrs, " $attr=\"$opts{$attr}\"";
1139 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1144 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1147 sub openiduser ($) {
1150 if ($user =~ m!^https?://! &&
1151 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1154 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1155 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1158 # backcompat with old version
1159 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1160 $display=$oid->display;
1163 # Convert "user.somehost.com" to "user [somehost.com]"
1164 # (also "user.somehost.co.uk")
1165 if ($display !~ /\[/) {
1166 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1168 # Convert "http://somehost.com/user" to "user [somehost.com]".
1169 # (also "https://somehost.com/user/")
1170 if ($display !~ /\[/) {
1171 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1173 $display=~s!^https?://!!; # make sure this is removed
1174 eval q{use CGI 'escapeHTML'};
1176 return escapeHTML($display);
1181 sub htmlize ($$$$) {
1187 my $oneline = $content !~ /\n/;
1189 if (exists $hooks{htmlize}{$type}) {
1190 $content=$hooks{htmlize}{$type}{call}->(
1192 content => $content,
1196 error("htmlization of $type not supported");
1199 run_hooks(sanitize => sub {
1202 destpage => $destpage,
1203 content => $content,
1208 # hack to get rid of enclosing junk added by markdown
1209 # and other htmlizers/sanitizers
1210 $content=~s/^<p>//i;
1211 $content=~s/<\/p>\n*$//i;
1222 run_hooks(linkify => sub {
1225 destpage => $destpage,
1226 content => $content,
1234 our $preprocess_preview=0;
1235 sub preprocess ($$$;$$) {
1236 my $page=shift; # the page the data comes from
1237 my $destpage=shift; # the page the data will appear in (different for inline)
1242 # Using local because it needs to be set within any nested calls
1244 local $preprocess_preview=$preview if defined $preview;
1251 $params="" if ! defined $params;
1253 if (length $escape) {
1254 return "[[$prefix$command $params]]";
1256 elsif (exists $hooks{preprocess}{$command}) {
1257 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1258 # Note: preserve order of params, some plugins may
1259 # consider it significant.
1261 while ($params =~ m{
1262 (?:([-\w]+)=)? # 1: named parameter key?
1264 """(.*?)""" # 2: triple-quoted value
1266 "([^"]*?)" # 3: single-quoted value
1268 (\S+) # 4: unquoted value
1270 (?:\s+|$) # delimiter to next param
1280 elsif (defined $3) {
1283 elsif (defined $4) {
1288 push @params, $key, $val;
1291 push @params, $val, '';
1294 if ($preprocessing{$page}++ > 3) {
1295 # Avoid loops of preprocessed pages preprocessing
1296 # other pages that preprocess them, etc.
1297 return "[[!$command <span class=\"error\">".
1298 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1299 $page, $preprocessing{$page}).
1305 $hooks{preprocess}{$command}{call}->(
1308 destpage => $destpage,
1309 preview => $preprocess_preview,
1315 $ret="[[!$command <span class=\"error\">".
1316 gettext("Error").": $error"."</span>]]";
1320 # use void context during scan pass
1322 $hooks{preprocess}{$command}{call}->(
1325 destpage => $destpage,
1326 preview => $preprocess_preview,
1331 $preprocessing{$page}--;
1335 return "[[$prefix$command $params]]";
1340 if ($config{prefix_directives}) {
1343 \[\[(!) # directive open; 2: prefix
1344 ([-\w]+) # 3: command
1345 ( # 4: the parameters..
1346 \s+ # Must have space if parameters present
1348 (?:[-\w]+=)? # named parameter key?
1350 """.*?""" # triple-quoted value
1352 "[^"]*?" # single-quoted value
1354 [^"\s\]]+ # unquoted value
1356 \s* # whitespace or end
1359 *)? # 0 or more parameters
1360 \]\] # directive closed
1366 \[\[(!?) # directive open; 2: optional prefix
1367 ([-\w]+) # 3: command
1369 ( # 4: the parameters..
1371 (?:[-\w]+=)? # named parameter key?
1373 """.*?""" # triple-quoted value
1375 "[^"]*?" # single-quoted value
1377 [^"\s\]]+ # unquoted value
1379 \s* # whitespace or end
1382 *) # 0 or more parameters
1383 \]\] # directive closed
1387 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1396 run_hooks(filter => sub {
1397 $content=shift->(page => $page, destpage => $destpage,
1398 content => $content);
1404 sub check_canedit ($$$;$) {
1411 run_hooks(canedit => sub {
1412 return if defined $canedit;
1413 my $ret=shift->($page, $q, $session);
1418 elsif (ref $ret eq 'CODE') {
1419 $ret->() unless $nonfatal;
1422 elsif (defined $ret) {
1423 error($ret) unless $nonfatal;
1428 return defined $canedit ? $canedit : 1;
1431 sub check_content (@) {
1434 return 1 if ! exists $hooks{checkcontent}; # optimisation
1436 if (exists $pagesources{$params{page}}) {
1438 my %old=map { $_ => 1 }
1439 split("\n", readfile(srcfile($pagesources{$params{page}})));
1440 foreach my $line (split("\n", $params{content})) {
1441 push @diff, $line if ! exists $old{$line};
1443 $params{diff}=join("\n", @diff);
1447 run_hooks(checkcontent => sub {
1448 return if defined $ok;
1449 my $ret=shift->(%params);
1454 elsif (ref $ret eq 'CODE') {
1455 $ret->() unless $params{nonfatal};
1458 elsif (defined $ret) {
1459 error($ret) unless $params{nonfatal};
1465 return defined $ok ? $ok : 1;
1471 # Take an exclusive lock on the wiki to prevent multiple concurrent
1472 # run issues. The lock will be dropped on program exit.
1473 if (! -d $config{wikistatedir}) {
1474 mkdir($config{wikistatedir});
1476 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1477 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1478 if (! flock($wikilock, 2)) { # LOCK_EX
1479 error("failed to get lock");
1485 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1486 return close($wikilock) if $wikilock;
1492 sub commit_hook_enabled () {
1493 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1494 error("cannot write to $config{wikistatedir}/commitlock: $!");
1495 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1496 close($commitlock) || error("failed closing commitlock: $!");
1499 close($commitlock) || error("failed closing commitlock: $!");
1503 sub disable_commit_hook () {
1504 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1505 error("cannot write to $config{wikistatedir}/commitlock: $!");
1506 if (! flock($commitlock, 2)) { # LOCK_EX
1507 error("failed to get commit lock");
1512 sub enable_commit_hook () {
1513 return close($commitlock) if $commitlock;
1518 %oldrenderedfiles=%pagectime=();
1519 if (! $config{rebuild}) {
1520 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1521 %destsources=%renderedfiles=%pagecase=%pagestate=
1522 %depends_simple=%typedlinks=%oldtypedlinks=();
1525 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1526 if (-e "$config{wikistatedir}/index") {
1527 system("ikiwiki-transition", "indexdb", $config{srcdir});
1528 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1531 $config{gettime}=1; # first build
1536 my $index=Storable::fd_retrieve($in);
1537 if (! defined $index) {
1542 if (exists $index->{version} && ! ref $index->{version}) {
1543 $pages=$index->{page};
1544 %wikistate=%{$index->{state}};
1551 foreach my $src (keys %$pages) {
1552 my $d=$pages->{$src};
1553 my $page=pagename($src);
1554 $pagectime{$page}=$d->{ctime};
1555 $pagesources{$page}=$src;
1556 if (! $config{rebuild}) {
1557 $pagemtime{$page}=$d->{mtime};
1558 $renderedfiles{$page}=$d->{dest};
1559 if (exists $d->{links} && ref $d->{links}) {
1560 $links{$page}=$d->{links};
1561 $oldlinks{$page}=[@{$d->{links}}];
1563 if (ref $d->{depends_simple} eq 'ARRAY') {
1565 $depends_simple{$page}={
1566 map { $_ => 1 } @{$d->{depends_simple}}
1569 elsif (exists $d->{depends_simple}) {
1570 $depends_simple{$page}=$d->{depends_simple};
1572 if (exists $d->{dependslist}) {
1575 map { $_ => $DEPEND_CONTENT }
1576 @{$d->{dependslist}}
1579 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1581 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1583 elsif (exists $d->{depends}) {
1584 $depends{$page}=$d->{depends};
1586 if (exists $d->{state}) {
1587 $pagestate{$page}=$d->{state};
1589 if (exists $d->{typedlinks}) {
1590 $typedlinks{$page}=$d->{typedlinks};
1592 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1593 next unless %$links;
1594 $oldtypedlinks{$page}{$type} = {%$links};
1598 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1600 foreach my $page (keys %pagesources) {
1601 $pagecase{lc $page}=$page;
1603 foreach my $page (keys %renderedfiles) {
1604 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1610 run_hooks(savestate => sub { shift->() });
1613 foreach my $type (keys %hooks) {
1614 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1616 my @hookids=keys %hookids;
1618 if (! -d $config{wikistatedir}) {
1619 mkdir($config{wikistatedir});
1621 my $newfile="$config{wikistatedir}/indexdb.new";
1622 my $cleanup = sub { unlink($newfile) };
1623 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1626 foreach my $page (keys %pagemtime) {
1627 next unless $pagemtime{$page};
1628 my $src=$pagesources{$page};
1630 $index{page}{$src}={
1631 ctime => $pagectime{$page},
1632 mtime => $pagemtime{$page},
1633 dest => $renderedfiles{$page},
1634 links => $links{$page},
1637 if (exists $depends{$page}) {
1638 $index{page}{$src}{depends} = $depends{$page};
1641 if (exists $depends_simple{$page}) {
1642 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1645 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1646 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1649 if (exists $pagestate{$page}) {
1650 foreach my $id (@hookids) {
1651 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1652 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1659 foreach my $id (@hookids) {
1660 foreach my $key (keys %{$wikistate{$id}}) {
1661 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1665 $index{version}="3";
1666 my $ret=Storable::nstore_fd(\%index, $out);
1667 return if ! defined $ret || ! $ret;
1668 close $out || error("failed saving to $newfile: $!", $cleanup);
1669 rename($newfile, "$config{wikistatedir}/indexdb") ||
1670 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1675 sub template_file ($) {
1678 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1679 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1680 $tpage=$pagesources{$tpage};
1684 my $template=srcfile($tpage, 1);
1685 if (defined $template) {
1686 return $template, $tpage, 1 if wantarray;
1690 $name=~s:/::; # avoid path traversal
1691 foreach my $dir ($config{templatedir},
1692 "$installdir/share/ikiwiki/templates") {
1693 if (-e "$dir/$name") {
1694 $template="$dir/$name";
1698 if (defined $template) {
1699 return $template, $tpage if wantarray;
1707 sub template_depends ($$;@) {
1711 my ($filename, $tpage, $untrusted)=template_file($name);
1712 if (defined $page && defined $tpage) {
1713 add_depends($page, $tpage);
1716 return unless defined $filename;
1720 my $text_ref = shift;
1721 ${$text_ref} = decode_utf8(${$text_ref});
1723 loop_context_vars => 1,
1724 die_on_bad_params => 0,
1725 filename => $filename,
1727 ($untrusted ? (no_includes => 1) : ()),
1729 return @opts if wantarray;
1731 require HTML::Template;
1732 return HTML::Template->new(@opts);
1735 sub template ($;@) {
1736 template_depends(shift, undef, @_);
1739 sub misctemplate ($$;@) {
1744 my $template=template("page.tmpl");
1747 if (exists $params{page}) {
1748 $page=delete $params{page};
1750 run_hooks(pagetemplate => sub {
1754 template => $template,
1757 templateactions($template, "");
1762 wikiname => $config{wikiname},
1763 content => $content,
1764 baseurl => baseurl(),
1765 html5 => $config{html5},
1769 return $template->output;
1772 sub templateactions ($$) {
1778 run_hooks(pageactions => sub {
1779 push @actions, map { { action => $_ } }
1780 grep { defined } shift->(page => $page);
1782 $template->param(actions => \@actions);
1784 if ($config{cgiurl} && exists $hooks{auth}) {
1785 $template->param(prefsurl => cgiurl(do => "prefs"));
1789 if ($have_actions || @actions) {
1790 $template->param(have_actions => 1);
1797 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1798 error 'hook requires type, call, and id parameters';
1801 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1803 $hooks{$param{type}}{$param{id}}=\%param;
1807 sub run_hooks ($$) {
1808 # Calls the given sub for each hook of the given type,
1809 # passing it the hook function to call.
1813 if (exists $hooks{$type}) {
1814 my (@first, @middle, @last);
1815 foreach my $id (keys %{$hooks{$type}}) {
1816 if ($hooks{$type}{$id}{first}) {
1819 elsif ($hooks{$type}{$id}{last}) {
1826 foreach my $id (@first, @middle, @last) {
1827 $sub->($hooks{$type}{$id}{call});
1835 $hooks{rcs}{rcs_update}{call}->(@_);
1838 sub rcs_prepedit ($) {
1839 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1842 sub rcs_commit ($$$;$$) {
1843 $hooks{rcs}{rcs_commit}{call}->(@_);
1846 sub rcs_commit_staged ($$$) {
1847 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1851 $hooks{rcs}{rcs_add}{call}->(@_);
1854 sub rcs_remove ($) {
1855 $hooks{rcs}{rcs_remove}{call}->(@_);
1858 sub rcs_rename ($$) {
1859 $hooks{rcs}{rcs_rename}{call}->(@_);
1862 sub rcs_recentchanges ($) {
1863 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1867 $hooks{rcs}{rcs_diff}{call}->(@_);
1870 sub rcs_getctime ($) {
1871 $hooks{rcs}{rcs_getctime}{call}->(@_);
1874 sub rcs_getmtime ($) {
1875 $hooks{rcs}{rcs_getmtime}{call}->(@_);
1878 sub rcs_receive () {
1879 $hooks{rcs}{rcs_receive}{call}->();
1882 sub add_depends ($$;$) {
1885 my $deptype=shift || $DEPEND_CONTENT;
1887 # Is the pagespec a simple page name?
1888 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1889 $pagespec !~ /[\s*?()!]/) {
1890 $depends_simple{$page}{lc $pagespec} |= $deptype;
1894 # Add explicit dependencies for influences.
1895 my $sub=pagespec_translate($pagespec);
1896 return unless defined $sub;
1897 foreach my $p (keys %pagesources) {
1898 my $r=$sub->($p, location => $page);
1899 my $i=$r->influences;
1900 my $static=$r->influences_static;
1901 foreach my $k (keys %$i) {
1902 next unless $r || $static || $k eq $page;
1903 $depends_simple{$page}{lc $k} |= $i->{$k};
1908 $depends{$page}{$pagespec} |= $deptype;
1914 foreach my $type (@_) {
1915 if ($type eq 'presence') {
1916 $deptype |= $DEPEND_PRESENCE;
1918 elsif ($type eq 'links') {
1919 $deptype |= $DEPEND_LINKS;
1921 elsif ($type eq 'content') {
1922 $deptype |= $DEPEND_CONTENT;
1928 my $file_prune_regexp;
1929 sub file_pruned ($) {
1932 if (defined $config{include} && length $config{include}) {
1933 return 0 if $file =~ m/$config{include}/;
1936 if (! defined $file_prune_regexp) {
1937 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1938 $file_prune_regexp=qr/$file_prune_regexp/;
1940 return $file =~ m/$file_prune_regexp/;
1943 sub define_gettext () {
1944 # If translation is needed, redefine the gettext function to do it.
1945 # Otherwise, it becomes a quick no-op.
1948 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1949 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1950 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1952 $gettext_obj=eval q{
1953 use Locale::gettext q{textdomain};
1954 Locale::gettext->domain('ikiwiki')
1959 no warnings 'redefine';
1961 $getobj->() if $getobj;
1963 $gettext_obj->get(shift);
1970 $getobj->() if $getobj;
1972 $gettext_obj->nget(@_);
1975 return ($_[2] == 1 ? $_[0] : $_[1])
1993 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1997 # Injects a new function into the symbol table to replace an
1998 # exported function.
2001 # This is deep ugly perl foo, beware.
2004 if (! defined $params{parent}) {
2005 $params{parent}='::';
2006 $params{old}=\&{$params{name}};
2007 $params{name}=~s/.*:://;
2009 my $parent=$params{parent};
2010 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2011 $ns = $params{parent} . $ns;
2012 inject(%params, parent => $ns) unless $ns eq '::main::';
2013 *{$ns . $params{name}} = $params{call}
2014 if exists ${$ns}{$params{name}} &&
2015 \&{${$ns}{$params{name}}} == $params{old};
2021 sub add_link ($$;$) {
2026 push @{$links{$page}}, $link
2027 unless grep { $_ eq $link } @{$links{$page}};
2029 if (defined $type) {
2030 $typedlinks{$page}{$type}{$link} = 1;
2034 sub add_autofile ($$$) {
2037 my $generator=shift;
2039 $autofiles{$file}{plugin}=$plugin;
2040 $autofiles{$file}{generator}=$generator;
2043 sub sortspec_translate ($$) {
2045 my $reverse = shift;
2051 (-?) # group 1: perhaps negated
2054 \w+\([^\)]*\) # command(params)
2056 [^\s]+ # or anything else
2064 if ($word =~ m/^(\w+)\((.*)\)$/) {
2065 # command with parameters
2069 elsif ($word !~ m/^\w+$/) {
2070 error(sprintf(gettext("invalid sort type %s"), $word));
2081 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2082 if (defined $params) {
2083 push @data, $params;
2084 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2087 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2091 error(sprintf(gettext("unknown sort type %s"), $word));
2095 if (! length $code) {
2096 # undefined sorting method... sort arbitrarily
2105 return eval 'sub { '.$code.' }';
2108 sub pagespec_translate ($) {
2111 # Convert spec to perl code.
2115 \s* # ignore whitespace
2116 ( # 1: match a single word
2123 \w+\([^\)]*\) # command(params)
2125 [^\s()]+ # any other text
2127 \s* # ignore whitespace
2130 if (lc $word eq 'and') {
2133 elsif (lc $word eq 'or') {
2136 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2139 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2140 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2142 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2145 push @data, qq{unknown function in pagespec "$word"};
2146 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2151 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2155 if (! length $code) {
2156 $code="IkiWiki::FailReason->new('empty pagespec')";
2160 return eval 'sub { my $page=shift; '.$code.' }';
2163 sub pagespec_match ($$;@) {
2168 # Backwards compatability with old calling convention.
2170 unshift @params, 'location';
2173 my $sub=pagespec_translate($spec);
2174 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2176 return $sub->($page, @params);
2179 sub pagespec_match_list ($$;@) {
2184 # Backwards compatability with old calling convention.
2186 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2187 $params{list}=$page;
2188 $page=$params{location}; # ugh!
2191 my $sub=pagespec_translate($pagespec);
2192 error "syntax error in pagespec \"$pagespec\""
2194 my $sort=sortspec_translate($params{sort}, $params{reverse})
2195 if defined $params{sort};
2198 if (exists $params{list}) {
2199 @candidates=exists $params{filter}
2200 ? grep { ! $params{filter}->($_) } @{$params{list}}
2204 @candidates=exists $params{filter}
2205 ? grep { ! $params{filter}->($_) } keys %pagesources
2206 : keys %pagesources;
2209 # clear params, remainder is passed to pagespec
2210 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2211 my $num=$params{num};
2212 delete @params{qw{num deptype reverse sort filter list}};
2214 # when only the top matches will be returned, it's efficient to
2215 # sort before matching to pagespec,
2216 if (defined $num && defined $sort) {
2217 @candidates=IkiWiki::SortSpec::sort_pages(
2218 $sort, @candidates);
2224 my $accum=IkiWiki::SuccessReason->new();
2225 foreach my $p (@candidates) {
2226 my $r=$sub->($p, %params, location => $page);
2227 error(sprintf(gettext("cannot match pages: %s"), $r))
2228 if $r->isa("IkiWiki::ErrorReason");
2229 unless ($r || $r->influences_static) {
2230 $r->remove_influence($p);
2235 last if defined $num && ++$count == $num;
2239 # Add simple dependencies for accumulated influences.
2240 my $i=$accum->influences;
2241 foreach my $k (keys %$i) {
2242 $depends_simple{$page}{lc $k} |= $i->{$k};
2245 # when all matches will be returned, it's efficient to
2246 # sort after matching
2247 if (! defined $num && defined $sort) {
2248 return IkiWiki::SortSpec::sort_pages(
2256 sub pagespec_valid ($) {
2259 return defined pagespec_translate($spec);
2263 my $re=quotemeta(shift);
2269 package IkiWiki::FailReason;
2272 '""' => sub { $_[0][0] },
2274 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2275 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2276 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2280 our @ISA = 'IkiWiki::SuccessReason';
2282 package IkiWiki::SuccessReason;
2285 '""' => sub { $_[0][0] },
2287 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2288 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2289 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2296 return bless [$value, {@_}], $class;
2301 $this->[1]={@_} if @_;
2302 my %i=%{$this->[1]};
2307 sub influences_static {
2308 return ! $_[0][1]->{""};
2311 sub merge_influences {
2316 if (! $anded || (($this || %{$this->[1]}) &&
2317 ($other || %{$other->[1]}))) {
2318 foreach my $influence (keys %{$other->[1]}) {
2319 $this->[1]{$influence} |= $other->[1]{$influence};
2328 sub remove_influence {
2332 delete $this->[1]{$torm};
2335 package IkiWiki::ErrorReason;
2337 our @ISA = 'IkiWiki::FailReason';
2339 package IkiWiki::PageSpec;
2345 if ($path =~ m!^\./!) {
2346 $from=~s#/?[^/]+$## if defined $from;
2348 $path="$from/$path" if defined $from && length $from;
2354 sub match_glob ($$;@) {
2359 $glob=derel($glob, $params{location});
2361 my $regexp=IkiWiki::glob2re($glob);
2362 if ($page=~/^$regexp$/i) {
2363 if (! IkiWiki::isinternal($page) || $params{internal}) {
2364 return IkiWiki::SuccessReason->new("$glob matches $page");
2367 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2371 return IkiWiki::FailReason->new("$glob does not match $page");
2375 sub match_internal ($$;@) {
2376 return match_glob(shift, shift, @_, internal => 1)
2379 sub match_page ($$;@) {
2381 my $match=match_glob($page, shift, @_);
2382 if ($match && ! (exists $IkiWiki::pagesources{$page}
2383 && defined IkiWiki::pagetype($IkiWiki::pagesources{$page}))) {
2384 return IkiWiki::FailReason->new("$page is not a page");
2391 sub match_link ($$;@) {
2396 $link=derel($link, $params{location});
2397 my $from=exists $params{location} ? $params{location} : '';
2398 my $linktype=$params{linktype};
2400 if (defined $linktype) {
2401 $qualifier=" with type $linktype";
2404 my $links = $IkiWiki::links{$page};
2405 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2406 unless $links && @{$links};
2407 my $bestlink = IkiWiki::bestlink($from, $link);
2408 foreach my $p (@{$links}) {
2409 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2411 if (length $bestlink) {
2412 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2413 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2417 if (match_glob($p, $link, %params)) {
2418 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2420 my ($p_rel)=$p=~/^\/?(.*)/;
2422 if (match_glob($p_rel, $link, %params)) {
2423 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2427 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2430 sub match_backlink ($$;@) {
2431 my $ret=match_link($_[1], $_[0], @_);
2432 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2436 sub match_created_before ($$;@) {
2441 $testpage=derel($testpage, $params{location});
2443 if (exists $IkiWiki::pagectime{$testpage}) {
2444 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2445 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2448 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2452 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2456 sub match_created_after ($$;@) {
2461 $testpage=derel($testpage, $params{location});
2463 if (exists $IkiWiki::pagectime{$testpage}) {
2464 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2465 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2468 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2472 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2476 sub match_creation_day ($$;@) {
2477 if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2478 return IkiWiki::SuccessReason->new('creation_day matched');
2481 return IkiWiki::FailReason->new('creation_day did not match');
2485 sub match_creation_month ($$;@) {
2486 if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2487 return IkiWiki::SuccessReason->new('creation_month matched');
2490 return IkiWiki::FailReason->new('creation_month did not match');
2494 sub match_creation_year ($$;@) {
2495 if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2496 return IkiWiki::SuccessReason->new('creation_year matched');
2499 return IkiWiki::FailReason->new('creation_year did not match');
2503 sub match_user ($$;@) {
2508 my $regexp=IkiWiki::glob2re($user);
2510 if (! exists $params{user}) {
2511 return IkiWiki::ErrorReason->new("no user specified");
2514 if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2515 return IkiWiki::SuccessReason->new("user is $user");
2517 elsif (! defined $params{user}) {
2518 return IkiWiki::FailReason->new("not logged in");
2521 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2525 sub match_admin ($$;@) {
2530 if (! exists $params{user}) {
2531 return IkiWiki::ErrorReason->new("no user specified");
2534 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2535 return IkiWiki::SuccessReason->new("user is an admin");
2537 elsif (! defined $params{user}) {
2538 return IkiWiki::FailReason->new("not logged in");
2541 return IkiWiki::FailReason->new("user is not an admin");
2545 sub match_ip ($$;@) {
2550 if (! exists $params{ip}) {
2551 return IkiWiki::ErrorReason->new("no IP specified");
2554 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2555 return IkiWiki::SuccessReason->new("IP is $ip");
2558 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2562 package IkiWiki::SortSpec;
2564 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2565 # are easily available in this namespace, for cmp functions to use them.
2572 IkiWiki::pagetitle(IkiWiki::basename($a))
2574 IkiWiki::pagetitle(IkiWiki::basename($b))
2577 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2578 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }