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 add_depends pagespec_match
21 pagespec_match_list bestlink htmllink readfile writefile
22 pagetype srcfile pagename displaytime will_render gettext urlto
23 targetpage add_underlay pagetitle titlepage linkpage
24 newpagefile inject add_link
25 %config %links %pagestate %wikistate %renderedfiles
26 %pagesources %destsources);
27 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
34 memoize("pagespec_translate");
35 memoize("template_file");
41 description => "name of the wiki",
48 example => 'me@example.com',
49 description => "contact email for wiki",
56 description => "users who are wiki admins",
63 description => "users who are banned from the wiki",
70 example => "$ENV{HOME}/wiki",
71 description => "where the source of the wiki is located",
78 example => "/var/www/wiki",
79 description => "where to build the wiki",
86 example => "http://example.com/wiki",
87 description => "base url to the wiki",
94 example => "http://example.com/wiki/ikiwiki.cgi",
95 description => "url to the ikiwiki.cgi",
102 example => "/var/www/wiki/ikiwiki.cgi",
103 description => "filename of cgi wrapper to generate",
110 description => "mode for cgi_wrapper (can safely be made suid)",
117 description => "rcs backend to use",
118 safe => 0, # don't allow overriding
123 default => [qw{mdwn link inline meta htmlscrubber passwordauth
124 openid signinedit lockedit conditional
125 recentchanges parentlinks editpage}],
126 description => "plugins to enable by default",
133 description => "plugins to add to the default configuration",
140 description => "plugins to disable",
146 default => "$installdir/share/ikiwiki/templates",
147 description => "location of template files",
155 description => "additional directories containing 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 => "only send cookies over SSL connections?",
248 description => "extension to use for new pages",
249 safe => 0, # not sanitized
255 description => "extension to use for html files",
256 safe => 0, # not sanitized
262 description => "strftime format string to display date",
270 example => "en_US.UTF-8",
271 description => "UTF-8 locale to use",
280 description => "put user pages below specified page",
287 description => "how many backlinks to show before hiding excess (0 to show all)",
294 description => "attempt to hardlink source files? (optimisation for large files)",
296 safe => 0, # paranoia
302 description => "force ikiwiki to use a particular umask",
304 safe => 0, # paranoia
309 example => "ikiwiki",
310 description => "group for wrappers to run in",
312 safe => 0, # paranoia
318 example => "$ENV{HOME}/.ikiwiki/",
319 description => "extra library and plugin directory",
321 safe => 0, # directory
327 description => "environment variables",
328 safe => 0, # paranoia
335 description => "regexp of source files to ignore",
340 wiki_file_prune_regexps => {
342 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
343 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
344 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
345 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
346 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
347 description => "regexps of source files to ignore",
353 description => "specifies the characters that are allowed in source filenames",
354 default => "-[:alnum:]+/.:_",
358 wiki_file_regexp => {
360 description => "regexp of legal source files",
364 web_commit_regexp => {
366 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
367 description => "regexp to parse web commits from logs",
374 description => "run as a cgi",
378 cgi_disable_uploads => {
381 description => "whether CGI should accept file uploads",
388 description => "run as a post-commit hook",
395 description => "running in rebuild mode",
402 description => "running in setup mode",
409 description => "running in refresh mode",
416 description => "running in receive test mode",
423 description => "running in getctime mode",
430 description => "running in w3mmode",
437 description => "path to the .ikiwiki directory holding ikiwiki state",
444 description => "path to setup file",
448 allow_symlinks_before_srcdir => {
451 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
457 sub defaultconfig () {
460 foreach my $key (keys %s) {
461 push @ret, $key, $s{$key}->{default};
468 # locale stuff; avoid LC_ALL since it overrides everything
469 if (defined $ENV{LC_ALL}) {
470 $ENV{LANG} = $ENV{LC_ALL};
473 if (defined $config{locale}) {
474 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
475 $ENV{LANG}=$config{locale};
480 if (! defined $config{wiki_file_regexp}) {
481 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
484 if (ref $config{ENV} eq 'HASH') {
485 foreach my $val (keys %{$config{ENV}}) {
486 $ENV{$val}=$config{ENV}{$val};
490 if ($config{w3mmode}) {
491 eval q{use Cwd q{abs_path}};
493 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
494 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
495 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
496 unless $config{cgiurl} =~ m!file:///!;
497 $config{url}="file://".$config{destdir};
500 if ($config{cgi} && ! length $config{url}) {
501 error(gettext("Must specify url to wiki with --url when using --cgi"));
504 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
505 unless exists $config{wikistatedir} && defined $config{wikistatedir};
507 if (defined $config{umask}) {
508 umask(possibly_foolish_untaint($config{umask}));
511 run_hooks(checkconfig => sub { shift->() });
519 foreach my $dir (@INC, $config{libdir}) {
520 next unless defined $dir && length $dir;
521 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
522 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
526 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
527 next unless defined $dir && length $dir;
528 foreach my $file (glob("$dir/plugins/*")) {
529 $ret{basename($file)}=1 if -x $file;
537 if (defined $config{libdir} && length $config{libdir}) {
538 unshift @INC, possibly_foolish_untaint($config{libdir});
541 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
546 if (exists $hooks{rcs}) {
547 error(gettext("cannot use multiple rcs plugins"));
549 loadplugin($config{rcs});
551 if (! exists $hooks{rcs}) {
555 run_hooks(getopt => sub { shift->() });
556 if (grep /^-/, @ARGV) {
557 print STDERR "Unknown option (or missing parameter): $_\n"
558 foreach grep /^-/, @ARGV;
568 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
570 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
571 "$installdir/lib/ikiwiki") {
572 if (defined $dir && -x "$dir/plugins/$plugin") {
573 eval { require IkiWiki::Plugin::external };
576 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
578 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
579 $loaded_plugins{$plugin}=1;
584 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
587 error("Failed to load plugin $mod: $@");
589 $loaded_plugins{$plugin}=1;
596 log_message('err' => $message) if $config{syslog};
597 if (defined $cleaner) {
604 return unless $config{verbose};
605 return log_message(debug => @_);
609 sub log_message ($$) {
612 if ($config{syslog}) {
615 Sys::Syslog::setlogsock('unix');
616 Sys::Syslog::openlog('ikiwiki', '', 'user');
620 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
623 elsif (! $config{cgi}) {
627 return print STDERR "@_\n";
631 sub possibly_foolish_untaint ($) {
633 my ($untainted)=$tainted=~/(.*)/s;
653 return exists $pagesources{$page} &&
654 $pagesources{$page} =~ /\._([^.]+)$/;
660 if ($file =~ /\.([^.]+)$/) {
661 return $1 if exists $hooks{htmlize}{$1};
663 my $base=basename($file);
664 if (exists $hooks{htmlize}{$base} &&
665 $hooks{htmlize}{$base}{noextension}) {
676 if (exists $pagename_cache{$file}) {
677 return $pagename_cache{$file};
680 my $type=pagetype($file);
682 $page=~s/\Q.$type\E*$//
683 if defined $type && !$hooks{htmlize}{$type}{keepextension}
684 && !$hooks{htmlize}{$type}{noextension};
685 if ($config{indexpages} && $page=~/(.*)\/index$/) {
689 $pagename_cache{$file} = $page;
693 sub newpagefile ($$) {
697 if (! $config{indexpages} || $page eq 'index') {
698 return $page.".".$type;
701 return $page."/index.".$type;
705 sub targetpage ($$;$) {
710 if (defined $filename) {
711 return $page."/".$filename.".".$ext;
713 elsif (! $config{usedirs} || $page eq 'index') {
714 return $page.".".$ext;
717 return $page."/index.".$ext;
724 return targetpage($page, $config{htmlext});
731 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
732 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
733 return "$dir/$file", stat(_) if -e "$dir/$file";
735 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
740 return (srcfile_stat(@_))[0];
743 sub add_underlay ($) {
747 $dir="$config{underlaydirbase}/$dir";
750 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
751 unshift @{$config{underlaydirs}}, $dir;
757 sub readfile ($;$$) {
763 error("cannot read a symlink ($file)");
767 open (my $in, "<", $file) || error("failed to read $file: $!");
768 binmode($in) if ($binary);
769 return \*$in if $wantfd;
771 # check for invalid utf-8, and toss it back to avoid crashes
772 if (! utf8::valid($ret)) {
773 $ret=encode_utf8($ret);
775 close $in || error("failed to read $file: $!");
779 sub prep_writefile ($$) {
784 while (length $test) {
785 if (-l "$destdir/$test") {
786 error("cannot write to a symlink ($test)");
788 $test=dirname($test);
791 my $dir=dirname("$destdir/$file");
794 foreach my $s (split(m!/+!, $dir)) {
797 mkdir($d) || error("failed to create directory $d: $!");
805 sub writefile ($$$;$$) {
806 my $file=shift; # can include subdirs
807 my $destdir=shift; # directory to put file in
812 prep_writefile($file, $destdir);
814 my $newfile="$destdir/$file.ikiwiki-new";
816 error("cannot write to a symlink ($newfile)");
819 my $cleanup = sub { unlink($newfile) };
820 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
821 binmode($out) if ($binary);
823 $writer->(\*$out, $cleanup);
826 print $out $content or error("failed writing to $newfile: $!", $cleanup);
828 close $out || error("failed saving $newfile: $!", $cleanup);
829 rename($newfile, "$destdir/$file") ||
830 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
836 sub will_render ($$;$) {
841 # Important security check.
842 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
843 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
844 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
847 if (! $clear || $cleared{$page}) {
848 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
851 foreach my $old (@{$renderedfiles{$page}}) {
852 delete $destsources{$old};
854 $renderedfiles{$page}=[$dest];
857 $destsources{$dest}=$page;
867 if ($link=~s/^\/+//) {
875 $l.="/" if length $l;
878 if (exists $links{$l}) {
881 elsif (exists $pagecase{lc $l}) {
882 return $pagecase{lc $l};
884 } while $cwd=~s{/?[^/]+$}{};
886 if (length $config{userdir}) {
887 my $l = "$config{userdir}/".lc($link);
888 if (exists $links{$l}) {
891 elsif (exists $pagecase{lc $l}) {
892 return $pagecase{lc $l};
896 #print STDERR "warning: page $page, broken link: $link\n";
900 sub isinlinableimage ($) {
903 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
906 sub pagetitle ($;$) {
911 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
914 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
922 # support use w/o %config set
923 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
924 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
930 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
931 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
938 return $config{cgiurl}."?".
939 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
945 return "$config{url}/" if ! defined $page;
947 $page=htmlpage($page);
949 $page=~s/[^\/]+\//..\//g;
954 # Work around very innefficient behavior in File::Spec if abs2rel
955 # is passed two relative paths. It's much faster if paths are
956 # absolute! (Debian bug #376658; fixed in debian unstable now)
961 my $ret=File::Spec->abs2rel($path, $base);
962 $ret=~s/^// if defined $ret;
966 sub displaytime ($;$) {
967 # Plugins can override this function to mark up the time to
969 return '<span class="date">'.formattime(@_).'</span>';
972 sub formattime ($;$) {
973 # Plugins can override this function to format the time.
976 if (! defined $format) {
977 $format=$config{timeformat};
980 # strftime doesn't know about encodings, so make sure
981 # its output is properly treated as utf8
982 return decode_utf8(POSIX::strftime($format, localtime($time)));
985 sub beautify_urlpath ($) {
988 # Ensure url is not an empty link, and if necessary,
989 # add ./ to avoid colon confusion.
990 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
994 if ($config{usedirs}) {
995 $url =~ s!/index.$config{htmlext}$!/!;
1007 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1010 if (! $destsources{$to}) {
1015 return $config{url}.beautify_urlpath("/".$to);
1018 my $link = abs2rel($to, dirname(htmlpage($from)));
1020 return beautify_urlpath($link);
1023 sub htmllink ($$$;@) {
1024 my $lpage=shift; # the page doing the linking
1025 my $page=shift; # the page that will contain the link (different for inline)
1032 if (! $opts{forcesubpage}) {
1033 $bestlink=bestlink($lpage, $link);
1036 $bestlink="$lpage/".lc($link);
1040 if (defined $opts{linktext}) {
1041 $linktext=$opts{linktext};
1044 $linktext=pagetitle(basename($link));
1047 return "<span class=\"selflink\">$linktext</span>"
1048 if length $bestlink && $page eq $bestlink &&
1049 ! defined $opts{anchor};
1051 if (! $destsources{$bestlink}) {
1052 $bestlink=htmlpage($bestlink);
1054 if (! $destsources{$bestlink}) {
1055 return $linktext unless length $config{cgiurl};
1056 return "<span class=\"createlink\"><a href=\"".
1062 "\" rel=\"nofollow\">?</a>$linktext</span>"
1066 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1067 $bestlink=beautify_urlpath($bestlink);
1069 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1070 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1073 if (defined $opts{anchor}) {
1074 $bestlink.="#".$opts{anchor};
1078 if (defined $opts{rel}) {
1079 push @attrs, ' rel="'.$opts{rel}.'"';
1081 if (defined $opts{class}) {
1082 push @attrs, ' class="'.$opts{class}.'"';
1085 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1088 sub openiduser ($) {
1091 if ($user =~ m!^https?://! &&
1092 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1095 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1096 # this works in at least 2.x
1097 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1100 # this only works in 1.x
1101 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1102 $display=$oid->display;
1105 # Convert "user.somehost.com" to "user [somehost.com]"
1106 # (also "user.somehost.co.uk")
1107 if ($display !~ /\[/) {
1108 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1110 # Convert "http://somehost.com/user" to "user [somehost.com]".
1111 # (also "https://somehost.com/user/")
1112 if ($display !~ /\[/) {
1113 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1115 $display=~s!^https?://!!; # make sure this is removed
1116 eval q{use CGI 'escapeHTML'};
1118 return escapeHTML($display);
1126 my $oiduser=eval { openiduser($user) };
1127 if (defined $oiduser) {
1128 return "<a href=\"$user\">$oiduser</a>";
1131 eval q{use CGI 'escapeHTML'};
1134 return htmllink("", "", escapeHTML(
1135 length $config{userdir} ? $config{userdir}."/".$user : $user
1136 ), noimageinline => 1);
1140 sub htmlize ($$$$) {
1146 my $oneline = $content !~ /\n/;
1148 if (exists $hooks{htmlize}{$type}) {
1149 $content=$hooks{htmlize}{$type}{call}->(
1151 content => $content,
1155 error("htmlization of $type not supported");
1158 run_hooks(sanitize => sub {
1161 destpage => $destpage,
1162 content => $content,
1167 # hack to get rid of enclosing junk added by markdown
1168 # and other htmlizers
1169 $content=~s/^<p>//i;
1170 $content=~s/<\/p>$//i;
1182 run_hooks(linkify => sub {
1185 destpage => $destpage,
1186 content => $content,
1194 our $preprocess_preview=0;
1195 sub preprocess ($$$;$$) {
1196 my $page=shift; # the page the data comes from
1197 my $destpage=shift; # the page the data will appear in (different for inline)
1202 # Using local because it needs to be set within any nested calls
1204 local $preprocess_preview=$preview if defined $preview;
1211 $params="" if ! defined $params;
1213 if (length $escape) {
1214 return "[[$prefix$command $params]]";
1216 elsif (exists $hooks{preprocess}{$command}) {
1217 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1218 # Note: preserve order of params, some plugins may
1219 # consider it significant.
1221 while ($params =~ m{
1222 (?:([-\w]+)=)? # 1: named parameter key?
1224 """(.*?)""" # 2: triple-quoted value
1226 "([^"]+)" # 3: single-quoted value
1228 (\S+) # 4: unquoted value
1230 (?:\s+|$) # delimiter to next param
1240 elsif (defined $3) {
1243 elsif (defined $4) {
1248 push @params, $key, $val;
1251 push @params, $val, '';
1254 if ($preprocessing{$page}++ > 3) {
1255 # Avoid loops of preprocessed pages preprocessing
1256 # other pages that preprocess them, etc.
1257 return "[[!$command <span class=\"error\">".
1258 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1259 $page, $preprocessing{$page}).
1265 $hooks{preprocess}{$command}{call}->(
1268 destpage => $destpage,
1269 preview => $preprocess_preview,
1275 $ret="[[!$command <span class=\"error\">".
1276 gettext("Error").": $error"."</span>]]";
1280 # use void context during scan pass
1282 $hooks{preprocess}{$command}{call}->(
1285 destpage => $destpage,
1286 preview => $preprocess_preview,
1291 $preprocessing{$page}--;
1295 return "[[$prefix$command $params]]";
1300 if ($config{prefix_directives}) {
1303 \[\[(!) # directive open; 2: prefix
1304 ([-\w]+) # 3: command
1305 ( # 4: the parameters..
1306 \s+ # Must have space if parameters present
1308 (?:[-\w]+=)? # named parameter key?
1310 """.*?""" # triple-quoted value
1312 "[^"]+" # single-quoted value
1314 [^"\s\]]+ # unquoted value
1316 \s* # whitespace or end
1319 *)? # 0 or more parameters
1320 \]\] # directive closed
1326 \[\[(!?) # directive open; 2: optional prefix
1327 ([-\w]+) # 3: command
1329 ( # 4: the parameters..
1331 (?:[-\w]+=)? # named parameter key?
1333 """.*?""" # triple-quoted value
1335 "[^"]+" # single-quoted value
1337 [^"\s\]]+ # unquoted value
1339 \s* # whitespace or end
1342 *) # 0 or more parameters
1343 \]\] # directive closed
1347 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1356 run_hooks(filter => sub {
1357 $content=shift->(page => $page, destpage => $destpage,
1358 content => $content);
1365 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1368 sub check_canedit ($$$;$) {
1375 run_hooks(canedit => sub {
1376 return if defined $canedit;
1377 my $ret=shift->($page, $q, $session);
1382 elsif (ref $ret eq 'CODE') {
1383 $ret->() unless $nonfatal;
1386 elsif (defined $ret) {
1387 error($ret) unless $nonfatal;
1392 return defined $canedit ? $canedit : 1;
1395 sub check_content (@) {
1398 return 1 if ! exists $hooks{checkcontent}; # optimisation
1400 if (exists $pagesources{$params{page}}) {
1402 my %old=map { $_ => 1 }
1403 split("\n", readfile(srcfile($pagesources{$params{page}})));
1404 foreach my $line (split("\n", $params{content})) {
1405 push @diff, $line if ! exists $old{$_};
1407 $params{diff}=join("\n", @diff);
1411 run_hooks(checkcontent => sub {
1412 return if defined $ok;
1413 my $ret=shift->(%params);
1418 elsif (ref $ret eq 'CODE') {
1419 $ret->() unless $params{nonfatal};
1422 elsif (defined $ret) {
1423 error($ret) unless $params{nonfatal};
1429 return defined $ok ? $ok : 1;
1435 # Take an exclusive lock on the wiki to prevent multiple concurrent
1436 # run issues. The lock will be dropped on program exit.
1437 if (! -d $config{wikistatedir}) {
1438 mkdir($config{wikistatedir});
1440 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1441 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1442 if (! flock($wikilock, 2)) { # LOCK_EX
1443 error("failed to get lock");
1449 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1450 return close($wikilock) if $wikilock;
1456 sub commit_hook_enabled () {
1457 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1458 error("cannot write to $config{wikistatedir}/commitlock: $!");
1459 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1460 close($commitlock) || error("failed closing commitlock: $!");
1463 close($commitlock) || error("failed closing commitlock: $!");
1467 sub disable_commit_hook () {
1468 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1469 error("cannot write to $config{wikistatedir}/commitlock: $!");
1470 if (! flock($commitlock, 2)) { # LOCK_EX
1471 error("failed to get commit lock");
1476 sub enable_commit_hook () {
1477 return close($commitlock) if $commitlock;
1482 %oldrenderedfiles=%pagectime=();
1483 if (! $config{rebuild}) {
1484 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1485 %destsources=%renderedfiles=%pagecase=%pagestate=
1489 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1490 if (-e "$config{wikistatedir}/index") {
1491 system("ikiwiki-transition", "indexdb", $config{srcdir});
1492 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1499 my $index=Storable::fd_retrieve($in);
1500 if (! defined $index) {
1505 if (exists $index->{version} && ! ref $index->{version}) {
1506 $pages=$index->{page};
1507 %wikistate=%{$index->{state}};
1514 foreach my $src (keys %$pages) {
1515 my $d=$pages->{$src};
1516 my $page=pagename($src);
1517 $pagectime{$page}=$d->{ctime};
1518 if (! $config{rebuild}) {
1519 $pagesources{$page}=$src;
1520 $pagemtime{$page}=$d->{mtime};
1521 $renderedfiles{$page}=$d->{dest};
1522 if (exists $d->{links} && ref $d->{links}) {
1523 $links{$page}=$d->{links};
1524 $oldlinks{$page}=[@{$d->{links}}];
1526 if (exists $d->{depends_simple}) {
1527 $depends_simple{$page}={
1528 map { $_ => 1 } @{$d->{depends_simple}}
1531 if (exists $d->{dependslist}) {
1533 map { $_ => 1 } @{$d->{dependslist}}
1536 elsif (exists $d->{depends}) {
1537 $depends{$page}={$d->{depends} => 1};
1539 if (exists $d->{state}) {
1540 $pagestate{$page}=$d->{state};
1543 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1545 foreach my $page (keys %pagesources) {
1546 $pagecase{lc $page}=$page;
1548 foreach my $page (keys %renderedfiles) {
1549 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1555 run_hooks(savestate => sub { shift->() });
1558 foreach my $type (keys %hooks) {
1559 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1561 my @hookids=keys %hookids;
1563 if (! -d $config{wikistatedir}) {
1564 mkdir($config{wikistatedir});
1566 my $newfile="$config{wikistatedir}/indexdb.new";
1567 my $cleanup = sub { unlink($newfile) };
1568 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1571 foreach my $page (keys %pagemtime) {
1572 next unless $pagemtime{$page};
1573 my $src=$pagesources{$page};
1575 $index{page}{$src}={
1576 ctime => $pagectime{$page},
1577 mtime => $pagemtime{$page},
1578 dest => $renderedfiles{$page},
1579 links => $links{$page},
1582 if (exists $depends{$page}) {
1583 $index{page}{$src}{dependslist} = [ keys %{$depends{$page}} ];
1586 if (exists $depends_simple{$page}) {
1587 $index{page}{$src}{depends_simple} = [ keys %{$depends_simple{$page}} ];
1590 if (exists $pagestate{$page}) {
1591 foreach my $id (@hookids) {
1592 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1593 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1600 foreach my $id (@hookids) {
1601 foreach my $key (keys %{$wikistate{$id}}) {
1602 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1606 $index{version}="3";
1607 my $ret=Storable::nstore_fd(\%index, $out);
1608 return if ! defined $ret || ! $ret;
1609 close $out || error("failed saving to $newfile: $!", $cleanup);
1610 rename($newfile, "$config{wikistatedir}/indexdb") ||
1611 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1616 sub template_file ($) {
1619 foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1620 "$installdir/share/ikiwiki/templates") {
1621 return "$dir/$template" if -e "$dir/$template";
1626 sub template_params (@) {
1627 my $filename=template_file(shift);
1629 if (! defined $filename) {
1630 return if wantarray;
1636 my $text_ref = shift;
1637 ${$text_ref} = decode_utf8(${$text_ref});
1639 filename => $filename,
1640 loop_context_vars => 1,
1641 die_on_bad_params => 0,
1644 return wantarray ? @ret : {@ret};
1647 sub template ($;@) {
1648 require HTML::Template;
1649 return HTML::Template->new(template_params(@_));
1652 sub misctemplate ($$;@) {
1656 my $template=template("misc.tmpl");
1659 indexlink => indexlink(),
1660 wikiname => $config{wikiname},
1661 pagebody => $pagebody,
1662 baseurl => baseurl(),
1665 run_hooks(pagetemplate => sub {
1666 shift->(page => "", destpage => "", template => $template);
1668 return $template->output;
1674 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1675 error 'hook requires type, call, and id parameters';
1678 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1680 $hooks{$param{type}}{$param{id}}=\%param;
1684 sub run_hooks ($$) {
1685 # Calls the given sub for each hook of the given type,
1686 # passing it the hook function to call.
1690 if (exists $hooks{$type}) {
1691 my (@first, @middle, @last);
1692 foreach my $id (keys %{$hooks{$type}}) {
1693 if ($hooks{$type}{$id}{first}) {
1696 elsif ($hooks{$type}{$id}{last}) {
1703 foreach my $id (@first, @middle, @last) {
1704 $sub->($hooks{$type}{$id}{call});
1712 $hooks{rcs}{rcs_update}{call}->(@_);
1715 sub rcs_prepedit ($) {
1716 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1719 sub rcs_commit ($$$;$$) {
1720 $hooks{rcs}{rcs_commit}{call}->(@_);
1723 sub rcs_commit_staged ($$$) {
1724 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1728 $hooks{rcs}{rcs_add}{call}->(@_);
1731 sub rcs_remove ($) {
1732 $hooks{rcs}{rcs_remove}{call}->(@_);
1735 sub rcs_rename ($$) {
1736 $hooks{rcs}{rcs_rename}{call}->(@_);
1739 sub rcs_recentchanges ($) {
1740 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1744 $hooks{rcs}{rcs_diff}{call}->(@_);
1747 sub rcs_getctime ($) {
1748 $hooks{rcs}{rcs_getctime}{call}->(@_);
1751 sub rcs_receive () {
1752 $hooks{rcs}{rcs_receive}{call}->();
1755 sub add_depends ($$) {
1759 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1760 $pagespec !~ /[\s*?()!]/) {
1761 # a simple dependency, which can be matched by string eq
1762 $depends_simple{$page}{lc $pagespec} = 1;
1766 return unless pagespec_valid($pagespec);
1768 $depends{$page}{$pagespec} = 1;
1772 sub file_pruned ($;$) {
1776 $file=File::Spec->canonpath($file);
1777 my $base=File::Spec->canonpath(shift);
1778 return if $file eq $base;
1779 $file =~ s#^\Q$base\E/+##;
1782 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1783 return $file =~ m/$regexp/;
1786 sub define_gettext () {
1787 # If translation is needed, redefine the gettext function to do it.
1788 # Otherwise, it becomes a quick no-op.
1789 no warnings 'redefine';
1790 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1791 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1792 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1794 my $gettext_obj=eval q{
1795 use Locale::gettext q{textdomain};
1796 Locale::gettext->domain('ikiwiki')
1800 $gettext_obj->get(shift);
1808 *gettext=sub { return shift };
1820 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1824 # Injects a new function into the symbol table to replace an
1825 # exported function.
1828 # This is deep ugly perl foo, beware.
1831 if (! defined $params{parent}) {
1832 $params{parent}='::';
1833 $params{old}=\&{$params{name}};
1834 $params{name}=~s/.*:://;
1836 my $parent=$params{parent};
1837 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1838 $ns = $params{parent} . $ns;
1839 inject(%params, parent => $ns) unless $ns eq '::main::';
1840 *{$ns . $params{name}} = $params{call}
1841 if exists ${$ns}{$params{name}} &&
1842 \&{${$ns}{$params{name}}} == $params{old};
1852 push @{$links{$page}}, $link
1853 unless grep { $_ eq $link } @{$links{$page}};
1856 sub pagespec_translate ($) {
1859 # Convert spec to perl code.
1863 \s* # ignore whitespace
1864 ( # 1: match a single word
1871 \w+\([^\)]*\) # command(params)
1873 [^\s()]+ # any other text
1875 \s* # ignore whitespace
1878 if (lc $word eq 'and') {
1881 elsif (lc $word eq 'or') {
1884 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1887 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1888 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1890 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1893 push @data, qq{unknown function in pagespec "$word"};
1894 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1899 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1903 if (! length $code) {
1904 $code="IkiWiki::FailReason->new('empty pagespec')";
1908 return eval 'sub { my $page=shift; '.$code.' }';
1911 sub pagespec_match ($$;@) {
1916 # Backwards compatability with old calling convention.
1918 unshift @params, 'location';
1921 my $sub=pagespec_translate($spec);
1922 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1923 if $@ || ! defined $sub;
1924 return $sub->($page, @params);
1927 sub pagespec_match_list ($$;@) {
1932 my $sub=pagespec_translate($spec);
1933 error "syntax error in pagespec \"$spec\""
1934 if $@ || ! defined $sub;
1938 foreach my $page (@$pages) {
1939 $r=$sub->($page, @params);
1940 push @ret, $page if $r;
1943 if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1944 error(sprintf(gettext("cannot match pages: %s"), $r));
1951 sub pagespec_valid ($) {
1954 my $sub=pagespec_translate($spec);
1959 my $re=quotemeta(shift);
1965 package IkiWiki::FailReason;
1968 '""' => sub { ${$_[0]} },
1970 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1977 return bless \$value, $class;
1980 package IkiWiki::ErrorReason;
1982 our @ISA = 'IkiWiki::FailReason';
1984 package IkiWiki::SuccessReason;
1987 '""' => sub { ${$_[0]} },
1989 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1996 return bless \$value, $class;
1999 package IkiWiki::PageSpec;
2005 if ($path =~ m!^\./!) {
2006 $from=~s#/?[^/]+$## if defined $from;
2008 $path="$from/$path" if length $from;
2014 sub match_glob ($$;@) {
2019 $glob=derel($glob, $params{location});
2021 my $regexp=IkiWiki::glob2re($glob);
2022 if ($page=~/^$regexp$/i) {
2023 if (! IkiWiki::isinternal($page) || $params{internal}) {
2024 return IkiWiki::SuccessReason->new("$glob matches $page");
2027 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2031 return IkiWiki::FailReason->new("$glob does not match $page");
2035 sub match_internal ($$;@) {
2036 return match_glob($_[0], $_[1], @_, internal => 1)
2039 sub match_link ($$;@) {
2044 $link=derel($link, $params{location});
2045 my $from=exists $params{location} ? $params{location} : '';
2047 my $links = $IkiWiki::links{$page};
2048 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
2049 my $bestlink = IkiWiki::bestlink($from, $link);
2050 foreach my $p (@{$links}) {
2051 if (length $bestlink) {
2052 return IkiWiki::SuccessReason->new("$page links to $link")
2053 if $bestlink eq IkiWiki::bestlink($page, $p);
2056 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2057 if match_glob($p, $link, %params);
2058 my ($p_rel)=$p=~/^\/?(.*)/;
2060 return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link")
2061 if match_glob($p_rel, $link, %params);
2064 return IkiWiki::FailReason->new("$page does not link to $link");
2067 sub match_backlink ($$;@) {
2068 return match_link($_[1], $_[0], @_);
2071 sub match_created_before ($$;@) {
2076 $testpage=derel($testpage, $params{location});
2078 if (exists $IkiWiki::pagectime{$testpage}) {
2079 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2080 return IkiWiki::SuccessReason->new("$page created before $testpage");
2083 return IkiWiki::FailReason->new("$page not created before $testpage");
2087 return IkiWiki::ErrorReason->new("$testpage does not exist");
2091 sub match_created_after ($$;@) {
2096 $testpage=derel($testpage, $params{location});
2098 if (exists $IkiWiki::pagectime{$testpage}) {
2099 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2100 return IkiWiki::SuccessReason->new("$page created after $testpage");
2103 return IkiWiki::FailReason->new("$page not created after $testpage");
2107 return IkiWiki::ErrorReason->new("$testpage does not exist");
2111 sub match_creation_day ($$;@) {
2112 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2113 return IkiWiki::SuccessReason->new('creation_day matched');
2116 return IkiWiki::FailReason->new('creation_day did not match');
2120 sub match_creation_month ($$;@) {
2121 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2122 return IkiWiki::SuccessReason->new('creation_month matched');
2125 return IkiWiki::FailReason->new('creation_month did not match');
2129 sub match_creation_year ($$;@) {
2130 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2131 return IkiWiki::SuccessReason->new('creation_year matched');
2134 return IkiWiki::FailReason->new('creation_year did not match');
2138 sub match_user ($$;@) {
2143 if (! exists $params{user}) {
2144 return IkiWiki::ErrorReason->new("no user specified");
2147 if (defined $params{user} && lc $params{user} eq lc $user) {
2148 return IkiWiki::SuccessReason->new("user is $user");
2150 elsif (! defined $params{user}) {
2151 return IkiWiki::FailReason->new("not logged in");
2154 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2158 sub match_admin ($$;@) {
2163 if (! exists $params{user}) {
2164 return IkiWiki::ErrorReason->new("no user specified");
2167 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2168 return IkiWiki::SuccessReason->new("user is an admin");
2170 elsif (! defined $params{user}) {
2171 return IkiWiki::FailReason->new("not logged in");
2174 return IkiWiki::FailReason->new("user is not an admin");
2178 sub match_ip ($$;@) {
2183 if (! exists $params{ip}) {
2184 return IkiWiki::ErrorReason->new("no IP specified");
2187 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2188 return IkiWiki::SuccessReason->new("IP is $ip");
2191 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");