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
17 $gettext_obj %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21 bestlink htmllink readfile writefile pagetype srcfile pagename
22 displaytime will_render gettext urlto targetpage
23 add_underlay pagetitle titlepage linkpage newpagefile
25 %config %links %pagestate %wikistate %renderedfiles
26 %pagesources %destsources);
27 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
34 memoize("pagespec_translate");
35 memoize("file_pruned");
37 sub getsetup () { #{{{
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 => "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",
163 description => "wrappers to generate",
170 description => "additional underlays to use",
177 description => "display verbose messages when building?",
184 description => "log to syslog?",
191 description => "create output files named page/index.html?",
192 safe => 0, # changing requires manual transition
195 prefix_directives => {
198 description => "use '!'-prefixed preprocessor directives?",
199 safe => 0, # changing requires manual transition
205 description => "use page/index.mdwn source files",
212 description => "enable Discussion pages?",
219 description => "only send cookies over SSL connections?",
227 description => "extension to use for new pages",
228 safe => 0, # not sanitized
234 description => "extension to use for html files",
235 safe => 0, # not sanitized
241 description => "strftime format string to display date",
249 example => "en_US.UTF-8",
250 description => "UTF-8 locale to use",
259 description => "put user pages below specified page",
266 description => "how many backlinks to show before hiding excess (0 to show all)",
273 description => "attempt to hardlink source files? (optimisation for large files)",
275 safe => 0, # paranoia
281 description => "force ikiwiki to use a particular umask",
283 safe => 0, # paranoia
288 example => "ikiwiki",
289 description => "group for wrappers to run in",
291 safe => 0, # paranoia
297 example => "$ENV{HOME}/.ikiwiki/",
298 description => "extra library and plugin directory",
300 safe => 0, # directory
306 description => "environment variables",
307 safe => 0, # paranoia
314 description => "regexp of source files to ignore",
319 wiki_file_prune_regexps => {
321 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
322 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
323 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
326 description => "regexps of source files to ignore",
332 description => "specifies the characters that are allowed in source filenames",
333 default => "-[:alnum:]+/.:_",
337 wiki_file_regexp => {
339 description => "regexp of legal source files",
343 web_commit_regexp => {
345 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
346 description => "regexp to parse web commits from logs",
353 description => "run as a cgi",
357 cgi_disable_uploads => {
360 description => "whether CGI should accept file uploads",
367 description => "run as a post-commit hook",
374 description => "running in rebuild mode",
381 description => "running in setup mode",
388 description => "running in refresh mode",
395 description => "running in receive test mode",
402 description => "running in getctime mode",
409 description => "running in w3mmode",
416 description => "path to the .ikiwiki directory holding ikiwiki state",
423 description => "path to setup file",
427 allow_symlinks_before_srcdir => {
430 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
436 sub defaultconfig () { #{{{
439 foreach my $key (keys %s) {
440 push @ret, $key, $s{$key}->{default};
446 sub checkconfig () { #{{{
447 # locale stuff; avoid LC_ALL since it overrides everything
448 if (defined $ENV{LC_ALL}) {
449 $ENV{LANG} = $ENV{LC_ALL};
452 if (defined $config{locale}) {
453 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
454 $ENV{LANG}=$config{locale};
459 if (! defined $config{wiki_file_regexp}) {
460 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
463 if (ref $config{ENV} eq 'HASH') {
464 foreach my $val (keys %{$config{ENV}}) {
465 $ENV{$val}=$config{ENV}{$val};
469 if ($config{w3mmode}) {
470 eval q{use Cwd q{abs_path}};
472 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
473 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
474 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
475 unless $config{cgiurl} =~ m!file:///!;
476 $config{url}="file://".$config{destdir};
479 if ($config{cgi} && ! length $config{url}) {
480 error(gettext("Must specify url to wiki with --url when using --cgi"));
483 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
484 unless exists $config{wikistatedir} && defined $config{wikistatedir};
486 if (defined $config{umask}) {
487 umask(possibly_foolish_untaint($config{umask}));
490 run_hooks(checkconfig => sub { shift->() });
495 sub listplugins () { #{{{
498 foreach my $dir (@INC, $config{libdir}) {
499 next unless defined $dir && length $dir;
500 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
501 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
505 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
506 next unless defined $dir && length $dir;
507 foreach my $file (glob("$dir/plugins/*")) {
508 $ret{basename($file)}=1 if -x $file;
515 sub loadplugins () { #{{{
516 if (defined $config{libdir} && length $config{libdir}) {
517 unshift @INC, possibly_foolish_untaint($config{libdir});
520 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
525 if (exists $IkiWiki::hooks{rcs}) {
526 error(gettext("cannot use multiple rcs plugins"));
528 loadplugin($config{rcs});
530 if (! exists $IkiWiki::hooks{rcs}) {
534 run_hooks(getopt => sub { shift->() });
535 if (grep /^-/, @ARGV) {
536 print STDERR "Unknown option: $_\n"
537 foreach grep /^-/, @ARGV;
544 sub loadplugin ($) { #{{{
547 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
549 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
550 "$installdir/lib/ikiwiki") {
551 if (defined $dir && -x "$dir/plugins/$plugin") {
552 eval { require IkiWiki::Plugin::external };
555 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
557 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
558 $loaded_plugins{$plugin}=1;
563 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
566 error("Failed to load plugin $mod: $@");
568 $loaded_plugins{$plugin}=1;
572 sub error ($;$) { #{{{
575 log_message('err' => $message) if $config{syslog};
576 if (defined $cleaner) {
583 return unless $config{verbose};
584 return log_message(debug => @_);
588 sub log_message ($$) { #{{{
591 if ($config{syslog}) {
594 Sys::Syslog::setlogsock('unix');
595 Sys::Syslog::openlog('ikiwiki', '', 'user');
599 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
602 elsif (! $config{cgi}) {
606 return print STDERR "@_\n";
610 sub possibly_foolish_untaint ($) { #{{{
612 my ($untainted)=$tainted=~/(.*)/s;
616 sub basename ($) { #{{{
623 sub dirname ($) { #{{{
630 sub pagetype ($) { #{{{
633 if ($page =~ /\.([^.]+)$/) {
634 return $1 if exists $hooks{htmlize}{$1};
639 sub isinternal ($) { #{{{
641 return exists $pagesources{$page} &&
642 $pagesources{$page} =~ /\._([^.]+)$/;
645 sub pagename ($) { #{{{
648 my $type=pagetype($file);
650 $page=~s/\Q.$type\E*$// if defined $type && !$hooks{htmlize}{$type}{keepextension};
651 if ($config{indexpages} && $page=~/(.*)\/index$/) {
657 sub newpagefile ($$) { #{{{
661 if (! $config{indexpages} || $page eq 'index') {
662 return $page.".".$type;
665 return $page."/index.".$type;
669 sub targetpage ($$) { #{{{
673 if (! $config{usedirs} || $page eq 'index') {
674 return $page.".".$ext;
677 return $page."/index.".$ext;
681 sub htmlpage ($) { #{{{
684 return targetpage($page, $config{htmlext});
687 sub srcfile_stat { #{{{
691 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
692 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
693 return "$dir/$file", stat(_) if -e "$dir/$file";
695 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
699 sub srcfile ($;$) { #{{{
700 return (srcfile_stat(@_))[0];
703 sub add_underlay ($) { #{{{
707 $dir="$config{underlaydir}/../$dir";
710 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
711 unshift @{$config{underlaydirs}}, $dir;
717 sub readfile ($;$$) { #{{{
723 error("cannot read a symlink ($file)");
727 open (my $in, "<", $file) || error("failed to read $file: $!");
728 binmode($in) if ($binary);
729 return \*$in if $wantfd;
731 # check for invalid utf-8, and toss it back to avoid crashes
732 if (! utf8::valid($ret)) {
733 $ret=encode_utf8($ret);
735 close $in || error("failed to read $file: $!");
739 sub prep_writefile ($$) { #{{{
744 while (length $test) {
745 if (-l "$destdir/$test") {
746 error("cannot write to a symlink ($test)");
748 $test=dirname($test);
751 my $dir=dirname("$destdir/$file");
754 foreach my $s (split(m!/+!, $dir)) {
757 mkdir($d) || error("failed to create directory $d: $!");
765 sub writefile ($$$;$$) { #{{{
766 my $file=shift; # can include subdirs
767 my $destdir=shift; # directory to put file in
772 prep_writefile($file, $destdir);
774 my $newfile="$destdir/$file.ikiwiki-new";
776 error("cannot write to a symlink ($newfile)");
779 my $cleanup = sub { unlink($newfile) };
780 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
781 binmode($out) if ($binary);
783 $writer->(\*$out, $cleanup);
786 print $out $content or error("failed writing to $newfile: $!", $cleanup);
788 close $out || error("failed saving $newfile: $!", $cleanup);
789 rename($newfile, "$destdir/$file") ||
790 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
796 sub will_render ($$;$) { #{{{
801 # Important security check.
802 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
803 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
804 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
807 if (! $clear || $cleared{$page}) {
808 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
811 foreach my $old (@{$renderedfiles{$page}}) {
812 delete $destsources{$old};
814 $renderedfiles{$page}=[$dest];
817 $destsources{$dest}=$page;
822 sub bestlink ($$) { #{{{
827 if ($link=~s/^\/+//) {
835 $l.="/" if length $l;
838 if (exists $links{$l}) {
841 elsif (exists $pagecase{lc $l}) {
842 return $pagecase{lc $l};
844 } while $cwd=~s{/?[^/]+$}{};
846 if (length $config{userdir}) {
847 my $l = "$config{userdir}/".lc($link);
848 if (exists $links{$l}) {
851 elsif (exists $pagecase{lc $l}) {
852 return $pagecase{lc $l};
856 #print STDERR "warning: page $page, broken link: $link\n";
860 sub isinlinableimage ($) { #{{{
863 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
866 sub pagetitle ($;$) { #{{{
871 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
874 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
880 sub titlepage ($) { #{{{
882 # support use w/o %config set
883 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
884 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
888 sub linkpage ($) { #{{{
890 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
891 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
895 sub cgiurl (@) { #{{{
898 return $config{cgiurl}."?".
899 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
902 sub baseurl (;$) { #{{{
905 return "$config{url}/" if ! defined $page;
907 $page=htmlpage($page);
909 $page=~s/[^\/]+\//..\//g;
913 sub abs2rel ($$) { #{{{
914 # Work around very innefficient behavior in File::Spec if abs2rel
915 # is passed two relative paths. It's much faster if paths are
916 # absolute! (Debian bug #376658; fixed in debian unstable now)
921 my $ret=File::Spec->abs2rel($path, $base);
922 $ret=~s/^// if defined $ret;
926 sub displaytime ($;$) { #{{{
927 # Plugins can override this function to mark up the time to
929 return '<span class="date">'.formattime(@_).'</span>';
932 sub formattime ($;$) { #{{{
933 # Plugins can override this function to format the time.
936 if (! defined $format) {
937 $format=$config{timeformat};
940 # strftime doesn't know about encodings, so make sure
941 # its output is properly treated as utf8
942 return decode_utf8(POSIX::strftime($format, localtime($time)));
945 sub beautify_urlpath ($) { #{{{
948 if ($config{usedirs}) {
949 $url =~ s!/index.$config{htmlext}$!/!;
952 # Ensure url is not an empty link, and if necessary,
953 # add ./ to avoid colon confusion.
954 if ($url !~ /^\// && $url !~ /^\.\.\//) {
961 sub urlto ($$;$) { #{{{
967 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
970 if (! $destsources{$to}) {
975 return $config{url}.beautify_urlpath("/".$to);
978 my $link = abs2rel($to, dirname(htmlpage($from)));
980 return beautify_urlpath($link);
983 sub htmllink ($$$;@) { #{{{
984 my $lpage=shift; # the page doing the linking
985 my $page=shift; # the page that will contain the link (different for inline)
992 if (! $opts{forcesubpage}) {
993 $bestlink=bestlink($lpage, $link);
996 $bestlink="$lpage/".lc($link);
1000 if (defined $opts{linktext}) {
1001 $linktext=$opts{linktext};
1004 $linktext=pagetitle(basename($link));
1007 return "<span class=\"selflink\">$linktext</span>"
1008 if length $bestlink && $page eq $bestlink &&
1009 ! defined $opts{anchor};
1011 if (! $destsources{$bestlink}) {
1012 $bestlink=htmlpage($bestlink);
1014 if (! $destsources{$bestlink}) {
1015 return $linktext unless length $config{cgiurl};
1016 return "<span class=\"createlink\"><a href=\"".
1022 "\" rel=\"nofollow\">?</a>$linktext</span>"
1026 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1027 $bestlink=beautify_urlpath($bestlink);
1029 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1030 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1033 if (defined $opts{anchor}) {
1034 $bestlink.="#".$opts{anchor};
1038 if (defined $opts{rel}) {
1039 push @attrs, ' rel="'.$opts{rel}.'"';
1041 if (defined $opts{class}) {
1042 push @attrs, ' class="'.$opts{class}.'"';
1045 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1048 sub userlink ($) { #{{{
1051 my $oiduser=eval { openiduser($user) };
1052 if (defined $oiduser) {
1053 return "<a href=\"$user\">$oiduser</a>";
1056 eval q{use CGI 'escapeHTML'};
1059 return htmllink("", "", escapeHTML(
1060 length $config{userdir} ? $config{userdir}."/".$user : $user
1061 ), noimageinline => 1);
1065 sub htmlize ($$$$) { #{{{
1071 my $oneline = $content !~ /\n/;
1073 if (exists $hooks{htmlize}{$type}) {
1074 $content=$hooks{htmlize}{$type}{call}->(
1076 content => $content,
1080 error("htmlization of $type not supported");
1083 run_hooks(sanitize => sub {
1086 destpage => $destpage,
1087 content => $content,
1092 # hack to get rid of enclosing junk added by markdown
1093 # and other htmlizers
1094 $content=~s/^<p>//i;
1095 $content=~s/<\/p>$//i;
1102 sub linkify ($$$) { #{{{
1107 run_hooks(linkify => sub {
1110 destpage => $destpage,
1111 content => $content,
1119 our $preprocess_preview=0;
1120 sub preprocess ($$$;$$) { #{{{
1121 my $page=shift; # the page the data comes from
1122 my $destpage=shift; # the page the data will appear in (different for inline)
1127 # Using local because it needs to be set within any nested calls
1129 local $preprocess_preview=$preview if defined $preview;
1136 $params="" if ! defined $params;
1138 if (length $escape) {
1139 return "[[$prefix$command $params]]";
1141 elsif (exists $hooks{preprocess}{$command}) {
1142 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1143 # Note: preserve order of params, some plugins may
1144 # consider it significant.
1146 while ($params =~ m{
1147 (?:([-\w]+)=)? # 1: named parameter key?
1149 """(.*?)""" # 2: triple-quoted value
1151 "([^"]+)" # 3: single-quoted value
1153 (\S+) # 4: unquoted value
1155 (?:\s+|$) # delimiter to next param
1165 elsif (defined $3) {
1168 elsif (defined $4) {
1173 push @params, $key, $val;
1176 push @params, $val, '';
1179 if ($preprocessing{$page}++ > 3) {
1180 # Avoid loops of preprocessed pages preprocessing
1181 # other pages that preprocess them, etc.
1182 return "[[!$command <span class=\"error\">".
1183 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1184 $page, $preprocessing{$page}).
1190 $hooks{preprocess}{$command}{call}->(
1193 destpage => $destpage,
1194 preview => $preprocess_preview,
1199 $ret="[[!$command <span class=\"error\">".
1200 gettext("Error").": $@"."</span>]]";
1204 # use void context during scan pass
1206 $hooks{preprocess}{$command}{call}->(
1209 destpage => $destpage,
1210 preview => $preprocess_preview,
1215 $preprocessing{$page}--;
1219 return "[[$prefix$command $params]]";
1224 if ($config{prefix_directives}) {
1227 \[\[(!) # directive open; 2: prefix
1228 ([-\w]+) # 3: command
1229 ( # 4: the parameters..
1230 \s+ # Must have space if parameters present
1232 (?:[-\w]+=)? # named parameter key?
1234 """.*?""" # triple-quoted value
1236 "[^"]+" # single-quoted value
1238 [^\s\]]+ # unquoted value
1240 \s* # whitespace or end
1243 *)? # 0 or more parameters
1244 \]\] # directive closed
1250 \[\[(!?) # directive open; 2: optional prefix
1251 ([-\w]+) # 3: command
1253 ( # 4: the parameters..
1255 (?:[-\w]+=)? # named parameter key?
1257 """.*?""" # triple-quoted value
1259 "[^"]+" # single-quoted value
1261 [^\s\]]+ # unquoted value
1263 \s* # whitespace or end
1266 *) # 0 or more parameters
1267 \]\] # directive closed
1271 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1275 sub filter ($$$) { #{{{
1280 run_hooks(filter => sub {
1281 $content=shift->(page => $page, destpage => $destpage,
1282 content => $content);
1288 sub indexlink () { #{{{
1289 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1294 sub lockwiki () { #{{{
1295 # Take an exclusive lock on the wiki to prevent multiple concurrent
1296 # run issues. The lock will be dropped on program exit.
1297 if (! -d $config{wikistatedir}) {
1298 mkdir($config{wikistatedir});
1300 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1301 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1302 if (! flock($wikilock, 2)) { # LOCK_EX
1303 error("failed to get lock");
1308 sub unlockwiki () { #{{{
1309 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1310 return close($wikilock) if $wikilock;
1316 sub commit_hook_enabled () { #{{{
1317 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1318 error("cannot write to $config{wikistatedir}/commitlock: $!");
1319 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1320 close($commitlock) || error("failed closing commitlock: $!");
1323 close($commitlock) || error("failed closing commitlock: $!");
1327 sub disable_commit_hook () { #{{{
1328 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1329 error("cannot write to $config{wikistatedir}/commitlock: $!");
1330 if (! flock($commitlock, 2)) { # LOCK_EX
1331 error("failed to get commit lock");
1336 sub enable_commit_hook () { #{{{
1337 return close($commitlock) if $commitlock;
1341 sub loadindex () { #{{{
1342 %oldrenderedfiles=%pagectime=();
1343 if (! $config{rebuild}) {
1344 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1345 %destsources=%renderedfiles=%pagecase=%pagestate=();
1348 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1349 if (-e "$config{wikistatedir}/index") {
1350 system("ikiwiki-transition", "indexdb", $config{srcdir});
1351 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1358 my $index=Storable::fd_retrieve($in);
1359 if (! defined $index) {
1364 if (exists $index->{version} && ! ref $index->{version}) {
1365 $pages=$index->{page};
1366 %wikistate=%{$index->{state}};
1373 foreach my $src (keys %$pages) {
1374 my $d=$pages->{$src};
1375 my $page=pagename($src);
1376 $pagectime{$page}=$d->{ctime};
1377 if (! $config{rebuild}) {
1378 $pagesources{$page}=$src;
1379 $pagemtime{$page}=$d->{mtime};
1380 $renderedfiles{$page}=$d->{dest};
1381 if (exists $d->{links} && ref $d->{links}) {
1382 $links{$page}=$d->{links};
1383 $oldlinks{$page}=[@{$d->{links}}];
1385 if (exists $d->{depends}) {
1386 $depends{$page}=$d->{depends};
1388 if (exists $d->{state}) {
1389 $pagestate{$page}=$d->{state};
1392 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1394 foreach my $page (keys %pagesources) {
1395 $pagecase{lc $page}=$page;
1397 foreach my $page (keys %renderedfiles) {
1398 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1403 sub saveindex () { #{{{
1404 run_hooks(savestate => sub { shift->() });
1407 foreach my $type (keys %hooks) {
1408 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1410 my @hookids=keys %hookids;
1412 if (! -d $config{wikistatedir}) {
1413 mkdir($config{wikistatedir});
1415 my $newfile="$config{wikistatedir}/indexdb.new";
1416 my $cleanup = sub { unlink($newfile) };
1417 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1420 foreach my $page (keys %pagemtime) {
1421 next unless $pagemtime{$page};
1422 my $src=$pagesources{$page};
1424 $index{page}{$src}={
1425 ctime => $pagectime{$page},
1426 mtime => $pagemtime{$page},
1427 dest => $renderedfiles{$page},
1428 links => $links{$page},
1431 if (exists $depends{$page}) {
1432 $index{page}{$src}{depends} = $depends{$page};
1435 if (exists $pagestate{$page}) {
1436 foreach my $id (@hookids) {
1437 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1438 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1445 foreach my $id (@hookids) {
1446 foreach my $key (keys %{$wikistate{$id}}) {
1447 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1451 $index{version}="3";
1452 my $ret=Storable::nstore_fd(\%index, $out);
1453 return if ! defined $ret || ! $ret;
1454 close $out || error("failed saving to $newfile: $!", $cleanup);
1455 rename($newfile, "$config{wikistatedir}/indexdb") ||
1456 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1461 sub template_file ($) { #{{{
1464 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1465 return "$dir/$template" if -e "$dir/$template";
1470 sub template_params (@) { #{{{
1471 my $filename=template_file(shift);
1473 if (! defined $filename) {
1474 return if wantarray;
1480 my $text_ref = shift;
1481 ${$text_ref} = decode_utf8(${$text_ref});
1483 filename => $filename,
1484 loop_context_vars => 1,
1485 die_on_bad_params => 0,
1488 return wantarray ? @ret : {@ret};
1491 sub template ($;@) { #{{{
1492 require HTML::Template;
1493 return HTML::Template->new(template_params(@_));
1496 sub misctemplate ($$;@) { #{{{
1500 my $template=template("misc.tmpl");
1503 indexlink => indexlink(),
1504 wikiname => $config{wikiname},
1505 pagebody => $pagebody,
1506 baseurl => baseurl(),
1509 run_hooks(pagetemplate => sub {
1510 shift->(page => "", destpage => "", template => $template);
1512 return $template->output;
1515 sub hook (@) { # {{{
1518 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1519 error 'hook requires type, call, and id parameters';
1522 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1524 $hooks{$param{type}}{$param{id}}=\%param;
1528 sub run_hooks ($$) { # {{{
1529 # Calls the given sub for each hook of the given type,
1530 # passing it the hook function to call.
1534 if (exists $hooks{$type}) {
1536 foreach my $id (keys %{$hooks{$type}}) {
1537 if ($hooks{$type}{$id}{last}) {
1538 push @deferred, $id;
1541 $sub->($hooks{$type}{$id}{call});
1543 foreach my $id (@deferred) {
1544 $sub->($hooks{$type}{$id}{call});
1551 sub rcs_update () { #{{{
1552 $hooks{rcs}{rcs_update}{call}->(@_);
1555 sub rcs_prepedit ($) { #{{{
1556 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1559 sub rcs_commit ($$$;$$) { #{{{
1560 $hooks{rcs}{rcs_commit}{call}->(@_);
1563 sub rcs_commit_staged ($$$) { #{{{
1564 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1567 sub rcs_add ($) { #{{{
1568 $hooks{rcs}{rcs_add}{call}->(@_);
1571 sub rcs_remove ($) { #{{{
1572 $hooks{rcs}{rcs_remove}{call}->(@_);
1575 sub rcs_rename ($$) { #{{{
1576 $hooks{rcs}{rcs_rename}{call}->(@_);
1579 sub rcs_recentchanges ($) { #{{{
1580 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1583 sub rcs_diff ($) { #{{{
1584 $hooks{rcs}{rcs_diff}{call}->(@_);
1587 sub rcs_getctime ($) { #{{{
1588 $hooks{rcs}{rcs_getctime}{call}->(@_);
1591 sub rcs_receive () { #{{{
1592 $hooks{rcs}{rcs_receive}{call}->();
1595 sub globlist_to_pagespec ($) { #{{{
1596 my @globlist=split(' ', shift);
1599 foreach my $glob (@globlist) {
1600 if ($glob=~/^!(.*)/) {
1608 my $spec=join(' or ', @spec);
1610 my $skip=join(' and ', @skip);
1612 $spec="$skip and ($spec)";
1621 sub is_globlist ($) { #{{{
1623 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1626 sub safequote ($) { #{{{
1632 sub add_depends ($$) { #{{{
1636 return unless pagespec_valid($pagespec);
1638 if (! exists $depends{$page}) {
1639 $depends{$page}=$pagespec;
1642 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1648 sub file_pruned ($$) { #{{{
1650 my $file=File::Spec->canonpath(shift);
1651 my $base=File::Spec->canonpath(shift);
1652 $file =~ s#^\Q$base\E/+##;
1654 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1655 return $file =~ m/$regexp/ && $file ne $base;
1659 # Only use gettext in the rare cases it's needed.
1660 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1661 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1662 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1663 if (! $gettext_obj) {
1664 $gettext_obj=eval q{
1665 use Locale::gettext q{textdomain};
1666 Locale::gettext->domain('ikiwiki')
1674 return $gettext_obj->get(shift);
1681 sub yesno ($) { #{{{
1684 return (defined $val && lc($val) eq gettext("yes"));
1688 # Injects a new function into the symbol table to replace an
1689 # exported function.
1692 # This is deep ugly perl foo, beware.
1695 if (! defined $params{parent}) {
1696 $params{parent}='::';
1697 $params{old}=\&{$params{name}};
1698 $params{name}=~s/.*:://;
1700 my $parent=$params{parent};
1701 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1702 $ns = $params{parent} . $ns;
1703 inject(%params, parent => $ns) unless $ns eq '::main::';
1704 *{$ns . $params{name}} = $params{call}
1705 if exists ${$ns}{$params{name}} &&
1706 \&{${$ns}{$params{name}}} == $params{old};
1712 sub pagespec_merge ($$) { #{{{
1716 return $a if $a eq $b;
1718 # Support for old-style GlobLists.
1719 if (is_globlist($a)) {
1720 $a=globlist_to_pagespec($a);
1722 if (is_globlist($b)) {
1723 $b=globlist_to_pagespec($b);
1726 return "($a) or ($b)";
1729 sub pagespec_translate ($) { #{{{
1732 # Support for old-style GlobLists.
1733 if (is_globlist($spec)) {
1734 $spec=globlist_to_pagespec($spec);
1737 # Convert spec to perl code.
1740 \s* # ignore whitespace
1741 ( # 1: match a single word
1748 \w+\([^\)]*\) # command(params)
1750 [^\s()]+ # any other text
1752 \s* # ignore whitespace
1755 if (lc $word eq 'and') {
1758 elsif (lc $word eq 'or') {
1761 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1764 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1765 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1766 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1773 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1777 if (! length $code) {
1782 return eval 'sub { my $page=shift; '.$code.' }';
1785 sub pagespec_match ($$;@) { #{{{
1790 # Backwards compatability with old calling convention.
1792 unshift @params, 'location';
1795 my $sub=pagespec_translate($spec);
1796 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1797 return $sub->($page, @params);
1800 sub pagespec_valid ($) { #{{{
1803 my $sub=pagespec_translate($spec);
1807 sub glob2re ($) { #{{{
1808 my $re=quotemeta(shift);
1814 package IkiWiki::FailReason;
1817 '""' => sub { ${$_[0]} },
1819 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1826 return bless \$value, $class;
1829 package IkiWiki::SuccessReason;
1832 '""' => sub { ${$_[0]} },
1834 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1841 return bless \$value, $class;
1844 package IkiWiki::PageSpec;
1846 sub match_glob ($$;@) { #{{{
1851 my $from=exists $params{location} ? $params{location} : '';
1854 if ($glob =~ m!^\./!) {
1855 $from=~s#/?[^/]+$##;
1857 $glob="$from/$glob" if length $from;
1860 my $regexp=IkiWiki::glob2re($glob);
1861 if ($page=~/^$regexp$/i) {
1862 if (! IkiWiki::isinternal($page) || $params{internal}) {
1863 return IkiWiki::SuccessReason->new("$glob matches $page");
1866 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1870 return IkiWiki::FailReason->new("$glob does not match $page");
1874 sub match_internal ($$;@) { #{{{
1875 return match_glob($_[0], $_[1], @_, internal => 1)
1878 sub match_link ($$;@) { #{{{
1883 my $from=exists $params{location} ? $params{location} : '';
1886 if ($link =~ m!^\.! && defined $from) {
1887 $from=~s#/?[^/]+$##;
1889 $link="$from/$link" if length $from;
1892 my $links = $IkiWiki::links{$page};
1893 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1894 my $bestlink = IkiWiki::bestlink($from, $link);
1895 foreach my $p (@{$links}) {
1896 if (length $bestlink) {
1897 return IkiWiki::SuccessReason->new("$page links to $link")
1898 if $bestlink eq IkiWiki::bestlink($page, $p);
1901 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1902 if match_glob($p, $link, %params);
1905 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1906 if match_glob($p, $link, %params);
1909 return IkiWiki::FailReason->new("$page does not link to $link");
1912 sub match_backlink ($$;@) { #{{{
1913 return match_link($_[1], $_[0], @_);
1916 sub match_created_before ($$;@) { #{{{
1920 if (exists $IkiWiki::pagectime{$testpage}) {
1921 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1922 return IkiWiki::SuccessReason->new("$page created before $testpage");
1925 return IkiWiki::FailReason->new("$page not created before $testpage");
1929 return IkiWiki::FailReason->new("$testpage has no ctime");
1933 sub match_created_after ($$;@) { #{{{
1937 if (exists $IkiWiki::pagectime{$testpage}) {
1938 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1939 return IkiWiki::SuccessReason->new("$page created after $testpage");
1942 return IkiWiki::FailReason->new("$page not created after $testpage");
1946 return IkiWiki::FailReason->new("$testpage has no ctime");
1950 sub match_creation_day ($$;@) { #{{{
1951 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1952 return IkiWiki::SuccessReason->new('creation_day matched');
1955 return IkiWiki::FailReason->new('creation_day did not match');
1959 sub match_creation_month ($$;@) { #{{{
1960 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1961 return IkiWiki::SuccessReason->new('creation_month matched');
1964 return IkiWiki::FailReason->new('creation_month did not match');
1968 sub match_creation_year ($$;@) { #{{{
1969 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1970 return IkiWiki::SuccessReason->new('creation_year matched');
1973 return IkiWiki::FailReason->new('creation_year did not match');
1977 sub match_user ($$;@) { #{{{
1982 if (! exists $params{user}) {
1983 return IkiWiki::FailReason->new("no user specified");
1986 if (defined $params{user} && lc $params{user} eq lc $user) {
1987 return IkiWiki::SuccessReason->new("user is $user");
1989 elsif (! defined $params{user}) {
1990 return IkiWiki::FailReason->new("not logged in");
1993 return IkiWiki::FailReason->new("user is $params{user}, not $user");
1997 sub match_admin ($$;@) { #{{{
2002 if (! exists $params{user}) {
2003 return IkiWiki::FailReason->new("no user specified");
2006 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2007 return IkiWiki::SuccessReason->new("user is an admin");
2009 elsif (! defined $params{user}) {
2010 return IkiWiki::FailReason->new("not logged in");
2013 return IkiWiki::FailReason->new("user is not an admin");
2017 sub match_ip ($$;@) { #{{{
2022 if (! exists $params{ip}) {
2023 return IkiWiki::FailReason->new("no IP specified");
2026 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2027 return IkiWiki::SuccessReason->new("IP is $ip");
2030 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");