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;
595 sub loadplugin ($;$) {
599 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
601 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
602 "$installdir/lib/ikiwiki") {
603 if (defined $dir && -x "$dir/plugins/$plugin") {
604 eval { require IkiWiki::Plugin::external };
607 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
609 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
610 $loaded_plugins{$plugin}=1;
615 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
618 error("Failed to load plugin $mod: $@");
620 $loaded_plugins{$plugin}=1;
627 log_message('err' => $message) if $config{syslog};
628 if (defined $cleaner) {
635 return unless $config{verbose};
636 return log_message(debug => @_);
640 sub log_message ($$) {
643 if ($config{syslog}) {
646 Sys::Syslog::setlogsock('unix');
647 Sys::Syslog::openlog('ikiwiki', '', 'user');
651 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
654 elsif (! $config{cgi}) {
658 return print STDERR "@_\n";
662 sub possibly_foolish_untaint ($) {
664 my ($untainted)=$tainted=~/(.*)/s;
684 return exists $pagesources{$page} &&
685 $pagesources{$page} =~ /\._([^.]+)$/;
691 if ($file =~ /\.([^.]+)$/) {
692 return $1 if exists $hooks{htmlize}{$1};
694 my $base=basename($file);
695 if (exists $hooks{htmlize}{$base} &&
696 $hooks{htmlize}{$base}{noextension}) {
707 if (exists $pagename_cache{$file}) {
708 return $pagename_cache{$file};
711 my $type=pagetype($file);
713 $page=~s/\Q.$type\E*$//
714 if defined $type && !$hooks{htmlize}{$type}{keepextension}
715 && !$hooks{htmlize}{$type}{noextension};
716 if ($config{indexpages} && $page=~/(.*)\/index$/) {
720 $pagename_cache{$file} = $page;
724 sub newpagefile ($$) {
728 if (! $config{indexpages} || $page eq 'index') {
729 return $page.".".$type;
732 return $page."/index.".$type;
736 sub targetpage ($$;$) {
741 if (defined $filename) {
742 return $page."/".$filename.".".$ext;
744 elsif (! $config{usedirs} || $page eq 'index') {
745 return $page.".".$ext;
748 return $page."/index.".$ext;
755 return targetpage($page, $config{htmlext});
762 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
763 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
764 return "$dir/$file", stat(_) if -e "$dir/$file";
766 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
771 return (srcfile_stat(@_))[0];
774 sub add_underlay ($) {
778 $dir="$config{underlaydirbase}/$dir";
781 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
782 unshift @{$config{underlaydirs}}, $dir;
788 sub readfile ($;$$) {
794 error("cannot read a symlink ($file)");
798 open (my $in, "<", $file) || error("failed to read $file: $!");
799 binmode($in) if ($binary);
800 return \*$in if $wantfd;
802 # check for invalid utf-8, and toss it back to avoid crashes
803 if (! utf8::valid($ret)) {
804 $ret=encode_utf8($ret);
806 close $in || error("failed to read $file: $!");
810 sub prep_writefile ($$) {
815 while (length $test) {
816 if (-l "$destdir/$test") {
817 error("cannot write to a symlink ($test)");
819 $test=dirname($test);
822 my $dir=dirname("$destdir/$file");
825 foreach my $s (split(m!/+!, $dir)) {
828 mkdir($d) || error("failed to create directory $d: $!");
836 sub writefile ($$$;$$) {
837 my $file=shift; # can include subdirs
838 my $destdir=shift; # directory to put file in
843 prep_writefile($file, $destdir);
845 my $newfile="$destdir/$file.ikiwiki-new";
847 error("cannot write to a symlink ($newfile)");
850 my $cleanup = sub { unlink($newfile) };
851 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
852 binmode($out) if ($binary);
854 $writer->(\*$out, $cleanup);
857 print $out $content or error("failed writing to $newfile: $!", $cleanup);
859 close $out || error("failed saving $newfile: $!", $cleanup);
860 rename($newfile, "$destdir/$file") ||
861 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
867 sub will_render ($$;$) {
872 # Important security check.
873 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
874 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
875 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
878 if (! $clear || $cleared{$page}) {
879 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
882 foreach my $old (@{$renderedfiles{$page}}) {
883 delete $destsources{$old};
885 $renderedfiles{$page}=[$dest];
888 $destsources{$dest}=$page;
898 if ($link=~s/^\/+//) {
906 $l.="/" if length $l;
909 if (exists $pagesources{$l}) {
912 elsif (exists $pagecase{lc $l}) {
913 return $pagecase{lc $l};
915 } while $cwd=~s{/?[^/]+$}{};
917 if (length $config{userdir}) {
918 my $l = "$config{userdir}/".lc($link);
919 if (exists $pagesources{$l}) {
922 elsif (exists $pagecase{lc $l}) {
923 return $pagecase{lc $l};
927 #print STDERR "warning: page $page, broken link: $link\n";
931 sub isinlinableimage ($) {
934 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
937 sub pagetitle ($;$) {
942 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
945 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
953 # support use w/o %config set
954 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
955 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
961 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
962 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
969 my $cgiurl=$config{cgiurl};
970 if (exists $params{cgiurl}) {
971 $cgiurl=$params{cgiurl};
972 delete $params{cgiurl};
975 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
981 return "$config{url}/" if ! defined $page;
983 $page=htmlpage($page);
985 $page=~s/[^\/]+\//..\//g;
990 # Work around very innefficient behavior in File::Spec if abs2rel
991 # is passed two relative paths. It's much faster if paths are
992 # absolute! (Debian bug #376658; fixed in debian unstable now)
997 my $ret=File::Spec->abs2rel($path, $base);
998 $ret=~s/^// if defined $ret;
1002 sub displaytime ($;$$) {
1003 # Plugins can override this function to mark up the time to
1005 my $time=formattime($_[0], $_[1]);
1006 if ($config{html5}) {
1007 return '<time datetime="'.date_3339($_[0]).'"'.
1008 ($_[2] ? ' pubdate="pubdate"' : '').
1009 '>'.$time.'</time>';
1012 return '<span class="date">'.$time.'</span>';
1016 sub formattime ($;$) {
1017 # Plugins can override this function to format the time.
1020 if (! defined $format) {
1021 $format=$config{timeformat};
1024 # strftime doesn't know about encodings, so make sure
1025 # its output is properly treated as utf8
1026 return decode_utf8(POSIX::strftime($format, localtime($time)));
1032 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1033 POSIX::setlocale(&POSIX::LC_TIME, "C");
1034 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1035 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1039 sub beautify_urlpath ($) {
1042 # Ensure url is not an empty link, and if necessary,
1043 # add ./ to avoid colon confusion.
1044 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1048 if ($config{usedirs}) {
1049 $url =~ s!/index.$config{htmlext}$!/!;
1061 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1064 if (! $destsources{$to}) {
1069 return $config{url}.beautify_urlpath("/".$to);
1072 my $link = abs2rel($to, dirname(htmlpage($from)));
1074 return beautify_urlpath($link);
1077 sub htmllink ($$$;@) {
1078 my $lpage=shift; # the page doing the linking
1079 my $page=shift; # the page that will contain the link (different for inline)
1086 if (! $opts{forcesubpage}) {
1087 $bestlink=bestlink($lpage, $link);
1090 $bestlink="$lpage/".lc($link);
1094 if (defined $opts{linktext}) {
1095 $linktext=$opts{linktext};
1098 $linktext=pagetitle(basename($link));
1101 return "<span class=\"selflink\">$linktext</span>"
1102 if length $bestlink && $page eq $bestlink &&
1103 ! defined $opts{anchor};
1105 if (! $destsources{$bestlink}) {
1106 $bestlink=htmlpage($bestlink);
1108 if (! $destsources{$bestlink}) {
1110 if (length $config{cgiurl}) {
1111 $cgilink = "<a href=\"".
1116 )."\" rel=\"nofollow\">?</a>";
1118 return "<span class=\"createlink\">$cgilink$linktext</span>"
1122 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1123 $bestlink=beautify_urlpath($bestlink);
1125 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1126 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1129 if (defined $opts{anchor}) {
1130 $bestlink.="#".$opts{anchor};
1134 foreach my $attr (qw{rel class title}) {
1135 if (defined $opts{$attr}) {
1136 push @attrs, " $attr=\"$opts{$attr}\"";
1140 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1145 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1148 sub openiduser ($) {
1151 if ($user =~ m!^https?://! &&
1152 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1155 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1156 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1159 # backcompat with old version
1160 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1161 $display=$oid->display;
1164 # Convert "user.somehost.com" to "user [somehost.com]"
1165 # (also "user.somehost.co.uk")
1166 if ($display !~ /\[/) {
1167 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1169 # Convert "http://somehost.com/user" to "user [somehost.com]".
1170 # (also "https://somehost.com/user/")
1171 if ($display !~ /\[/) {
1172 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1174 $display=~s!^https?://!!; # make sure this is removed
1175 eval q{use CGI 'escapeHTML'};
1177 return escapeHTML($display);
1182 sub htmlize ($$$$) {
1188 my $oneline = $content !~ /\n/;
1190 if (exists $hooks{htmlize}{$type}) {
1191 $content=$hooks{htmlize}{$type}{call}->(
1193 content => $content,
1197 error("htmlization of $type not supported");
1200 run_hooks(sanitize => sub {
1203 destpage => $destpage,
1204 content => $content,
1209 # hack to get rid of enclosing junk added by markdown
1210 # and other htmlizers/sanitizers
1211 $content=~s/^<p>//i;
1212 $content=~s/<\/p>\n*$//i;
1223 run_hooks(linkify => sub {
1226 destpage => $destpage,
1227 content => $content,
1235 our $preprocess_preview=0;
1236 sub preprocess ($$$;$$) {
1237 my $page=shift; # the page the data comes from
1238 my $destpage=shift; # the page the data will appear in (different for inline)
1243 # Using local because it needs to be set within any nested calls
1245 local $preprocess_preview=$preview if defined $preview;
1252 $params="" if ! defined $params;
1254 if (length $escape) {
1255 return "[[$prefix$command $params]]";
1257 elsif (exists $hooks{preprocess}{$command}) {
1258 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1259 # Note: preserve order of params, some plugins may
1260 # consider it significant.
1262 while ($params =~ m{
1263 (?:([-\w]+)=)? # 1: named parameter key?
1265 """(.*?)""" # 2: triple-quoted value
1267 "([^"]*?)" # 3: single-quoted value
1269 (\S+) # 4: unquoted value
1271 (?:\s+|$) # delimiter to next param
1281 elsif (defined $3) {
1284 elsif (defined $4) {
1289 push @params, $key, $val;
1292 push @params, $val, '';
1295 if ($preprocessing{$page}++ > 3) {
1296 # Avoid loops of preprocessed pages preprocessing
1297 # other pages that preprocess them, etc.
1298 return "[[!$command <span class=\"error\">".
1299 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1300 $page, $preprocessing{$page}).
1306 $hooks{preprocess}{$command}{call}->(
1309 destpage => $destpage,
1310 preview => $preprocess_preview,
1316 $ret="[[!$command <span class=\"error\">".
1317 gettext("Error").": $error"."</span>]]";
1321 # use void context during scan pass
1323 $hooks{preprocess}{$command}{call}->(
1326 destpage => $destpage,
1327 preview => $preprocess_preview,
1332 $preprocessing{$page}--;
1336 return "[[$prefix$command $params]]";
1341 if ($config{prefix_directives}) {
1344 \[\[(!) # directive open; 2: prefix
1345 ([-\w]+) # 3: command
1346 ( # 4: the parameters..
1347 \s+ # Must have space if parameters present
1349 (?:[-\w]+=)? # named parameter key?
1351 """.*?""" # triple-quoted value
1353 "[^"]*?" # single-quoted value
1355 [^"\s\]]+ # unquoted value
1357 \s* # whitespace or end
1360 *)? # 0 or more parameters
1361 \]\] # directive closed
1367 \[\[(!?) # directive open; 2: optional prefix
1368 ([-\w]+) # 3: command
1370 ( # 4: the parameters..
1372 (?:[-\w]+=)? # named parameter key?
1374 """.*?""" # triple-quoted value
1376 "[^"]*?" # single-quoted value
1378 [^"\s\]]+ # unquoted value
1380 \s* # whitespace or end
1383 *) # 0 or more parameters
1384 \]\] # directive closed
1388 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1397 run_hooks(filter => sub {
1398 $content=shift->(page => $page, destpage => $destpage,
1399 content => $content);
1405 sub check_canedit ($$$;$) {
1412 run_hooks(canedit => sub {
1413 return if defined $canedit;
1414 my $ret=shift->($page, $q, $session);
1419 elsif (ref $ret eq 'CODE') {
1420 $ret->() unless $nonfatal;
1423 elsif (defined $ret) {
1424 error($ret) unless $nonfatal;
1429 return defined $canedit ? $canedit : 1;
1432 sub check_content (@) {
1435 return 1 if ! exists $hooks{checkcontent}; # optimisation
1437 if (exists $pagesources{$params{page}}) {
1439 my %old=map { $_ => 1 }
1440 split("\n", readfile(srcfile($pagesources{$params{page}})));
1441 foreach my $line (split("\n", $params{content})) {
1442 push @diff, $line if ! exists $old{$line};
1444 $params{diff}=join("\n", @diff);
1448 run_hooks(checkcontent => sub {
1449 return if defined $ok;
1450 my $ret=shift->(%params);
1455 elsif (ref $ret eq 'CODE') {
1456 $ret->() unless $params{nonfatal};
1459 elsif (defined $ret) {
1460 error($ret) unless $params{nonfatal};
1466 return defined $ok ? $ok : 1;
1472 # Take an exclusive lock on the wiki to prevent multiple concurrent
1473 # run issues. The lock will be dropped on program exit.
1474 if (! -d $config{wikistatedir}) {
1475 mkdir($config{wikistatedir});
1477 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1478 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1479 if (! flock($wikilock, 2)) { # LOCK_EX
1480 error("failed to get lock");
1486 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1487 return close($wikilock) if $wikilock;
1493 sub commit_hook_enabled () {
1494 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1495 error("cannot write to $config{wikistatedir}/commitlock: $!");
1496 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1497 close($commitlock) || error("failed closing commitlock: $!");
1500 close($commitlock) || error("failed closing commitlock: $!");
1504 sub disable_commit_hook () {
1505 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1506 error("cannot write to $config{wikistatedir}/commitlock: $!");
1507 if (! flock($commitlock, 2)) { # LOCK_EX
1508 error("failed to get commit lock");
1513 sub enable_commit_hook () {
1514 return close($commitlock) if $commitlock;
1519 %oldrenderedfiles=%pagectime=();
1520 if (! $config{rebuild}) {
1521 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1522 %destsources=%renderedfiles=%pagecase=%pagestate=
1523 %depends_simple=%typedlinks=%oldtypedlinks=();
1526 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1527 if (-e "$config{wikistatedir}/index") {
1528 system("ikiwiki-transition", "indexdb", $config{srcdir});
1529 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1532 $config{gettime}=1; # first build
1537 my $index=Storable::fd_retrieve($in);
1538 if (! defined $index) {
1543 if (exists $index->{version} && ! ref $index->{version}) {
1544 $pages=$index->{page};
1545 %wikistate=%{$index->{state}};
1552 foreach my $src (keys %$pages) {
1553 my $d=$pages->{$src};
1554 my $page=pagename($src);
1555 $pagectime{$page}=$d->{ctime};
1556 $pagesources{$page}=$src;
1557 if (! $config{rebuild}) {
1558 $pagemtime{$page}=$d->{mtime};
1559 $renderedfiles{$page}=$d->{dest};
1560 if (exists $d->{links} && ref $d->{links}) {
1561 $links{$page}=$d->{links};
1562 $oldlinks{$page}=[@{$d->{links}}];
1564 if (ref $d->{depends_simple} eq 'ARRAY') {
1566 $depends_simple{$page}={
1567 map { $_ => 1 } @{$d->{depends_simple}}
1570 elsif (exists $d->{depends_simple}) {
1571 $depends_simple{$page}=$d->{depends_simple};
1573 if (exists $d->{dependslist}) {
1576 map { $_ => $DEPEND_CONTENT }
1577 @{$d->{dependslist}}
1580 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1582 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1584 elsif (exists $d->{depends}) {
1585 $depends{$page}=$d->{depends};
1587 if (exists $d->{state}) {
1588 $pagestate{$page}=$d->{state};
1590 if (exists $d->{typedlinks}) {
1591 $typedlinks{$page}=$d->{typedlinks};
1593 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1594 next unless %$links;
1595 $oldtypedlinks{$page}{$type} = {%$links};
1599 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1601 foreach my $page (keys %pagesources) {
1602 $pagecase{lc $page}=$page;
1604 foreach my $page (keys %renderedfiles) {
1605 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1611 run_hooks(savestate => sub { shift->() });
1614 foreach my $type (keys %hooks) {
1615 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1617 my @hookids=keys %hookids;
1619 if (! -d $config{wikistatedir}) {
1620 mkdir($config{wikistatedir});
1622 my $newfile="$config{wikistatedir}/indexdb.new";
1623 my $cleanup = sub { unlink($newfile) };
1624 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1627 foreach my $page (keys %pagemtime) {
1628 next unless $pagemtime{$page};
1629 my $src=$pagesources{$page};
1631 $index{page}{$src}={
1632 ctime => $pagectime{$page},
1633 mtime => $pagemtime{$page},
1634 dest => $renderedfiles{$page},
1635 links => $links{$page},
1638 if (exists $depends{$page}) {
1639 $index{page}{$src}{depends} = $depends{$page};
1642 if (exists $depends_simple{$page}) {
1643 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1646 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1647 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1650 if (exists $pagestate{$page}) {
1651 foreach my $id (@hookids) {
1652 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1653 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1660 foreach my $id (@hookids) {
1661 foreach my $key (keys %{$wikistate{$id}}) {
1662 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1666 $index{version}="3";
1667 my $ret=Storable::nstore_fd(\%index, $out);
1668 return if ! defined $ret || ! $ret;
1669 close $out || error("failed saving to $newfile: $!", $cleanup);
1670 rename($newfile, "$config{wikistatedir}/indexdb") ||
1671 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1676 sub template_file ($) {
1679 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1680 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1681 $tpage=$pagesources{$tpage};
1685 my $template=srcfile($tpage, 1);
1686 if (defined $template) {
1687 return $template, $tpage, 1 if wantarray;
1691 $name=~s:/::; # avoid path traversal
1692 foreach my $dir ($config{templatedir},
1693 "$installdir/share/ikiwiki/templates") {
1694 if (-e "$dir/$name") {
1695 $template="$dir/$name";
1699 if (defined $template) {
1700 return $template, $tpage if wantarray;
1708 sub template_depends ($$;@) {
1712 my ($filename, $tpage, $untrusted)=template_file($name);
1713 if (defined $page && defined $tpage) {
1714 add_depends($page, $tpage);
1717 return unless defined $filename;
1721 my $text_ref = shift;
1722 ${$text_ref} = decode_utf8(${$text_ref});
1724 loop_context_vars => 1,
1725 die_on_bad_params => 0,
1726 filename => $filename,
1728 ($untrusted ? (no_includes => 1) : ()),
1730 return @opts if wantarray;
1732 require HTML::Template;
1733 return HTML::Template->new(@opts);
1736 sub template ($;@) {
1737 template_depends(shift, undef, @_);
1740 sub misctemplate ($$;@) {
1745 my $template=template("page.tmpl");
1748 if (exists $params{page}) {
1749 $page=delete $params{page};
1751 run_hooks(pagetemplate => sub {
1755 template => $template,
1758 templateactions($template, "");
1763 wikiname => $config{wikiname},
1764 content => $content,
1765 baseurl => baseurl(),
1766 html5 => $config{html5},
1770 return $template->output;
1773 sub templateactions ($$) {
1779 run_hooks(pageactions => sub {
1780 push @actions, map { { action => $_ } }
1781 grep { defined } shift->(page => $page);
1783 $template->param(actions => \@actions);
1785 if ($config{cgiurl} && exists $hooks{auth}) {
1786 $template->param(prefsurl => cgiurl(do => "prefs"));
1790 if ($have_actions || @actions) {
1791 $template->param(have_actions => 1);
1798 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1799 error 'hook requires type, call, and id parameters';
1802 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1804 $hooks{$param{type}}{$param{id}}=\%param;
1808 sub run_hooks ($$) {
1809 # Calls the given sub for each hook of the given type,
1810 # passing it the hook function to call.
1814 if (exists $hooks{$type}) {
1815 my (@first, @middle, @last);
1816 foreach my $id (keys %{$hooks{$type}}) {
1817 if ($hooks{$type}{$id}{first}) {
1820 elsif ($hooks{$type}{$id}{last}) {
1827 foreach my $id (@first, @middle, @last) {
1828 $sub->($hooks{$type}{$id}{call});
1836 $hooks{rcs}{rcs_update}{call}->(@_);
1839 sub rcs_prepedit ($) {
1840 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1843 sub rcs_commit (@) {
1844 $hooks{rcs}{rcs_commit}{call}->(@_);
1847 sub rcs_commit_staged (@) {
1848 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1852 $hooks{rcs}{rcs_add}{call}->(@_);
1855 sub rcs_remove ($) {
1856 $hooks{rcs}{rcs_remove}{call}->(@_);
1859 sub rcs_rename ($$) {
1860 $hooks{rcs}{rcs_rename}{call}->(@_);
1863 sub rcs_recentchanges ($) {
1864 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1868 $hooks{rcs}{rcs_diff}{call}->(@_);
1871 sub rcs_getctime ($) {
1872 $hooks{rcs}{rcs_getctime}{call}->(@_);
1875 sub rcs_getmtime ($) {
1876 $hooks{rcs}{rcs_getmtime}{call}->(@_);
1879 sub rcs_receive () {
1880 $hooks{rcs}{rcs_receive}{call}->();
1883 sub add_depends ($$;$) {
1886 my $deptype=shift || $DEPEND_CONTENT;
1888 # Is the pagespec a simple page name?
1889 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1890 $pagespec !~ /[\s*?()!]/) {
1891 $depends_simple{$page}{lc $pagespec} |= $deptype;
1895 # Add explicit dependencies for influences.
1896 my $sub=pagespec_translate($pagespec);
1897 return unless defined $sub;
1898 foreach my $p (keys %pagesources) {
1899 my $r=$sub->($p, location => $page);
1900 my $i=$r->influences;
1901 my $static=$r->influences_static;
1902 foreach my $k (keys %$i) {
1903 next unless $r || $static || $k eq $page;
1904 $depends_simple{$page}{lc $k} |= $i->{$k};
1909 $depends{$page}{$pagespec} |= $deptype;
1915 foreach my $type (@_) {
1916 if ($type eq 'presence') {
1917 $deptype |= $DEPEND_PRESENCE;
1919 elsif ($type eq 'links') {
1920 $deptype |= $DEPEND_LINKS;
1922 elsif ($type eq 'content') {
1923 $deptype |= $DEPEND_CONTENT;
1929 my $file_prune_regexp;
1930 sub file_pruned ($) {
1933 if (defined $config{include} && length $config{include}) {
1934 return 0 if $file =~ m/$config{include}/;
1937 if (! defined $file_prune_regexp) {
1938 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1939 $file_prune_regexp=qr/$file_prune_regexp/;
1941 return $file =~ m/$file_prune_regexp/;
1944 sub define_gettext () {
1945 # If translation is needed, redefine the gettext function to do it.
1946 # Otherwise, it becomes a quick no-op.
1949 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1950 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1951 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1953 $gettext_obj=eval q{
1954 use Locale::gettext q{textdomain};
1955 Locale::gettext->domain('ikiwiki')
1960 no warnings 'redefine';
1962 $getobj->() if $getobj;
1964 $gettext_obj->get(shift);
1971 $getobj->() if $getobj;
1973 $gettext_obj->nget(@_);
1976 return ($_[2] == 1 ? $_[0] : $_[1])
1994 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1998 # Injects a new function into the symbol table to replace an
1999 # exported function.
2002 # This is deep ugly perl foo, beware.
2005 if (! defined $params{parent}) {
2006 $params{parent}='::';
2007 $params{old}=\&{$params{name}};
2008 $params{name}=~s/.*:://;
2010 my $parent=$params{parent};
2011 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2012 $ns = $params{parent} . $ns;
2013 inject(%params, parent => $ns) unless $ns eq '::main::';
2014 *{$ns . $params{name}} = $params{call}
2015 if exists ${$ns}{$params{name}} &&
2016 \&{${$ns}{$params{name}}} == $params{old};
2022 sub add_link ($$;$) {
2027 push @{$links{$page}}, $link
2028 unless grep { $_ eq $link } @{$links{$page}};
2030 if (defined $type) {
2031 $typedlinks{$page}{$type}{$link} = 1;
2035 sub add_autofile ($$$) {
2038 my $generator=shift;
2040 $autofiles{$file}{plugin}=$plugin;
2041 $autofiles{$file}{generator}=$generator;
2044 sub sortspec_translate ($$) {
2046 my $reverse = shift;
2052 (-?) # group 1: perhaps negated
2055 \w+\([^\)]*\) # command(params)
2057 [^\s]+ # or anything else
2065 if ($word =~ m/^(\w+)\((.*)\)$/) {
2066 # command with parameters
2070 elsif ($word !~ m/^\w+$/) {
2071 error(sprintf(gettext("invalid sort type %s"), $word));
2082 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2083 if (defined $params) {
2084 push @data, $params;
2085 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2088 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2092 error(sprintf(gettext("unknown sort type %s"), $word));
2096 if (! length $code) {
2097 # undefined sorting method... sort arbitrarily
2106 return eval 'sub { '.$code.' }';
2109 sub pagespec_translate ($) {
2112 # Convert spec to perl code.
2116 \s* # ignore whitespace
2117 ( # 1: match a single word
2124 \w+\([^\)]*\) # command(params)
2126 [^\s()]+ # any other text
2128 \s* # ignore whitespace
2131 if (lc $word eq 'and') {
2134 elsif (lc $word eq 'or') {
2137 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2140 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2141 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2143 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2146 push @data, qq{unknown function in pagespec "$word"};
2147 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2152 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2156 if (! length $code) {
2157 $code="IkiWiki::FailReason->new('empty pagespec')";
2161 return eval 'sub { my $page=shift; '.$code.' }';
2164 sub pagespec_match ($$;@) {
2169 # Backwards compatability with old calling convention.
2171 unshift @params, 'location';
2174 my $sub=pagespec_translate($spec);
2175 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2177 return $sub->($page, @params);
2180 sub pagespec_match_list ($$;@) {
2185 # Backwards compatability with old calling convention.
2187 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2188 $params{list}=$page;
2189 $page=$params{location}; # ugh!
2192 my $sub=pagespec_translate($pagespec);
2193 error "syntax error in pagespec \"$pagespec\""
2195 my $sort=sortspec_translate($params{sort}, $params{reverse})
2196 if defined $params{sort};
2199 if (exists $params{list}) {
2200 @candidates=exists $params{filter}
2201 ? grep { ! $params{filter}->($_) } @{$params{list}}
2205 @candidates=exists $params{filter}
2206 ? grep { ! $params{filter}->($_) } keys %pagesources
2207 : keys %pagesources;
2210 # clear params, remainder is passed to pagespec
2211 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2212 my $num=$params{num};
2213 delete @params{qw{num deptype reverse sort filter list}};
2215 # when only the top matches will be returned, it's efficient to
2216 # sort before matching to pagespec,
2217 if (defined $num && defined $sort) {
2218 @candidates=IkiWiki::SortSpec::sort_pages(
2219 $sort, @candidates);
2225 my $accum=IkiWiki::SuccessReason->new();
2226 foreach my $p (@candidates) {
2227 my $r=$sub->($p, %params, location => $page);
2228 error(sprintf(gettext("cannot match pages: %s"), $r))
2229 if $r->isa("IkiWiki::ErrorReason");
2230 unless ($r || $r->influences_static) {
2231 $r->remove_influence($p);
2236 last if defined $num && ++$count == $num;
2240 # Add simple dependencies for accumulated influences.
2241 my $i=$accum->influences;
2242 foreach my $k (keys %$i) {
2243 $depends_simple{$page}{lc $k} |= $i->{$k};
2246 # when all matches will be returned, it's efficient to
2247 # sort after matching
2248 if (! defined $num && defined $sort) {
2249 return IkiWiki::SortSpec::sort_pages(
2257 sub pagespec_valid ($) {
2260 return defined pagespec_translate($spec);
2264 my $re=quotemeta(shift);
2270 package IkiWiki::FailReason;
2273 '""' => sub { $_[0][0] },
2275 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2276 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2277 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2281 our @ISA = 'IkiWiki::SuccessReason';
2283 package IkiWiki::SuccessReason;
2286 '""' => sub { $_[0][0] },
2288 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2289 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2290 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2297 return bless [$value, {@_}], $class;
2302 $this->[1]={@_} if @_;
2303 my %i=%{$this->[1]};
2308 sub influences_static {
2309 return ! $_[0][1]->{""};
2312 sub merge_influences {
2317 if (! $anded || (($this || %{$this->[1]}) &&
2318 ($other || %{$other->[1]}))) {
2319 foreach my $influence (keys %{$other->[1]}) {
2320 $this->[1]{$influence} |= $other->[1]{$influence};
2329 sub remove_influence {
2333 delete $this->[1]{$torm};
2336 package IkiWiki::ErrorReason;
2338 our @ISA = 'IkiWiki::FailReason';
2340 package IkiWiki::PageSpec;
2346 if ($path =~ m!^\./!) {
2347 $from=~s#/?[^/]+$## if defined $from;
2349 $path="$from/$path" if defined $from && length $from;
2355 sub match_glob ($$;@) {
2360 $glob=derel($glob, $params{location});
2362 my $regexp=IkiWiki::glob2re($glob);
2363 if ($page=~/^$regexp$/i) {
2364 if (! IkiWiki::isinternal($page) || $params{internal}) {
2365 return IkiWiki::SuccessReason->new("$glob matches $page");
2368 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2372 return IkiWiki::FailReason->new("$glob does not match $page");
2376 sub match_internal ($$;@) {
2377 return match_glob(shift, shift, @_, internal => 1)
2380 sub match_page ($$;@) {
2382 my $match=match_glob($page, shift, @_);
2383 if ($match && ! (exists $IkiWiki::pagesources{$page}
2384 && defined IkiWiki::pagetype($IkiWiki::pagesources{$page}))) {
2385 return IkiWiki::FailReason->new("$page is not a page");
2392 sub match_link ($$;@) {
2397 $link=derel($link, $params{location});
2398 my $from=exists $params{location} ? $params{location} : '';
2399 my $linktype=$params{linktype};
2401 if (defined $linktype) {
2402 $qualifier=" with type $linktype";
2405 my $links = $IkiWiki::links{$page};
2406 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2407 unless $links && @{$links};
2408 my $bestlink = IkiWiki::bestlink($from, $link);
2409 foreach my $p (@{$links}) {
2410 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2412 if (length $bestlink) {
2413 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2414 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2418 if (match_glob($p, $link, %params)) {
2419 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2421 my ($p_rel)=$p=~/^\/?(.*)/;
2423 if (match_glob($p_rel, $link, %params)) {
2424 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2428 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2431 sub match_backlink ($$;@) {
2432 my $ret=match_link($_[1], $_[0], @_);
2433 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2437 sub match_created_before ($$;@) {
2442 $testpage=derel($testpage, $params{location});
2444 if (exists $IkiWiki::pagectime{$testpage}) {
2445 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2446 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2449 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2453 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2457 sub match_created_after ($$;@) {
2462 $testpage=derel($testpage, $params{location});
2464 if (exists $IkiWiki::pagectime{$testpage}) {
2465 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2466 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2469 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2473 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2477 sub match_creation_day ($$;@) {
2478 if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2479 return IkiWiki::SuccessReason->new('creation_day matched');
2482 return IkiWiki::FailReason->new('creation_day did not match');
2486 sub match_creation_month ($$;@) {
2487 if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2488 return IkiWiki::SuccessReason->new('creation_month matched');
2491 return IkiWiki::FailReason->new('creation_month did not match');
2495 sub match_creation_year ($$;@) {
2496 if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2497 return IkiWiki::SuccessReason->new('creation_year matched');
2500 return IkiWiki::FailReason->new('creation_year did not match');
2504 sub match_user ($$;@) {
2509 my $regexp=IkiWiki::glob2re($user);
2511 if (! exists $params{user}) {
2512 return IkiWiki::ErrorReason->new("no user specified");
2515 if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2516 return IkiWiki::SuccessReason->new("user is $user");
2518 elsif (! defined $params{user}) {
2519 return IkiWiki::FailReason->new("not logged in");
2522 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2526 sub match_admin ($$;@) {
2531 if (! exists $params{user}) {
2532 return IkiWiki::ErrorReason->new("no user specified");
2535 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2536 return IkiWiki::SuccessReason->new("user is an admin");
2538 elsif (! defined $params{user}) {
2539 return IkiWiki::FailReason->new("not logged in");
2542 return IkiWiki::FailReason->new("user is not an admin");
2546 sub match_ip ($$;@) {
2551 if (! exists $params{ip}) {
2552 return IkiWiki::ErrorReason->new("no IP specified");
2555 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2556 return IkiWiki::SuccessReason->new("IP is $ip");
2559 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2563 package IkiWiki::SortSpec;
2565 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2566 # are easily available in this namespace, for cmp functions to use them.
2573 IkiWiki::pagetitle(IkiWiki::basename($a))
2575 IkiWiki::pagetitle(IkiWiki::basename($b))
2578 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2579 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }