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 %hooks %forcerebuild
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("file_pruned");
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",
154 default => "$installdir/share/ikiwiki/basewiki",
155 description => "base wiki source location",
162 default => "$installdir/share/ikiwiki",
163 description => "parent directory containing additional underlays",
170 description => "wrappers to generate",
177 description => "additional underlays to use",
184 description => "display verbose messages?",
191 description => "log to syslog?",
198 description => "create output files named page/index.html?",
199 safe => 0, # changing requires manual transition
202 prefix_directives => {
205 description => "use '!'-prefixed preprocessor directives?",
206 safe => 0, # changing requires manual transition
212 description => "use page/index.mdwn source files",
219 description => "enable Discussion pages?",
225 default => gettext("Discussion"),
226 description => "name of Discussion pages",
233 description => "only send cookies over SSL connections?",
241 description => "extension to use for new pages",
242 safe => 0, # not sanitized
248 description => "extension to use for html files",
249 safe => 0, # not sanitized
255 description => "strftime format string to display date",
263 example => "en_US.UTF-8",
264 description => "UTF-8 locale to use",
273 description => "put user pages below specified page",
280 description => "how many backlinks to show before hiding excess (0 to show all)",
287 description => "attempt to hardlink source files? (optimisation for large files)",
289 safe => 0, # paranoia
295 description => "force ikiwiki to use a particular umask",
297 safe => 0, # paranoia
302 example => "ikiwiki",
303 description => "group for wrappers to run in",
305 safe => 0, # paranoia
311 example => "$ENV{HOME}/.ikiwiki/",
312 description => "extra library and plugin directory",
314 safe => 0, # directory
320 description => "environment variables",
321 safe => 0, # paranoia
328 description => "regexp of source files to ignore",
333 wiki_file_prune_regexps => {
335 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
336 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
337 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
338 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
340 description => "regexps of source files to ignore",
346 description => "specifies the characters that are allowed in source filenames",
347 default => "-[:alnum:]+/.:_",
351 wiki_file_regexp => {
353 description => "regexp of legal source files",
357 web_commit_regexp => {
359 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
360 description => "regexp to parse web commits from logs",
367 description => "run as a cgi",
371 cgi_disable_uploads => {
374 description => "whether CGI should accept file uploads",
381 description => "run as a post-commit hook",
388 description => "running in rebuild mode",
395 description => "running in setup mode",
402 description => "running in refresh mode",
409 description => "running in receive test mode",
416 description => "running in getctime mode",
423 description => "running in w3mmode",
430 description => "path to the .ikiwiki directory holding ikiwiki state",
437 description => "path to setup file",
441 allow_symlinks_before_srcdir => {
444 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
450 sub defaultconfig () {
453 foreach my $key (keys %s) {
454 push @ret, $key, $s{$key}->{default};
461 # locale stuff; avoid LC_ALL since it overrides everything
462 if (defined $ENV{LC_ALL}) {
463 $ENV{LANG} = $ENV{LC_ALL};
466 if (defined $config{locale}) {
467 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
468 $ENV{LANG}=$config{locale};
473 if (! defined $config{wiki_file_regexp}) {
474 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
477 if (ref $config{ENV} eq 'HASH') {
478 foreach my $val (keys %{$config{ENV}}) {
479 $ENV{$val}=$config{ENV}{$val};
483 if ($config{w3mmode}) {
484 eval q{use Cwd q{abs_path}};
486 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
487 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
488 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
489 unless $config{cgiurl} =~ m!file:///!;
490 $config{url}="file://".$config{destdir};
493 if ($config{cgi} && ! length $config{url}) {
494 error(gettext("Must specify url to wiki with --url when using --cgi"));
497 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
498 unless exists $config{wikistatedir} && defined $config{wikistatedir};
500 if (defined $config{umask}) {
501 umask(possibly_foolish_untaint($config{umask}));
504 run_hooks(checkconfig => sub { shift->() });
512 foreach my $dir (@INC, $config{libdir}) {
513 next unless defined $dir && length $dir;
514 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
515 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
519 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
520 next unless defined $dir && length $dir;
521 foreach my $file (glob("$dir/plugins/*")) {
522 $ret{basename($file)}=1 if -x $file;
530 if (defined $config{libdir} && length $config{libdir}) {
531 unshift @INC, possibly_foolish_untaint($config{libdir});
534 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
539 if (exists $IkiWiki::hooks{rcs}) {
540 error(gettext("cannot use multiple rcs plugins"));
542 loadplugin($config{rcs});
544 if (! exists $IkiWiki::hooks{rcs}) {
548 run_hooks(getopt => sub { shift->() });
549 if (grep /^-/, @ARGV) {
550 print STDERR "Unknown option (or missing parameter): $_\n"
551 foreach grep /^-/, @ARGV;
561 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
563 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
564 "$installdir/lib/ikiwiki") {
565 if (defined $dir && -x "$dir/plugins/$plugin") {
566 eval { require IkiWiki::Plugin::external };
569 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
571 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
572 $loaded_plugins{$plugin}=1;
577 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
580 error("Failed to load plugin $mod: $@");
582 $loaded_plugins{$plugin}=1;
589 log_message('err' => $message) if $config{syslog};
590 if (defined $cleaner) {
597 return unless $config{verbose};
598 return log_message(debug => @_);
602 sub log_message ($$) {
605 if ($config{syslog}) {
608 Sys::Syslog::setlogsock('unix');
609 Sys::Syslog::openlog('ikiwiki', '', 'user');
613 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
616 elsif (! $config{cgi}) {
620 return print STDERR "@_\n";
624 sub possibly_foolish_untaint ($) {
626 my ($untainted)=$tainted=~/(.*)/s;
646 return exists $pagesources{$page} &&
647 $pagesources{$page} =~ /\._([^.]+)$/;
653 if ($file =~ /\.([^.]+)$/) {
654 return $1 if exists $hooks{htmlize}{$1};
656 my $base=basename($file);
657 if (exists $hooks{htmlize}{$base} &&
658 $hooks{htmlize}{$base}{noextension}) {
667 my $type=pagetype($file);
669 $page=~s/\Q.$type\E*$//
670 if defined $type && !$hooks{htmlize}{$type}{keepextension}
671 && !$hooks{htmlize}{$type}{noextension};
672 if ($config{indexpages} && $page=~/(.*)\/index$/) {
678 sub newpagefile ($$) {
682 if (! $config{indexpages} || $page eq 'index') {
683 return $page.".".$type;
686 return $page."/index.".$type;
690 sub targetpage ($$;$) {
695 if (defined $filename) {
696 return $page."/".$filename.".".$ext;
698 elsif (! $config{usedirs} || $page eq 'index') {
699 return $page.".".$ext;
702 return $page."/index.".$ext;
709 return targetpage($page, $config{htmlext});
716 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
717 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
718 return "$dir/$file", stat(_) if -e "$dir/$file";
720 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
725 return (srcfile_stat(@_))[0];
728 sub add_underlay ($) {
732 $dir="$config{underlaydirbase}/$dir";
735 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
736 unshift @{$config{underlaydirs}}, $dir;
742 sub readfile ($;$$) {
748 error("cannot read a symlink ($file)");
752 open (my $in, "<", $file) || error("failed to read $file: $!");
753 binmode($in) if ($binary);
754 return \*$in if $wantfd;
756 # check for invalid utf-8, and toss it back to avoid crashes
757 if (! utf8::valid($ret)) {
758 $ret=encode_utf8($ret);
760 close $in || error("failed to read $file: $!");
764 sub prep_writefile ($$) {
769 while (length $test) {
770 if (-l "$destdir/$test") {
771 error("cannot write to a symlink ($test)");
773 $test=dirname($test);
776 my $dir=dirname("$destdir/$file");
779 foreach my $s (split(m!/+!, $dir)) {
782 mkdir($d) || error("failed to create directory $d: $!");
790 sub writefile ($$$;$$) {
791 my $file=shift; # can include subdirs
792 my $destdir=shift; # directory to put file in
797 prep_writefile($file, $destdir);
799 my $newfile="$destdir/$file.ikiwiki-new";
801 error("cannot write to a symlink ($newfile)");
804 my $cleanup = sub { unlink($newfile) };
805 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
806 binmode($out) if ($binary);
808 $writer->(\*$out, $cleanup);
811 print $out $content or error("failed writing to $newfile: $!", $cleanup);
813 close $out || error("failed saving $newfile: $!", $cleanup);
814 rename($newfile, "$destdir/$file") ||
815 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
821 sub will_render ($$;$) {
826 # Important security check.
827 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
828 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
829 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
832 if (! $clear || $cleared{$page}) {
833 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
836 foreach my $old (@{$renderedfiles{$page}}) {
837 delete $destsources{$old};
839 $renderedfiles{$page}=[$dest];
842 $destsources{$dest}=$page;
852 if ($link=~s/^\/+//) {
860 $l.="/" if length $l;
863 if (exists $links{$l}) {
866 elsif (exists $pagecase{lc $l}) {
867 return $pagecase{lc $l};
869 } while $cwd=~s{/?[^/]+$}{};
871 if (length $config{userdir}) {
872 my $l = "$config{userdir}/".lc($link);
873 if (exists $links{$l}) {
876 elsif (exists $pagecase{lc $l}) {
877 return $pagecase{lc $l};
881 #print STDERR "warning: page $page, broken link: $link\n";
885 sub isinlinableimage ($) {
888 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
891 sub pagetitle ($;$) {
896 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
899 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
907 # support use w/o %config set
908 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
909 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
915 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
916 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
923 return $config{cgiurl}."?".
924 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
930 return "$config{url}/" if ! defined $page;
932 $page=htmlpage($page);
934 $page=~s/[^\/]+\//..\//g;
939 # Work around very innefficient behavior in File::Spec if abs2rel
940 # is passed two relative paths. It's much faster if paths are
941 # absolute! (Debian bug #376658; fixed in debian unstable now)
946 my $ret=File::Spec->abs2rel($path, $base);
947 $ret=~s/^// if defined $ret;
951 sub displaytime ($;$) {
952 # Plugins can override this function to mark up the time to
954 return '<span class="date">'.formattime(@_).'</span>';
957 sub formattime ($;$) {
958 # Plugins can override this function to format the time.
961 if (! defined $format) {
962 $format=$config{timeformat};
965 # strftime doesn't know about encodings, so make sure
966 # its output is properly treated as utf8
967 return decode_utf8(POSIX::strftime($format, localtime($time)));
970 sub beautify_urlpath ($) {
973 # Ensure url is not an empty link, and if necessary,
974 # add ./ to avoid colon confusion.
975 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
979 if ($config{usedirs}) {
980 $url =~ s!/index.$config{htmlext}$!/!;
992 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
995 if (! $destsources{$to}) {
1000 return $config{url}.beautify_urlpath("/".$to);
1003 my $link = abs2rel($to, dirname(htmlpage($from)));
1005 return beautify_urlpath($link);
1008 sub htmllink ($$$;@) {
1009 my $lpage=shift; # the page doing the linking
1010 my $page=shift; # the page that will contain the link (different for inline)
1017 if (! $opts{forcesubpage}) {
1018 $bestlink=bestlink($lpage, $link);
1021 $bestlink="$lpage/".lc($link);
1025 if (defined $opts{linktext}) {
1026 $linktext=$opts{linktext};
1029 $linktext=pagetitle(basename($link));
1032 return "<span class=\"selflink\">$linktext</span>"
1033 if length $bestlink && $page eq $bestlink &&
1034 ! defined $opts{anchor};
1036 if (! $destsources{$bestlink}) {
1037 $bestlink=htmlpage($bestlink);
1039 if (! $destsources{$bestlink}) {
1040 return $linktext unless length $config{cgiurl};
1041 return "<span class=\"createlink\"><a href=\"".
1047 "\" rel=\"nofollow\">?</a>$linktext</span>"
1051 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1052 $bestlink=beautify_urlpath($bestlink);
1054 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1055 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1058 if (defined $opts{anchor}) {
1059 $bestlink.="#".$opts{anchor};
1063 if (defined $opts{rel}) {
1064 push @attrs, ' rel="'.$opts{rel}.'"';
1066 if (defined $opts{class}) {
1067 push @attrs, ' class="'.$opts{class}.'"';
1070 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1073 sub openiduser ($) {
1076 if ($user =~ m!^https?://! &&
1077 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1080 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1081 # this works in at least 2.x
1082 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1085 # this only works in 1.x
1086 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1087 $display=$oid->display;
1090 # Convert "user.somehost.com" to "user [somehost.com]"
1091 # (also "user.somehost.co.uk")
1092 if ($display !~ /\[/) {
1093 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1095 # Convert "http://somehost.com/user" to "user [somehost.com]".
1096 # (also "https://somehost.com/user/")
1097 if ($display !~ /\[/) {
1098 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1100 $display=~s!^https?://!!; # make sure this is removed
1101 eval q{use CGI 'escapeHTML'};
1103 return escapeHTML($display);
1111 my $oiduser=eval { openiduser($user) };
1112 if (defined $oiduser) {
1113 return "<a href=\"$user\">$oiduser</a>";
1116 eval q{use CGI 'escapeHTML'};
1119 return htmllink("", "", escapeHTML(
1120 length $config{userdir} ? $config{userdir}."/".$user : $user
1121 ), noimageinline => 1);
1125 sub htmlize ($$$$) {
1131 my $oneline = $content !~ /\n/;
1133 if (exists $hooks{htmlize}{$type}) {
1134 $content=$hooks{htmlize}{$type}{call}->(
1136 content => $content,
1140 error("htmlization of $type not supported");
1143 run_hooks(sanitize => sub {
1146 destpage => $destpage,
1147 content => $content,
1152 # hack to get rid of enclosing junk added by markdown
1153 # and other htmlizers
1154 $content=~s/^<p>//i;
1155 $content=~s/<\/p>$//i;
1167 run_hooks(linkify => sub {
1170 destpage => $destpage,
1171 content => $content,
1179 our $preprocess_preview=0;
1180 sub preprocess ($$$;$$) {
1181 my $page=shift; # the page the data comes from
1182 my $destpage=shift; # the page the data will appear in (different for inline)
1187 # Using local because it needs to be set within any nested calls
1189 local $preprocess_preview=$preview if defined $preview;
1196 $params="" if ! defined $params;
1198 if (length $escape) {
1199 return "[[$prefix$command $params]]";
1201 elsif (exists $hooks{preprocess}{$command}) {
1202 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1203 # Note: preserve order of params, some plugins may
1204 # consider it significant.
1206 while ($params =~ m{
1207 (?:([-\w]+)=)? # 1: named parameter key?
1209 """(.*?)""" # 2: triple-quoted value
1211 "([^"]+)" # 3: single-quoted value
1213 (\S+) # 4: unquoted value
1215 (?:\s+|$) # delimiter to next param
1225 elsif (defined $3) {
1228 elsif (defined $4) {
1233 push @params, $key, $val;
1236 push @params, $val, '';
1239 if ($preprocessing{$page}++ > 3) {
1240 # Avoid loops of preprocessed pages preprocessing
1241 # other pages that preprocess them, etc.
1242 return "[[!$command <span class=\"error\">".
1243 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1244 $page, $preprocessing{$page}).
1250 $hooks{preprocess}{$command}{call}->(
1253 destpage => $destpage,
1254 preview => $preprocess_preview,
1260 $ret="[[!$command <span class=\"error\">".
1261 gettext("Error").": $error"."</span>]]";
1265 # use void context during scan pass
1267 $hooks{preprocess}{$command}{call}->(
1270 destpage => $destpage,
1271 preview => $preprocess_preview,
1276 $preprocessing{$page}--;
1280 return "[[$prefix$command $params]]";
1285 if ($config{prefix_directives}) {
1288 \[\[(!) # directive open; 2: prefix
1289 ([-\w]+) # 3: command
1290 ( # 4: the parameters..
1291 \s+ # Must have space if parameters present
1293 (?:[-\w]+=)? # named parameter key?
1295 """.*?""" # triple-quoted value
1297 "[^"]+" # single-quoted value
1299 [^"\s\]]+ # unquoted value
1301 \s* # whitespace or end
1304 *)? # 0 or more parameters
1305 \]\] # directive closed
1311 \[\[(!?) # directive open; 2: optional prefix
1312 ([-\w]+) # 3: command
1314 ( # 4: the parameters..
1316 (?:[-\w]+=)? # named parameter key?
1318 """.*?""" # triple-quoted value
1320 "[^"]+" # single-quoted value
1322 [^"\s\]]+ # unquoted value
1324 \s* # whitespace or end
1327 *) # 0 or more parameters
1328 \]\] # directive closed
1332 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1341 run_hooks(filter => sub {
1342 $content=shift->(page => $page, destpage => $destpage,
1343 content => $content);
1350 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1353 sub check_canedit ($$$;$) {
1360 run_hooks(canedit => sub {
1361 return if defined $canedit;
1362 my $ret=shift->($page, $q, $session);
1367 elsif (ref $ret eq 'CODE') {
1368 $ret->() unless $nonfatal;
1371 elsif (defined $ret) {
1372 error($ret) unless $nonfatal;
1377 return defined $canedit ? $canedit : 1;
1380 sub check_content (@) {
1383 return 1 if ! exists $hooks{checkcontent}; # optimisation
1385 if (exists $pagesources{$params{page}}) {
1387 my %old=map { $_ => 1 }
1388 split("\n", readfile(srcfile($pagesources{$params{page}})));
1389 foreach my $line (split("\n", $params{content})) {
1390 push @diff, $line if ! exists $old{$_};
1392 $params{diff}=join("\n", @diff);
1396 run_hooks(checkcontent => sub {
1397 return if defined $ok;
1398 my $ret=shift->(%params);
1403 elsif (ref $ret eq 'CODE') {
1404 $ret->() unless $params{nonfatal};
1407 elsif (defined $ret) {
1408 error($ret) unless $params{nonfatal};
1414 return defined $ok ? $ok : 1;
1420 # Take an exclusive lock on the wiki to prevent multiple concurrent
1421 # run issues. The lock will be dropped on program exit.
1422 if (! -d $config{wikistatedir}) {
1423 mkdir($config{wikistatedir});
1425 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1426 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1427 if (! flock($wikilock, 2)) { # LOCK_EX
1428 error("failed to get lock");
1434 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1435 return close($wikilock) if $wikilock;
1441 sub commit_hook_enabled () {
1442 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1443 error("cannot write to $config{wikistatedir}/commitlock: $!");
1444 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1445 close($commitlock) || error("failed closing commitlock: $!");
1448 close($commitlock) || error("failed closing commitlock: $!");
1452 sub disable_commit_hook () {
1453 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1454 error("cannot write to $config{wikistatedir}/commitlock: $!");
1455 if (! flock($commitlock, 2)) { # LOCK_EX
1456 error("failed to get commit lock");
1461 sub enable_commit_hook () {
1462 return close($commitlock) if $commitlock;
1467 %oldrenderedfiles=%pagectime=();
1468 if (! $config{rebuild}) {
1469 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1470 %destsources=%renderedfiles=%pagecase=%pagestate=();
1473 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1474 if (-e "$config{wikistatedir}/index") {
1475 system("ikiwiki-transition", "indexdb", $config{srcdir});
1476 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1483 my $index=Storable::fd_retrieve($in);
1484 if (! defined $index) {
1489 if (exists $index->{version} && ! ref $index->{version}) {
1490 $pages=$index->{page};
1491 %wikistate=%{$index->{state}};
1498 foreach my $src (keys %$pages) {
1499 my $d=$pages->{$src};
1500 my $page=pagename($src);
1501 $pagectime{$page}=$d->{ctime};
1502 if (! $config{rebuild}) {
1503 $pagesources{$page}=$src;
1504 $pagemtime{$page}=$d->{mtime};
1505 $renderedfiles{$page}=$d->{dest};
1506 if (exists $d->{links} && ref $d->{links}) {
1507 $links{$page}=$d->{links};
1508 $oldlinks{$page}=[@{$d->{links}}];
1510 if (exists $d->{dependslist}) {
1512 map { $_ => 1 } @{$d->{dependslist}}
1515 elsif (exists $d->{depends}) {
1516 $depends{$page}={$d->{depends} => 1};
1518 if (exists $d->{state}) {
1519 $pagestate{$page}=$d->{state};
1522 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1524 foreach my $page (keys %pagesources) {
1525 $pagecase{lc $page}=$page;
1527 foreach my $page (keys %renderedfiles) {
1528 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1534 run_hooks(savestate => sub { shift->() });
1537 foreach my $type (keys %hooks) {
1538 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1540 my @hookids=keys %hookids;
1542 if (! -d $config{wikistatedir}) {
1543 mkdir($config{wikistatedir});
1545 my $newfile="$config{wikistatedir}/indexdb.new";
1546 my $cleanup = sub { unlink($newfile) };
1547 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1550 foreach my $page (keys %pagemtime) {
1551 next unless $pagemtime{$page};
1552 my $src=$pagesources{$page};
1554 $index{page}{$src}={
1555 ctime => $pagectime{$page},
1556 mtime => $pagemtime{$page},
1557 dest => $renderedfiles{$page},
1558 links => $links{$page},
1561 if (exists $depends{$page}) {
1562 $index{page}{$src}{dependslist} = [ keys %{$depends{$page}} ];
1565 if (exists $pagestate{$page}) {
1566 foreach my $id (@hookids) {
1567 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1568 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1575 foreach my $id (@hookids) {
1576 foreach my $key (keys %{$wikistate{$id}}) {
1577 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1581 $index{version}="3";
1582 my $ret=Storable::nstore_fd(\%index, $out);
1583 return if ! defined $ret || ! $ret;
1584 close $out || error("failed saving to $newfile: $!", $cleanup);
1585 rename($newfile, "$config{wikistatedir}/indexdb") ||
1586 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1591 sub template_file ($) {
1594 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1595 return "$dir/$template" if -e "$dir/$template";
1600 sub template_params (@) {
1601 my $filename=template_file(shift);
1603 if (! defined $filename) {
1604 return if wantarray;
1610 my $text_ref = shift;
1611 ${$text_ref} = decode_utf8(${$text_ref});
1613 filename => $filename,
1614 loop_context_vars => 1,
1615 die_on_bad_params => 0,
1618 return wantarray ? @ret : {@ret};
1621 sub template ($;@) {
1622 require HTML::Template;
1623 return HTML::Template->new(template_params(@_));
1626 sub misctemplate ($$;@) {
1630 my $template=template("misc.tmpl");
1633 indexlink => indexlink(),
1634 wikiname => $config{wikiname},
1635 pagebody => $pagebody,
1636 baseurl => baseurl(),
1639 run_hooks(pagetemplate => sub {
1640 shift->(page => "", destpage => "", template => $template);
1642 return $template->output;
1648 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1649 error 'hook requires type, call, and id parameters';
1652 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1654 $hooks{$param{type}}{$param{id}}=\%param;
1658 sub run_hooks ($$) {
1659 # Calls the given sub for each hook of the given type,
1660 # passing it the hook function to call.
1664 if (exists $hooks{$type}) {
1665 my (@first, @middle, @last);
1666 foreach my $id (keys %{$hooks{$type}}) {
1667 if ($hooks{$type}{$id}{first}) {
1670 elsif ($hooks{$type}{$id}{last}) {
1677 foreach my $id (@first, @middle, @last) {
1678 $sub->($hooks{$type}{$id}{call});
1686 $hooks{rcs}{rcs_update}{call}->(@_);
1689 sub rcs_prepedit ($) {
1690 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1693 sub rcs_commit ($$$;$$) {
1694 $hooks{rcs}{rcs_commit}{call}->(@_);
1697 sub rcs_commit_staged ($$$) {
1698 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1702 $hooks{rcs}{rcs_add}{call}->(@_);
1705 sub rcs_remove ($) {
1706 $hooks{rcs}{rcs_remove}{call}->(@_);
1709 sub rcs_rename ($$) {
1710 $hooks{rcs}{rcs_rename}{call}->(@_);
1713 sub rcs_recentchanges ($) {
1714 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1718 $hooks{rcs}{rcs_diff}{call}->(@_);
1721 sub rcs_getctime ($) {
1722 $hooks{rcs}{rcs_getctime}{call}->(@_);
1725 sub rcs_receive () {
1726 $hooks{rcs}{rcs_receive}{call}->();
1729 sub add_depends ($$) {
1733 if (ref $pagespec eq 'ARRAY') {
1734 foreach my $ps (@$pagespec) {
1735 if (pagespec_valid($ps)) {
1736 $depends{$page}{$ps} = 1;
1742 return unless pagespec_valid($pagespec);
1744 $depends{$page}{$pagespec} = 1;
1748 sub file_pruned ($$) {
1750 my $file=File::Spec->canonpath(shift);
1751 my $base=File::Spec->canonpath(shift);
1752 $file =~ s#^\Q$base\E/+##;
1754 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1755 return $file =~ m/$regexp/ && $file ne $base;
1758 sub define_gettext () {
1759 # If translation is needed, redefine the gettext function to do it.
1760 # Otherwise, it becomes a quick no-op.
1761 no warnings 'redefine';
1762 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1763 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1764 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1766 my $gettext_obj=eval q{
1767 use Locale::gettext q{textdomain};
1768 Locale::gettext->domain('ikiwiki')
1772 $gettext_obj->get(shift);
1780 *gettext=sub { return shift };
1792 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1796 # Injects a new function into the symbol table to replace an
1797 # exported function.
1800 # This is deep ugly perl foo, beware.
1803 if (! defined $params{parent}) {
1804 $params{parent}='::';
1805 $params{old}=\&{$params{name}};
1806 $params{name}=~s/.*:://;
1808 my $parent=$params{parent};
1809 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1810 $ns = $params{parent} . $ns;
1811 inject(%params, parent => $ns) unless $ns eq '::main::';
1812 *{$ns . $params{name}} = $params{call}
1813 if exists ${$ns}{$params{name}} &&
1814 \&{${$ns}{$params{name}}} == $params{old};
1824 push @{$links{$page}}, $link
1825 unless grep { $_ eq $link } @{$links{$page}};
1828 sub pagespec_merge ($$) {
1832 return $a if $a eq $b;
1833 return "($a) or ($b)";
1836 sub pagespec_translate ($) {
1839 # Convert spec to perl code.
1843 \s* # ignore whitespace
1844 ( # 1: match a single word
1851 \w+\([^\)]*\) # command(params)
1853 [^\s()]+ # any other text
1855 \s* # ignore whitespace
1858 if (lc $word eq 'and') {
1861 elsif (lc $word eq 'or') {
1864 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1867 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1868 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1870 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1873 push @data, qq{unknown function in pagespec "$word"};
1874 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1879 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1883 if (! length $code) {
1884 $code="IkiWiki::FailReason->new('empty pagespec')";
1888 return eval 'sub { my $page=shift; '.$code.' }';
1891 sub pagespec_match ($$;@) {
1896 # Backwards compatability with old calling convention.
1898 unshift @params, 'location';
1901 my $sub=pagespec_translate($spec);
1902 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1903 if $@ || ! defined $sub;
1904 return $sub->($page, @params);
1907 sub pagespec_match_list ($$;@) {
1912 my $sub=pagespec_translate($spec);
1913 error "syntax error in pagespec \"$spec\""
1914 if $@ || ! defined $sub;
1918 foreach my $page (@$pages) {
1919 $r=$sub->($page, @params);
1920 push @ret, $page if $r;
1923 if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1924 error(sprintf(gettext("cannot match pages: %s"), $r));
1931 sub pagespec_valid ($) {
1934 my $sub=pagespec_translate($spec);
1939 my $re=quotemeta(shift);
1945 package IkiWiki::FailReason;
1948 '""' => sub { ${$_[0]} },
1950 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1957 return bless \$value, $class;
1960 package IkiWiki::ErrorReason;
1962 our @ISA = 'IkiWiki::FailReason';
1964 package IkiWiki::SuccessReason;
1967 '""' => sub { ${$_[0]} },
1969 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1976 return bless \$value, $class;
1979 package IkiWiki::PageSpec;
1985 if ($path =~ m!^\./!) {
1986 $from=~s#/?[^/]+$## if defined $from;
1988 $path="$from/$path" if length $from;
1994 sub match_glob ($$;@) {
1999 $glob=derel($glob, $params{location});
2001 my $regexp=IkiWiki::glob2re($glob);
2002 if ($page=~/^$regexp$/i) {
2003 if (! IkiWiki::isinternal($page) || $params{internal}) {
2004 return IkiWiki::SuccessReason->new("$glob matches $page");
2007 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2011 return IkiWiki::FailReason->new("$glob does not match $page");
2015 sub match_internal ($$;@) {
2016 return match_glob($_[0], $_[1], @_, internal => 1)
2019 sub match_link ($$;@) {
2024 $link=derel($link, $params{location});
2025 my $from=exists $params{location} ? $params{location} : '';
2027 my $links = $IkiWiki::links{$page};
2028 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
2029 my $bestlink = IkiWiki::bestlink($from, $link);
2030 foreach my $p (@{$links}) {
2031 if (length $bestlink) {
2032 return IkiWiki::SuccessReason->new("$page links to $link")
2033 if $bestlink eq IkiWiki::bestlink($page, $p);
2036 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2037 if match_glob($p, $link, %params);
2040 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2041 if match_glob($p, $link, %params);
2044 return IkiWiki::FailReason->new("$page does not link to $link");
2047 sub match_backlink ($$;@) {
2048 return match_link($_[1], $_[0], @_);
2051 sub match_created_before ($$;@) {
2056 $testpage=derel($testpage, $params{location});
2058 if (exists $IkiWiki::pagectime{$testpage}) {
2059 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2060 return IkiWiki::SuccessReason->new("$page created before $testpage");
2063 return IkiWiki::FailReason->new("$page not created before $testpage");
2067 return IkiWiki::ErrorReason->new("$testpage does not exist");
2071 sub match_created_after ($$;@) {
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 after $testpage");
2083 return IkiWiki::FailReason->new("$page not created after $testpage");
2087 return IkiWiki::ErrorReason->new("$testpage does not exist");
2091 sub match_creation_day ($$;@) {
2092 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2093 return IkiWiki::SuccessReason->new('creation_day matched');
2096 return IkiWiki::FailReason->new('creation_day did not match');
2100 sub match_creation_month ($$;@) {
2101 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2102 return IkiWiki::SuccessReason->new('creation_month matched');
2105 return IkiWiki::FailReason->new('creation_month did not match');
2109 sub match_creation_year ($$;@) {
2110 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2111 return IkiWiki::SuccessReason->new('creation_year matched');
2114 return IkiWiki::FailReason->new('creation_year did not match');
2118 sub match_user ($$;@) {
2123 if (! exists $params{user}) {
2124 return IkiWiki::ErrorReason->new("no user specified");
2127 if (defined $params{user} && lc $params{user} eq lc $user) {
2128 return IkiWiki::SuccessReason->new("user is $user");
2130 elsif (! defined $params{user}) {
2131 return IkiWiki::FailReason->new("not logged in");
2134 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2138 sub match_admin ($$;@) {
2143 if (! exists $params{user}) {
2144 return IkiWiki::ErrorReason->new("no user specified");
2147 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2148 return IkiWiki::SuccessReason->new("user is an admin");
2150 elsif (! defined $params{user}) {
2151 return IkiWiki::FailReason->new("not logged in");
2154 return IkiWiki::FailReason->new("user is not an admin");
2158 sub match_ip ($$;@) {
2163 if (! exists $params{ip}) {
2164 return IkiWiki::ErrorReason->new("no IP specified");
2167 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2168 return IkiWiki::SuccessReason->new("IP is $ip");
2171 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");