9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %wikistate %renderedfiles %oldrenderedfiles
16 %pagesources %destsources %depends %depends_simple %hooks
17 %forcerebuild %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage deptype
21 add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime will_render gettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources);
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("pagespec_translate");
41 memoize("template_file");
47 description => "name of the wiki",
54 example => 'me@example.com',
55 description => "contact email for wiki",
62 description => "users who are wiki admins",
69 description => "users who are banned from the wiki",
76 example => "$ENV{HOME}/wiki",
77 description => "where the source of the wiki is located",
84 example => "/var/www/wiki",
85 description => "where to build the wiki",
92 example => "http://example.com/wiki",
93 description => "base url to the wiki",
100 example => "http://example.com/wiki/ikiwiki.cgi",
101 description => "url to the ikiwiki.cgi",
108 example => "/var/www/wiki/ikiwiki.cgi",
109 description => "filename of cgi wrapper to generate",
116 description => "mode for cgi_wrapper (can safely be made suid)",
123 description => "rcs backend to use",
124 safe => 0, # don't allow overriding
129 default => [qw{mdwn link inline meta htmlscrubber passwordauth
130 openid signinedit lockedit conditional
131 recentchanges parentlinks editpage}],
132 description => "plugins to enable by default",
139 description => "plugins to add to the default configuration",
146 description => "plugins to disable",
152 default => "$installdir/share/ikiwiki/templates",
153 description => "location of template files",
161 description => "additional directories containing template files",
167 default => "$installdir/share/ikiwiki/basewiki",
168 description => "base wiki source location",
175 default => "$installdir/share/ikiwiki",
176 description => "parent directory containing additional underlays",
183 description => "wrappers to generate",
190 description => "additional underlays to use",
197 description => "display verbose messages?",
204 description => "log to syslog?",
211 description => "create output files named page/index.html?",
212 safe => 0, # changing requires manual transition
215 prefix_directives => {
218 description => "use '!'-prefixed preprocessor directives?",
219 safe => 0, # changing requires manual transition
225 description => "use page/index.mdwn source files",
232 description => "enable Discussion pages?",
238 default => gettext("Discussion"),
239 description => "name of Discussion pages",
246 description => "only send cookies over SSL connections?",
254 description => "extension to use for new pages",
255 safe => 0, # not sanitized
261 description => "extension to use for html files",
262 safe => 0, # not sanitized
268 description => "strftime format string to display date",
276 example => "en_US.UTF-8",
277 description => "UTF-8 locale to use",
286 description => "put user pages below specified page",
293 description => "how many backlinks to show before hiding excess (0 to show all)",
300 description => "attempt to hardlink source files? (optimisation for large files)",
302 safe => 0, # paranoia
308 description => "force ikiwiki to use a particular umask",
310 safe => 0, # paranoia
315 example => "ikiwiki",
316 description => "group for wrappers to run in",
318 safe => 0, # paranoia
324 example => "$ENV{HOME}/.ikiwiki/",
325 description => "extra library and plugin directory",
327 safe => 0, # directory
333 description => "environment variables",
334 safe => 0, # paranoia
341 description => "regexp of source files to ignore",
346 wiki_file_prune_regexps => {
348 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
349 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
350 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
351 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
352 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
353 description => "regexps of source files to ignore",
359 description => "specifies the characters that are allowed in source filenames",
360 default => "-[:alnum:]+/.:_",
364 wiki_file_regexp => {
366 description => "regexp of legal source files",
370 web_commit_regexp => {
372 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
373 description => "regexp to parse web commits from logs",
380 description => "run as a cgi",
384 cgi_disable_uploads => {
387 description => "whether CGI should accept file uploads",
394 description => "run as a post-commit hook",
401 description => "running in rebuild mode",
408 description => "running in setup mode",
415 description => "running in refresh mode",
422 description => "running in receive test mode",
429 description => "running in getctime mode",
436 description => "running in w3mmode",
443 description => "path to the .ikiwiki directory holding ikiwiki state",
450 description => "path to setup file",
454 allow_symlinks_before_srcdir => {
457 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
463 sub defaultconfig () {
466 foreach my $key (keys %s) {
467 push @ret, $key, $s{$key}->{default};
474 # locale stuff; avoid LC_ALL since it overrides everything
475 if (defined $ENV{LC_ALL}) {
476 $ENV{LANG} = $ENV{LC_ALL};
479 if (defined $config{locale}) {
480 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
481 $ENV{LANG}=$config{locale};
486 if (! defined $config{wiki_file_regexp}) {
487 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
490 if (ref $config{ENV} eq 'HASH') {
491 foreach my $val (keys %{$config{ENV}}) {
492 $ENV{$val}=$config{ENV}{$val};
496 if ($config{w3mmode}) {
497 eval q{use Cwd q{abs_path}};
499 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
500 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
501 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
502 unless $config{cgiurl} =~ m!file:///!;
503 $config{url}="file://".$config{destdir};
506 if ($config{cgi} && ! length $config{url}) {
507 error(gettext("Must specify url to wiki with --url when using --cgi"));
510 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
511 unless exists $config{wikistatedir} && defined $config{wikistatedir};
513 if (defined $config{umask}) {
514 umask(possibly_foolish_untaint($config{umask}));
517 run_hooks(checkconfig => sub { shift->() });
525 foreach my $dir (@INC, $config{libdir}) {
526 next unless defined $dir && length $dir;
527 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
528 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
532 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
533 next unless defined $dir && length $dir;
534 foreach my $file (glob("$dir/plugins/*")) {
535 $ret{basename($file)}=1 if -x $file;
543 if (defined $config{libdir} && length $config{libdir}) {
544 unshift @INC, possibly_foolish_untaint($config{libdir});
547 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
552 if (exists $hooks{rcs}) {
553 error(gettext("cannot use multiple rcs plugins"));
555 loadplugin($config{rcs});
557 if (! exists $hooks{rcs}) {
561 run_hooks(getopt => sub { shift->() });
562 if (grep /^-/, @ARGV) {
563 print STDERR "Unknown option (or missing parameter): $_\n"
564 foreach grep /^-/, @ARGV;
574 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
576 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
577 "$installdir/lib/ikiwiki") {
578 if (defined $dir && -x "$dir/plugins/$plugin") {
579 eval { require IkiWiki::Plugin::external };
582 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
584 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
585 $loaded_plugins{$plugin}=1;
590 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
593 error("Failed to load plugin $mod: $@");
595 $loaded_plugins{$plugin}=1;
602 log_message('err' => $message) if $config{syslog};
603 if (defined $cleaner) {
610 return unless $config{verbose};
611 return log_message(debug => @_);
615 sub log_message ($$) {
618 if ($config{syslog}) {
621 Sys::Syslog::setlogsock('unix');
622 Sys::Syslog::openlog('ikiwiki', '', 'user');
626 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
629 elsif (! $config{cgi}) {
633 return print STDERR "@_\n";
637 sub possibly_foolish_untaint ($) {
639 my ($untainted)=$tainted=~/(.*)/s;
659 return exists $pagesources{$page} &&
660 $pagesources{$page} =~ /\._([^.]+)$/;
666 if ($file =~ /\.([^.]+)$/) {
667 return $1 if exists $hooks{htmlize}{$1};
669 my $base=basename($file);
670 if (exists $hooks{htmlize}{$base} &&
671 $hooks{htmlize}{$base}{noextension}) {
682 if (exists $pagename_cache{$file}) {
683 return $pagename_cache{$file};
686 my $type=pagetype($file);
688 $page=~s/\Q.$type\E*$//
689 if defined $type && !$hooks{htmlize}{$type}{keepextension}
690 && !$hooks{htmlize}{$type}{noextension};
691 if ($config{indexpages} && $page=~/(.*)\/index$/) {
695 $pagename_cache{$file} = $page;
699 sub newpagefile ($$) {
703 if (! $config{indexpages} || $page eq 'index') {
704 return $page.".".$type;
707 return $page."/index.".$type;
711 sub targetpage ($$;$) {
716 if (defined $filename) {
717 return $page."/".$filename.".".$ext;
719 elsif (! $config{usedirs} || $page eq 'index') {
720 return $page.".".$ext;
723 return $page."/index.".$ext;
730 return targetpage($page, $config{htmlext});
737 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
738 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
739 return "$dir/$file", stat(_) if -e "$dir/$file";
741 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
746 return (srcfile_stat(@_))[0];
749 sub add_underlay ($) {
753 $dir="$config{underlaydirbase}/$dir";
756 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
757 unshift @{$config{underlaydirs}}, $dir;
763 sub readfile ($;$$) {
769 error("cannot read a symlink ($file)");
773 open (my $in, "<", $file) || error("failed to read $file: $!");
774 binmode($in) if ($binary);
775 return \*$in if $wantfd;
777 # check for invalid utf-8, and toss it back to avoid crashes
778 if (! utf8::valid($ret)) {
779 $ret=encode_utf8($ret);
781 close $in || error("failed to read $file: $!");
785 sub prep_writefile ($$) {
790 while (length $test) {
791 if (-l "$destdir/$test") {
792 error("cannot write to a symlink ($test)");
794 $test=dirname($test);
797 my $dir=dirname("$destdir/$file");
800 foreach my $s (split(m!/+!, $dir)) {
803 mkdir($d) || error("failed to create directory $d: $!");
811 sub writefile ($$$;$$) {
812 my $file=shift; # can include subdirs
813 my $destdir=shift; # directory to put file in
818 prep_writefile($file, $destdir);
820 my $newfile="$destdir/$file.ikiwiki-new";
822 error("cannot write to a symlink ($newfile)");
825 my $cleanup = sub { unlink($newfile) };
826 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
827 binmode($out) if ($binary);
829 $writer->(\*$out, $cleanup);
832 print $out $content or error("failed writing to $newfile: $!", $cleanup);
834 close $out || error("failed saving $newfile: $!", $cleanup);
835 rename($newfile, "$destdir/$file") ||
836 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
842 sub will_render ($$;$) {
847 # Important security check.
848 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
849 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
850 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
853 if (! $clear || $cleared{$page}) {
854 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
857 foreach my $old (@{$renderedfiles{$page}}) {
858 delete $destsources{$old};
860 $renderedfiles{$page}=[$dest];
863 $destsources{$dest}=$page;
873 if ($link=~s/^\/+//) {
881 $l.="/" if length $l;
884 if (exists $pagesources{$l}) {
887 elsif (exists $pagecase{lc $l}) {
888 return $pagecase{lc $l};
890 } while $cwd=~s{/?[^/]+$}{};
892 if (length $config{userdir}) {
893 my $l = "$config{userdir}/".lc($link);
894 if (exists $pagesources{$l}) {
897 elsif (exists $pagecase{lc $l}) {
898 return $pagecase{lc $l};
902 #print STDERR "warning: page $page, broken link: $link\n";
906 sub isinlinableimage ($) {
909 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
912 sub pagetitle ($;$) {
917 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
920 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
928 # support use w/o %config set
929 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
930 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
936 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
937 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
944 return $config{cgiurl}."?".
945 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
951 return "$config{url}/" if ! defined $page;
953 $page=htmlpage($page);
955 $page=~s/[^\/]+\//..\//g;
960 # Work around very innefficient behavior in File::Spec if abs2rel
961 # is passed two relative paths. It's much faster if paths are
962 # absolute! (Debian bug #376658; fixed in debian unstable now)
967 my $ret=File::Spec->abs2rel($path, $base);
968 $ret=~s/^// if defined $ret;
972 sub displaytime ($;$) {
973 # Plugins can override this function to mark up the time to
975 return '<span class="date">'.formattime(@_).'</span>';
978 sub formattime ($;$) {
979 # Plugins can override this function to format the time.
982 if (! defined $format) {
983 $format=$config{timeformat};
986 # strftime doesn't know about encodings, so make sure
987 # its output is properly treated as utf8
988 return decode_utf8(POSIX::strftime($format, localtime($time)));
991 sub beautify_urlpath ($) {
994 # Ensure url is not an empty link, and if necessary,
995 # add ./ to avoid colon confusion.
996 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1000 if ($config{usedirs}) {
1001 $url =~ s!/index.$config{htmlext}$!/!;
1013 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1016 if (! $destsources{$to}) {
1021 return $config{url}.beautify_urlpath("/".$to);
1024 my $link = abs2rel($to, dirname(htmlpage($from)));
1026 return beautify_urlpath($link);
1029 sub htmllink ($$$;@) {
1030 my $lpage=shift; # the page doing the linking
1031 my $page=shift; # the page that will contain the link (different for inline)
1038 if (! $opts{forcesubpage}) {
1039 $bestlink=bestlink($lpage, $link);
1042 $bestlink="$lpage/".lc($link);
1046 if (defined $opts{linktext}) {
1047 $linktext=$opts{linktext};
1050 $linktext=pagetitle(basename($link));
1053 return "<span class=\"selflink\">$linktext</span>"
1054 if length $bestlink && $page eq $bestlink &&
1055 ! defined $opts{anchor};
1057 if (! $destsources{$bestlink}) {
1058 $bestlink=htmlpage($bestlink);
1060 if (! $destsources{$bestlink}) {
1061 return $linktext unless length $config{cgiurl};
1062 return "<span class=\"createlink\"><a href=\"".
1068 "\" rel=\"nofollow\">?</a>$linktext</span>"
1072 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1073 $bestlink=beautify_urlpath($bestlink);
1075 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1076 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1079 if (defined $opts{anchor}) {
1080 $bestlink.="#".$opts{anchor};
1084 foreach my $attr (qw{rel class title}) {
1085 if (defined $opts{$attr}) {
1086 push @attrs, " $attr=\"$opts{$attr}\"";
1090 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1095 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1098 sub openiduser ($) {
1101 if ($user =~ m!^https?://! &&
1102 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1105 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1106 # this works in at least 2.x
1107 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1110 # this only works in 1.x
1111 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1112 $display=$oid->display;
1115 # Convert "user.somehost.com" to "user [somehost.com]"
1116 # (also "user.somehost.co.uk")
1117 if ($display !~ /\[/) {
1118 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1120 # Convert "http://somehost.com/user" to "user [somehost.com]".
1121 # (also "https://somehost.com/user/")
1122 if ($display !~ /\[/) {
1123 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1125 $display=~s!^https?://!!; # make sure this is removed
1126 eval q{use CGI 'escapeHTML'};
1128 return escapeHTML($display);
1133 sub htmlize ($$$$) {
1139 my $oneline = $content !~ /\n/;
1141 if (exists $hooks{htmlize}{$type}) {
1142 $content=$hooks{htmlize}{$type}{call}->(
1144 content => $content,
1148 error("htmlization of $type not supported");
1151 run_hooks(sanitize => sub {
1154 destpage => $destpage,
1155 content => $content,
1160 # hack to get rid of enclosing junk added by markdown
1161 # and other htmlizers
1162 $content=~s/^<p>//i;
1163 $content=~s/<\/p>$//i;
1175 run_hooks(linkify => sub {
1178 destpage => $destpage,
1179 content => $content,
1187 our $preprocess_preview=0;
1188 sub preprocess ($$$;$$) {
1189 my $page=shift; # the page the data comes from
1190 my $destpage=shift; # the page the data will appear in (different for inline)
1195 # Using local because it needs to be set within any nested calls
1197 local $preprocess_preview=$preview if defined $preview;
1204 $params="" if ! defined $params;
1206 if (length $escape) {
1207 return "[[$prefix$command $params]]";
1209 elsif (exists $hooks{preprocess}{$command}) {
1210 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1211 # Note: preserve order of params, some plugins may
1212 # consider it significant.
1214 while ($params =~ m{
1215 (?:([-\w]+)=)? # 1: named parameter key?
1217 """(.*?)""" # 2: triple-quoted value
1219 "([^"]+)" # 3: single-quoted value
1221 (\S+) # 4: unquoted value
1223 (?:\s+|$) # delimiter to next param
1233 elsif (defined $3) {
1236 elsif (defined $4) {
1241 push @params, $key, $val;
1244 push @params, $val, '';
1247 if ($preprocessing{$page}++ > 3) {
1248 # Avoid loops of preprocessed pages preprocessing
1249 # other pages that preprocess them, etc.
1250 return "[[!$command <span class=\"error\">".
1251 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1252 $page, $preprocessing{$page}).
1258 $hooks{preprocess}{$command}{call}->(
1261 destpage => $destpage,
1262 preview => $preprocess_preview,
1268 $ret="[[!$command <span class=\"error\">".
1269 gettext("Error").": $error"."</span>]]";
1273 # use void context during scan pass
1275 $hooks{preprocess}{$command}{call}->(
1278 destpage => $destpage,
1279 preview => $preprocess_preview,
1284 $preprocessing{$page}--;
1288 return "[[$prefix$command $params]]";
1293 if ($config{prefix_directives}) {
1296 \[\[(!) # directive open; 2: prefix
1297 ([-\w]+) # 3: command
1298 ( # 4: the parameters..
1299 \s+ # Must have space if parameters present
1301 (?:[-\w]+=)? # named parameter key?
1303 """.*?""" # triple-quoted value
1305 "[^"]+" # single-quoted value
1307 [^"\s\]]+ # unquoted value
1309 \s* # whitespace or end
1312 *)? # 0 or more parameters
1313 \]\] # directive closed
1319 \[\[(!?) # directive open; 2: optional prefix
1320 ([-\w]+) # 3: command
1322 ( # 4: the parameters..
1324 (?:[-\w]+=)? # named parameter key?
1326 """.*?""" # triple-quoted value
1328 "[^"]+" # single-quoted value
1330 [^"\s\]]+ # unquoted value
1332 \s* # whitespace or end
1335 *) # 0 or more parameters
1336 \]\] # directive closed
1340 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1349 run_hooks(filter => sub {
1350 $content=shift->(page => $page, destpage => $destpage,
1351 content => $content);
1358 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1361 sub check_canedit ($$$;$) {
1368 run_hooks(canedit => sub {
1369 return if defined $canedit;
1370 my $ret=shift->($page, $q, $session);
1375 elsif (ref $ret eq 'CODE') {
1376 $ret->() unless $nonfatal;
1379 elsif (defined $ret) {
1380 error($ret) unless $nonfatal;
1385 return defined $canedit ? $canedit : 1;
1388 sub check_content (@) {
1391 return 1 if ! exists $hooks{checkcontent}; # optimisation
1393 if (exists $pagesources{$params{page}}) {
1395 my %old=map { $_ => 1 }
1396 split("\n", readfile(srcfile($pagesources{$params{page}})));
1397 foreach my $line (split("\n", $params{content})) {
1398 push @diff, $line if ! exists $old{$line};
1400 $params{diff}=join("\n", @diff);
1404 run_hooks(checkcontent => sub {
1405 return if defined $ok;
1406 my $ret=shift->(%params);
1411 elsif (ref $ret eq 'CODE') {
1412 $ret->() unless $params{nonfatal};
1415 elsif (defined $ret) {
1416 error($ret) unless $params{nonfatal};
1422 return defined $ok ? $ok : 1;
1428 # Take an exclusive lock on the wiki to prevent multiple concurrent
1429 # run issues. The lock will be dropped on program exit.
1430 if (! -d $config{wikistatedir}) {
1431 mkdir($config{wikistatedir});
1433 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1434 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1435 if (! flock($wikilock, 2)) { # LOCK_EX
1436 error("failed to get lock");
1442 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1443 return close($wikilock) if $wikilock;
1449 sub commit_hook_enabled () {
1450 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1451 error("cannot write to $config{wikistatedir}/commitlock: $!");
1452 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1453 close($commitlock) || error("failed closing commitlock: $!");
1456 close($commitlock) || error("failed closing commitlock: $!");
1460 sub disable_commit_hook () {
1461 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1462 error("cannot write to $config{wikistatedir}/commitlock: $!");
1463 if (! flock($commitlock, 2)) { # LOCK_EX
1464 error("failed to get commit lock");
1469 sub enable_commit_hook () {
1470 return close($commitlock) if $commitlock;
1475 %oldrenderedfiles=%pagectime=();
1476 if (! $config{rebuild}) {
1477 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1478 %destsources=%renderedfiles=%pagecase=%pagestate=
1482 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1483 if (-e "$config{wikistatedir}/index") {
1484 system("ikiwiki-transition", "indexdb", $config{srcdir});
1485 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1492 my $index=Storable::fd_retrieve($in);
1493 if (! defined $index) {
1498 if (exists $index->{version} && ! ref $index->{version}) {
1499 $pages=$index->{page};
1500 %wikistate=%{$index->{state}};
1507 foreach my $src (keys %$pages) {
1508 my $d=$pages->{$src};
1509 my $page=pagename($src);
1510 $pagectime{$page}=$d->{ctime};
1511 if (! $config{rebuild}) {
1512 $pagesources{$page}=$src;
1513 $pagemtime{$page}=$d->{mtime};
1514 $renderedfiles{$page}=$d->{dest};
1515 if (exists $d->{links} && ref $d->{links}) {
1516 $links{$page}=$d->{links};
1517 $oldlinks{$page}=[@{$d->{links}}];
1519 if (ref $d->{depends_simple} eq 'ARRAY') {
1521 $depends_simple{$page}={
1522 map { $_ => 1 } @{$d->{depends_simple}}
1525 elsif (exists $d->{depends_simple}) {
1526 $depends_simple{$page}=$d->{depends_simple};
1528 if (exists $d->{dependslist}) {
1531 map { $_ => $DEPEND_CONTENT }
1532 @{$d->{dependslist}}
1535 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1537 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1539 elsif (exists $d->{depends}) {
1540 $depends{$page}=$d->{depends};
1542 if (exists $d->{state}) {
1543 $pagestate{$page}=$d->{state};
1546 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1548 foreach my $page (keys %pagesources) {
1549 $pagecase{lc $page}=$page;
1551 foreach my $page (keys %renderedfiles) {
1552 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1558 run_hooks(savestate => sub { shift->() });
1561 foreach my $type (keys %hooks) {
1562 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1564 my @hookids=keys %hookids;
1566 if (! -d $config{wikistatedir}) {
1567 mkdir($config{wikistatedir});
1569 my $newfile="$config{wikistatedir}/indexdb.new";
1570 my $cleanup = sub { unlink($newfile) };
1571 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1574 foreach my $page (keys %pagemtime) {
1575 next unless $pagemtime{$page};
1576 my $src=$pagesources{$page};
1578 $index{page}{$src}={
1579 ctime => $pagectime{$page},
1580 mtime => $pagemtime{$page},
1581 dest => $renderedfiles{$page},
1582 links => $links{$page},
1585 if (exists $depends{$page}) {
1586 $index{page}{$src}{depends} = $depends{$page};
1589 if (exists $depends_simple{$page}) {
1590 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1593 if (exists $pagestate{$page}) {
1594 foreach my $id (@hookids) {
1595 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1596 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1603 foreach my $id (@hookids) {
1604 foreach my $key (keys %{$wikistate{$id}}) {
1605 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1609 $index{version}="3";
1610 my $ret=Storable::nstore_fd(\%index, $out);
1611 return if ! defined $ret || ! $ret;
1612 close $out || error("failed saving to $newfile: $!", $cleanup);
1613 rename($newfile, "$config{wikistatedir}/indexdb") ||
1614 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1619 sub template_file ($) {
1622 foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1623 "$installdir/share/ikiwiki/templates") {
1624 return "$dir/$template" if -e "$dir/$template";
1629 sub template_params (@) {
1630 my $filename=template_file(shift);
1632 if (! defined $filename) {
1633 return if wantarray;
1639 my $text_ref = shift;
1640 ${$text_ref} = decode_utf8(${$text_ref});
1642 filename => $filename,
1643 loop_context_vars => 1,
1644 die_on_bad_params => 0,
1647 return wantarray ? @ret : {@ret};
1650 sub template ($;@) {
1651 require HTML::Template;
1652 return HTML::Template->new(template_params(@_));
1655 sub misctemplate ($$;@) {
1659 my $template=template("misc.tmpl");
1662 indexlink => indexlink(),
1663 wikiname => $config{wikiname},
1664 pagebody => $pagebody,
1665 baseurl => baseurl(),
1668 run_hooks(pagetemplate => sub {
1669 shift->(page => "", destpage => "", template => $template);
1671 return $template->output;
1677 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1678 error 'hook requires type, call, and id parameters';
1681 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1683 $hooks{$param{type}}{$param{id}}=\%param;
1687 sub run_hooks ($$) {
1688 # Calls the given sub for each hook of the given type,
1689 # passing it the hook function to call.
1693 if (exists $hooks{$type}) {
1694 my (@first, @middle, @last);
1695 foreach my $id (keys %{$hooks{$type}}) {
1696 if ($hooks{$type}{$id}{first}) {
1699 elsif ($hooks{$type}{$id}{last}) {
1706 foreach my $id (@first, @middle, @last) {
1707 $sub->($hooks{$type}{$id}{call});
1715 $hooks{rcs}{rcs_update}{call}->(@_);
1718 sub rcs_prepedit ($) {
1719 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1722 sub rcs_commit ($$$;$$) {
1723 $hooks{rcs}{rcs_commit}{call}->(@_);
1726 sub rcs_commit_staged ($$$) {
1727 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1731 $hooks{rcs}{rcs_add}{call}->(@_);
1734 sub rcs_remove ($) {
1735 $hooks{rcs}{rcs_remove}{call}->(@_);
1738 sub rcs_rename ($$) {
1739 $hooks{rcs}{rcs_rename}{call}->(@_);
1742 sub rcs_recentchanges ($) {
1743 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1747 $hooks{rcs}{rcs_diff}{call}->(@_);
1750 sub rcs_getctime ($) {
1751 $hooks{rcs}{rcs_getctime}{call}->(@_);
1754 sub rcs_receive () {
1755 $hooks{rcs}{rcs_receive}{call}->();
1758 sub add_depends ($$;$) {
1761 my $deptype=shift || $DEPEND_CONTENT;
1763 # Is the pagespec a simple page name?
1764 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1765 $pagespec !~ /[\s*?()!]/) {
1766 $depends_simple{$page}{lc $pagespec} |= $deptype;
1770 # Add explicit dependencies for influences.
1771 my $sub=pagespec_translate($pagespec);
1773 foreach my $p (keys %pagesources) {
1774 my $r=$sub->($p, location => $page);
1775 my $i=$r->influences;
1776 foreach my $k (keys %$i) {
1777 $depends_simple{$page}{lc $k} |= $i->{$k};
1779 last if $r->influences_static;
1782 $depends{$page}{$pagespec} |= $deptype;
1788 foreach my $type (@_) {
1789 if ($type eq 'presence') {
1790 $deptype |= $DEPEND_PRESENCE;
1792 elsif ($type eq 'links') {
1793 $deptype |= $DEPEND_LINKS;
1795 elsif ($type eq 'content') {
1796 $deptype |= $DEPEND_CONTENT;
1802 sub file_pruned ($;$) {
1806 $file=File::Spec->canonpath($file);
1807 my $base=File::Spec->canonpath(shift);
1808 return if $file eq $base;
1809 $file =~ s#^\Q$base\E/+##;
1812 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1813 return $file =~ m/$regexp/;
1816 sub define_gettext () {
1817 # If translation is needed, redefine the gettext function to do it.
1818 # Otherwise, it becomes a quick no-op.
1819 no warnings 'redefine';
1820 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1821 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1822 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1824 my $gettext_obj=eval q{
1825 use Locale::gettext q{textdomain};
1826 Locale::gettext->domain('ikiwiki')
1830 $gettext_obj->get(shift);
1838 *gettext=sub { return shift };
1850 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1854 # Injects a new function into the symbol table to replace an
1855 # exported function.
1858 # This is deep ugly perl foo, beware.
1861 if (! defined $params{parent}) {
1862 $params{parent}='::';
1863 $params{old}=\&{$params{name}};
1864 $params{name}=~s/.*:://;
1866 my $parent=$params{parent};
1867 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1868 $ns = $params{parent} . $ns;
1869 inject(%params, parent => $ns) unless $ns eq '::main::';
1870 *{$ns . $params{name}} = $params{call}
1871 if exists ${$ns}{$params{name}} &&
1872 \&{${$ns}{$params{name}}} == $params{old};
1882 push @{$links{$page}}, $link
1883 unless grep { $_ eq $link } @{$links{$page}};
1886 sub pagespec_translate ($) {
1889 # Convert spec to perl code.
1893 \s* # ignore whitespace
1894 ( # 1: match a single word
1901 \w+\([^\)]*\) # command(params)
1903 [^\s()]+ # any other text
1905 \s* # ignore whitespace
1908 if (lc $word eq 'and') {
1911 elsif (lc $word eq 'or') {
1914 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1917 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1918 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1920 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1923 push @data, qq{unknown function in pagespec "$word"};
1924 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1929 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1933 if (! length $code) {
1934 $code="IkiWiki::FailReason->new('empty pagespec')";
1938 return eval 'sub { my $page=shift; '.$code.' }';
1941 sub pagespec_match ($$;@) {
1946 # Backwards compatability with old calling convention.
1948 unshift @params, 'location';
1951 my $sub=pagespec_translate($spec);
1952 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1953 if $@ || ! defined $sub;
1954 return $sub->($page, @params);
1957 sub pagespec_match_list ($$;@) {
1962 # Backwards compatability with old calling convention.
1964 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
1965 $params{list}=$page;
1966 $page=$params{location}; # ugh!
1969 my $sub=pagespec_translate($pagespec);
1970 error "syntax error in pagespec \"$pagespec\""
1971 if $@ || ! defined $sub;
1974 if (exists $params{list}) {
1975 @candidates=exists $params{filter}
1976 ? grep { ! $params{filter}->($_) } @{$params{list}}
1980 @candidates=exists $params{filter}
1981 ? grep { ! $params{filter}->($_) } keys %pagesources
1982 : keys %pagesources;
1985 if (defined $params{sort}) {
1987 if ($params{sort} eq 'title') {
1988 $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
1990 elsif ($params{sort} eq 'title_natural') {
1991 eval q{use Sort::Naturally};
1993 error(gettext("Sort::Naturally needed for title_natural sort"));
1995 $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
1997 elsif ($params{sort} eq 'mtime') {
1998 $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
2000 elsif ($params{sort} eq 'age') {
2001 $f=sub { $pagectime{$b} <=> $pagectime{$a} };
2004 error sprintf(gettext("unknown sort type %s"), $params{sort});
2006 @candidates = sort { &$f } @candidates;
2009 @candidates=reverse(@candidates) if $params{reverse};
2011 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2013 # clear params, remainder is passed to pagespec
2014 my $num=$params{num};
2015 delete @params{qw{num deptype reverse sort filter list}};
2020 my $accum=IkiWiki::SuccessReason->new();
2021 foreach my $p (@candidates) {
2022 my $r=$sub->($p, %params, location => $page);
2023 error(sprintf(gettext("cannot match pages: %s"), $r))
2024 if $r->isa("IkiWiki::ErrorReason");
2028 last if defined $num && ++$count == $num;
2032 # Add simple dependencies for accumulated influences.
2033 my $i=$accum->influences;
2034 foreach my $k (keys %$i) {
2035 $depends_simple{$page}{lc $k} |= $i->{$k};
2041 sub pagespec_valid ($) {
2044 my $sub=pagespec_translate($spec);
2049 my $re=quotemeta(shift);
2055 package IkiWiki::FailReason;
2058 '""' => sub { $_[0][0] },
2060 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2061 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2062 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2066 our @ISA = 'IkiWiki::SuccessReason';
2068 package IkiWiki::SuccessReason;
2071 '""' => sub { $_[0][0] },
2073 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2074 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2075 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2082 return bless [$value, {@_}], $class;
2087 $this->[1]={@_} if @_;
2088 my %i=%{$this->[1]};
2093 sub influences_static {
2094 return ! $_[0][1]->{""};
2097 sub merge_influences {
2102 if (! $anded || (($this || %{$this->[1]}) &&
2103 ($other || %{$other->[1]}))) {
2104 foreach my $influence (keys %{$other->[1]}) {
2105 $this->[1]{$influence} |= $other->[1]{$influence};
2114 package IkiWiki::ErrorReason;
2116 our @ISA = 'IkiWiki::FailReason';
2118 package IkiWiki::PageSpec;
2124 if ($path =~ m!^\./!) {
2125 $from=~s#/?[^/]+$## if defined $from;
2127 $path="$from/$path" if length $from;
2133 sub match_glob ($$;@) {
2138 $glob=derel($glob, $params{location});
2140 my $regexp=IkiWiki::glob2re($glob);
2141 if ($page=~/^$regexp$/i) {
2142 if (! IkiWiki::isinternal($page) || $params{internal}) {
2143 return IkiWiki::SuccessReason->new("$glob matches $page");
2146 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2150 return IkiWiki::FailReason->new("$glob does not match $page");
2154 sub match_internal ($$;@) {
2155 return match_glob($_[0], $_[1], @_, internal => 1)
2158 sub match_link ($$;@) {
2163 $link=derel($link, $params{location});
2164 my $from=exists $params{location} ? $params{location} : '';
2166 my $links = $IkiWiki::links{$page};
2167 return IkiWiki::FailReason->new("$page has no links", "" => 1)
2168 unless $links && @{$links};
2169 my $bestlink = IkiWiki::bestlink($from, $link);
2170 foreach my $p (@{$links}) {
2171 if (length $bestlink) {
2172 return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2173 if $bestlink eq IkiWiki::bestlink($page, $p);
2176 return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2177 if match_glob($p, $link, %params);
2178 my ($p_rel)=$p=~/^\/?(.*)/;
2180 return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2181 if match_glob($p_rel, $link, %params);
2184 return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
2187 sub match_backlink ($$;@) {
2188 my $ret=match_link($_[1], $_[0], @_);
2189 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2193 sub match_created_before ($$;@) {
2198 $testpage=derel($testpage, $params{location});
2200 if (exists $IkiWiki::pagectime{$testpage}) {
2201 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2202 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2205 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2209 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2213 sub match_created_after ($$;@) {
2218 $testpage=derel($testpage, $params{location});
2220 if (exists $IkiWiki::pagectime{$testpage}) {
2221 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2222 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2225 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2229 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2233 sub match_creation_day ($$;@) {
2234 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2235 return IkiWiki::SuccessReason->new('creation_day matched');
2238 return IkiWiki::FailReason->new('creation_day did not match');
2242 sub match_creation_month ($$;@) {
2243 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2244 return IkiWiki::SuccessReason->new('creation_month matched');
2247 return IkiWiki::FailReason->new('creation_month did not match');
2251 sub match_creation_year ($$;@) {
2252 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2253 return IkiWiki::SuccessReason->new('creation_year matched');
2256 return IkiWiki::FailReason->new('creation_year did not match');
2260 sub match_user ($$;@) {
2265 if (! exists $params{user}) {
2266 return IkiWiki::ErrorReason->new("no user specified");
2269 if (defined $params{user} && lc $params{user} eq lc $user) {
2270 return IkiWiki::SuccessReason->new("user is $user");
2272 elsif (! defined $params{user}) {
2273 return IkiWiki::FailReason->new("not logged in");
2276 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2280 sub match_admin ($$;@) {
2285 if (! exists $params{user}) {
2286 return IkiWiki::ErrorReason->new("no user specified");
2289 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2290 return IkiWiki::SuccessReason->new("user is an admin");
2292 elsif (! defined $params{user}) {
2293 return IkiWiki::FailReason->new("not logged in");
2296 return IkiWiki::FailReason->new("user is not an admin");
2300 sub match_ip ($$;@) {
2305 if (! exists $params{ip}) {
2306 return IkiWiki::ErrorReason->new("no IP specified");
2309 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2310 return IkiWiki::SuccessReason->new("IP is $ip");
2313 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");