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 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
282 description => "force ikiwiki to use a particular umask",
284 safe => 0, # paranoia
290 example => "$ENV{HOME}/.ikiwiki/",
291 description => "extra library and plugin directory",
293 safe => 0, # directory
299 description => "environment variables",
300 safe => 0, # paranoia
307 description => "regexp of source files to ignore",
312 wiki_file_prune_regexps => {
314 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
315 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
316 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
319 description => "regexps of source files to ignore",
325 description => "specifies the characters that are allowed in source filenames",
326 default => "-[:alnum:]+/.:_",
330 wiki_file_regexp => {
332 description => "regexp of legal source files",
336 web_commit_regexp => {
338 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
339 description => "regexp to parse web commits from logs",
346 description => "run as a cgi",
350 cgi_disable_uploads => {
353 description => "whether CGI should accept file uploads",
360 description => "run as a post-commit hook",
367 description => "running in rebuild mode",
374 description => "running in setup mode",
381 description => "running in refresh mode",
388 description => "running in getctime mode",
395 description => "running in w3mmode",
402 description => "path to setup file",
406 allow_symlinks_before_srcdir => {
409 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
415 sub defaultconfig () { #{{{
418 foreach my $key (keys %s) {
419 push @ret, $key, $s{$key}->{default};
425 sub checkconfig () { #{{{
426 # locale stuff; avoid LC_ALL since it overrides everything
427 if (defined $ENV{LC_ALL}) {
428 $ENV{LANG} = $ENV{LC_ALL};
431 if (defined $config{locale}) {
432 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
433 $ENV{LANG}=$config{locale};
438 if (! defined $config{wiki_file_regexp}) {
439 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
442 if (ref $config{ENV} eq 'HASH') {
443 foreach my $val (keys %{$config{ENV}}) {
444 $ENV{$val}=$config{ENV}{$val};
448 if ($config{w3mmode}) {
449 eval q{use Cwd q{abs_path}};
451 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
452 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
453 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
454 unless $config{cgiurl} =~ m!file:///!;
455 $config{url}="file://".$config{destdir};
458 if ($config{cgi} && ! length $config{url}) {
459 error(gettext("Must specify url to wiki with --url when using --cgi"));
462 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
463 unless exists $config{wikistatedir};
465 if (defined $config{umask}) {
466 umask(possibly_foolish_untaint($config{umask}));
469 run_hooks(checkconfig => sub { shift->() });
474 sub listplugins () { #{{{
477 foreach my $dir (@INC, $config{libdir}) {
478 next unless defined $dir && length $dir;
479 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
480 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
484 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
485 next unless defined $dir && length $dir;
486 foreach my $file (glob("$dir/plugins/*")) {
487 $ret{basename($file)}=1 if -x $file;
494 sub loadplugins () { #{{{
495 if (defined $config{libdir} && length $config{libdir}) {
496 unshift @INC, possibly_foolish_untaint($config{libdir});
499 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
504 if (exists $IkiWiki::hooks{rcs}) {
505 error(gettext("cannot use multiple rcs plugins"));
507 loadplugin($config{rcs});
509 if (! exists $IkiWiki::hooks{rcs}) {
513 run_hooks(getopt => sub { shift->() });
514 if (grep /^-/, @ARGV) {
515 print STDERR "Unknown option: $_\n"
516 foreach grep /^-/, @ARGV;
523 sub loadplugin ($) { #{{{
526 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
528 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
529 "$installdir/lib/ikiwiki") {
530 if (defined $dir && -x "$dir/plugins/$plugin") {
531 eval { require IkiWiki::Plugin::external };
534 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
536 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
537 $loaded_plugins{$plugin}=1;
542 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
545 error("Failed to load plugin $mod: $@");
547 $loaded_plugins{$plugin}=1;
551 sub error ($;$) { #{{{
554 log_message('err' => $message) if $config{syslog};
555 if (defined $cleaner) {
562 return unless $config{verbose};
563 return log_message(debug => @_);
567 sub log_message ($$) { #{{{
570 if ($config{syslog}) {
573 Sys::Syslog::setlogsock('unix');
574 Sys::Syslog::openlog('ikiwiki', '', 'user');
578 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
581 elsif (! $config{cgi}) {
585 return print STDERR "@_\n";
589 sub possibly_foolish_untaint ($) { #{{{
591 my ($untainted)=$tainted=~/(.*)/s;
595 sub basename ($) { #{{{
602 sub dirname ($) { #{{{
609 sub pagetype ($) { #{{{
612 if ($page =~ /\.([^.]+)$/) {
613 return $1 if exists $hooks{htmlize}{$1};
618 sub isinternal ($) { #{{{
620 return exists $pagesources{$page} &&
621 $pagesources{$page} =~ /\._([^.]+)$/;
624 sub pagename ($) { #{{{
627 my $type=pagetype($file);
629 $page=~s/\Q.$type\E*$// if defined $type && !$hooks{htmlize}{$type}{keepextension};
630 if ($config{indexpages} && $page=~/(.*)\/index$/) {
636 sub newpagefile ($$) { #{{{
640 if (! $config{indexpages} || $page eq 'index') {
641 return $page.".".$type;
644 return $page."/index.".$type;
648 sub targetpage ($$) { #{{{
652 if (! $config{usedirs} || $page eq 'index') {
653 return $page.".".$ext;
656 return $page."/index.".$ext;
660 sub htmlpage ($) { #{{{
663 return targetpage($page, $config{htmlext});
666 sub srcfile_stat { #{{{
670 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
671 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
672 return "$dir/$file", stat(_) if -e "$dir/$file";
674 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
678 sub srcfile ($;$) { #{{{
679 return (srcfile_stat(@_))[0];
682 sub add_underlay ($) { #{{{
686 $dir="$config{underlaydir}/../$dir";
689 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
690 unshift @{$config{underlaydirs}}, $dir;
696 sub readfile ($;$$) { #{{{
702 error("cannot read a symlink ($file)");
706 open (my $in, "<", $file) || error("failed to read $file: $!");
707 binmode($in) if ($binary);
708 return \*$in if $wantfd;
710 close $in || error("failed to read $file: $!");
714 sub prep_writefile ($$) { #{{{
719 while (length $test) {
720 if (-l "$destdir/$test") {
721 error("cannot write to a symlink ($test)");
723 $test=dirname($test);
726 my $dir=dirname("$destdir/$file");
729 foreach my $s (split(m!/+!, $dir)) {
732 mkdir($d) || error("failed to create directory $d: $!");
740 sub writefile ($$$;$$) { #{{{
741 my $file=shift; # can include subdirs
742 my $destdir=shift; # directory to put file in
747 prep_writefile($file, $destdir);
749 my $newfile="$destdir/$file.ikiwiki-new";
751 error("cannot write to a symlink ($newfile)");
754 my $cleanup = sub { unlink($newfile) };
755 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
756 binmode($out) if ($binary);
758 $writer->(\*$out, $cleanup);
761 print $out $content or error("failed writing to $newfile: $!", $cleanup);
763 close $out || error("failed saving $newfile: $!", $cleanup);
764 rename($newfile, "$destdir/$file") ||
765 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
771 sub will_render ($$;$) { #{{{
776 # Important security check.
777 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
778 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
779 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
782 if (! $clear || $cleared{$page}) {
783 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
786 foreach my $old (@{$renderedfiles{$page}}) {
787 delete $destsources{$old};
789 $renderedfiles{$page}=[$dest];
792 $destsources{$dest}=$page;
797 sub bestlink ($$) { #{{{
802 if ($link=~s/^\/+//) {
810 $l.="/" if length $l;
813 if (exists $links{$l}) {
816 elsif (exists $pagecase{lc $l}) {
817 return $pagecase{lc $l};
819 } while $cwd=~s{/?[^/]+$}{};
821 if (length $config{userdir}) {
822 my $l = "$config{userdir}/".lc($link);
823 if (exists $links{$l}) {
826 elsif (exists $pagecase{lc $l}) {
827 return $pagecase{lc $l};
831 #print STDERR "warning: page $page, broken link: $link\n";
835 sub isinlinableimage ($) { #{{{
838 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
841 sub pagetitle ($;$) { #{{{
846 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
849 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
855 sub titlepage ($) { #{{{
857 # support use w/o %config set
858 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
859 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
863 sub linkpage ($) { #{{{
865 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
866 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
870 sub cgiurl (@) { #{{{
873 return $config{cgiurl}."?".
874 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
877 sub baseurl (;$) { #{{{
880 return "$config{url}/" if ! defined $page;
882 $page=htmlpage($page);
884 $page=~s/[^\/]+\//..\//g;
888 sub abs2rel ($$) { #{{{
889 # Work around very innefficient behavior in File::Spec if abs2rel
890 # is passed two relative paths. It's much faster if paths are
891 # absolute! (Debian bug #376658; fixed in debian unstable now)
896 my $ret=File::Spec->abs2rel($path, $base);
897 $ret=~s/^// if defined $ret;
901 sub displaytime ($;$) { #{{{
902 # Plugins can override this function to mark up the time to
904 return '<span class="date">'.formattime(@_).'</span>';
907 sub formattime ($;$) { #{{{
908 # Plugins can override this function to format the time.
911 if (! defined $format) {
912 $format=$config{timeformat};
915 # strftime doesn't know about encodings, so make sure
916 # its output is properly treated as utf8
917 return decode_utf8(POSIX::strftime($format, localtime($time)));
920 sub beautify_urlpath ($) { #{{{
923 if ($config{usedirs}) {
924 $url =~ s!/index.$config{htmlext}$!/!;
927 # Ensure url is not an empty link, and
928 # if it's relative, make that explicit to avoid colon confusion.
936 sub urlto ($$;$) { #{{{
942 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
945 if (! $destsources{$to}) {
950 return $config{url}.beautify_urlpath("/".$to);
953 my $link = abs2rel($to, dirname(htmlpage($from)));
955 return beautify_urlpath($link);
958 sub htmllink ($$$;@) { #{{{
959 my $lpage=shift; # the page doing the linking
960 my $page=shift; # the page that will contain the link (different for inline)
967 if (! $opts{forcesubpage}) {
968 $bestlink=bestlink($lpage, $link);
971 $bestlink="$lpage/".lc($link);
975 if (defined $opts{linktext}) {
976 $linktext=$opts{linktext};
979 $linktext=pagetitle(basename($link));
982 return "<span class=\"selflink\">$linktext</span>"
983 if length $bestlink && $page eq $bestlink &&
984 ! defined $opts{anchor};
986 if (! $destsources{$bestlink}) {
987 $bestlink=htmlpage($bestlink);
989 if (! $destsources{$bestlink}) {
990 return $linktext unless length $config{cgiurl};
991 return "<span class=\"createlink\"><a href=\"".
997 "\" rel=\"nofollow\">?</a>$linktext</span>"
1001 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1002 $bestlink=beautify_urlpath($bestlink);
1004 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1005 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1008 if (defined $opts{anchor}) {
1009 $bestlink.="#".$opts{anchor};
1013 if (defined $opts{rel}) {
1014 push @attrs, ' rel="'.$opts{rel}.'"';
1016 if (defined $opts{class}) {
1017 push @attrs, ' class="'.$opts{class}.'"';
1020 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1023 sub userlink ($) { #{{{
1026 my $oiduser=eval { openiduser($user) };
1027 if (defined $oiduser) {
1028 return "<a href=\"$user\">$oiduser</a>";
1031 eval q{use CGI 'escapeHTML'};
1034 return htmllink("", "", escapeHTML(
1035 length $config{userdir} ? $config{userdir}."/".$user : $user
1036 ), noimageinline => 1);
1040 sub htmlize ($$$$) { #{{{
1046 my $oneline = $content !~ /\n/;
1048 if (exists $hooks{htmlize}{$type}) {
1049 $content=$hooks{htmlize}{$type}{call}->(
1051 content => $content,
1055 error("htmlization of $type not supported");
1058 run_hooks(sanitize => sub {
1061 destpage => $destpage,
1062 content => $content,
1067 # hack to get rid of enclosing junk added by markdown
1068 # and other htmlizers
1069 $content=~s/^<p>//i;
1070 $content=~s/<\/p>$//i;
1077 sub linkify ($$$) { #{{{
1082 run_hooks(linkify => sub {
1085 destpage => $destpage,
1086 content => $content,
1094 our $preprocess_preview=0;
1095 sub preprocess ($$$;$$) { #{{{
1096 my $page=shift; # the page the data comes from
1097 my $destpage=shift; # the page the data will appear in (different for inline)
1102 # Using local because it needs to be set within any nested calls
1104 local $preprocess_preview=$preview if defined $preview;
1111 $params="" if ! defined $params;
1113 if (length $escape) {
1114 return "[[$prefix$command $params]]";
1116 elsif (exists $hooks{preprocess}{$command}) {
1117 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1118 # Note: preserve order of params, some plugins may
1119 # consider it significant.
1121 while ($params =~ m{
1122 (?:([-\w]+)=)? # 1: named parameter key?
1124 """(.*?)""" # 2: triple-quoted value
1126 "([^"]+)" # 3: single-quoted value
1128 (\S+) # 4: unquoted value
1130 (?:\s+|$) # delimiter to next param
1140 elsif (defined $3) {
1143 elsif (defined $4) {
1148 push @params, $key, $val;
1151 push @params, $val, '';
1154 if ($preprocessing{$page}++ > 3) {
1155 # Avoid loops of preprocessed pages preprocessing
1156 # other pages that preprocess them, etc.
1157 return "[[!$command <span class=\"error\">".
1158 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1159 $page, $preprocessing{$page}).
1165 $hooks{preprocess}{$command}{call}->(
1168 destpage => $destpage,
1169 preview => $preprocess_preview,
1174 $ret="[[!$command <span class=\"error\">".
1175 gettext("Error").": $@"."</span>]]";
1179 # use void context during scan pass
1181 $hooks{preprocess}{$command}{call}->(
1184 destpage => $destpage,
1185 preview => $preprocess_preview,
1190 $preprocessing{$page}--;
1194 return "[[$prefix$command $params]]";
1199 if ($config{prefix_directives}) {
1202 \[\[(!) # directive open; 2: prefix
1203 ([-\w]+) # 3: command
1204 ( # 4: the parameters..
1205 \s+ # Must have space if parameters present
1207 (?:[-\w]+=)? # named parameter key?
1209 """.*?""" # triple-quoted value
1211 "[^"]+" # single-quoted value
1213 [^\s\]]+ # unquoted value
1215 \s* # whitespace or end
1218 *)? # 0 or more parameters
1219 \]\] # directive closed
1225 \[\[(!?) # directive open; 2: optional prefix
1226 ([-\w]+) # 3: command
1228 ( # 4: the parameters..
1230 (?:[-\w]+=)? # named parameter key?
1232 """.*?""" # triple-quoted value
1234 "[^"]+" # single-quoted value
1236 [^\s\]]+ # unquoted value
1238 \s* # whitespace or end
1241 *) # 0 or more parameters
1242 \]\] # directive closed
1246 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1250 sub filter ($$$) { #{{{
1255 run_hooks(filter => sub {
1256 $content=shift->(page => $page, destpage => $destpage,
1257 content => $content);
1263 sub indexlink () { #{{{
1264 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1269 sub lockwiki (;$) { #{{{
1270 my $wait=@_ ? shift : 1;
1271 # Take an exclusive lock on the wiki to prevent multiple concurrent
1272 # run issues. The lock will be dropped on program exit.
1273 if (! -d $config{wikistatedir}) {
1274 mkdir($config{wikistatedir});
1276 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1277 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1278 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1280 debug("wiki seems to be locked, waiting for lock");
1281 my $wait=600; # arbitrary, but don't hang forever to
1282 # prevent process pileup
1284 return if flock($wikilock, 2 | 4);
1287 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1296 sub unlockwiki () { #{{{
1297 return close($wikilock) if $wikilock;
1303 sub commit_hook_enabled () { #{{{
1304 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1305 error("cannot write to $config{wikistatedir}/commitlock: $!");
1306 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1307 close($commitlock) || error("failed closing commitlock: $!");
1310 close($commitlock) || error("failed closing commitlock: $!");
1314 sub disable_commit_hook () { #{{{
1315 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1316 error("cannot write to $config{wikistatedir}/commitlock: $!");
1317 if (! flock($commitlock, 2)) { # LOCK_EX
1318 error("failed to get commit lock");
1323 sub enable_commit_hook () { #{{{
1324 return close($commitlock) if $commitlock;
1328 sub loadindex () { #{{{
1329 %oldrenderedfiles=%pagectime=();
1330 if (! $config{rebuild}) {
1331 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1332 %destsources=%renderedfiles=%pagecase=%pagestate=();
1335 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1336 if (-e "$config{wikistatedir}/index") {
1337 system("ikiwiki-transition", "indexdb", $config{srcdir});
1338 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1345 my $index=Storable::fd_retrieve($in);
1346 if (! defined $index) {
1351 if (exists $index->{version} && ! ref $index->{version}) {
1352 $pages=$index->{page};
1353 %wikistate=%{$index->{state}};
1360 foreach my $src (keys %$pages) {
1361 my $d=$pages->{$src};
1362 my $page=pagename($src);
1363 $pagectime{$page}=$d->{ctime};
1364 if (! $config{rebuild}) {
1365 $pagesources{$page}=$src;
1366 $pagemtime{$page}=$d->{mtime};
1367 $renderedfiles{$page}=$d->{dest};
1368 if (exists $d->{links} && ref $d->{links}) {
1369 $links{$page}=$d->{links};
1370 $oldlinks{$page}=[@{$d->{links}}];
1372 if (exists $d->{depends}) {
1373 $depends{$page}=$d->{depends};
1375 if (exists $d->{state}) {
1376 $pagestate{$page}=$d->{state};
1379 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1381 foreach my $page (keys %pagesources) {
1382 $pagecase{lc $page}=$page;
1384 foreach my $page (keys %renderedfiles) {
1385 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1390 sub saveindex () { #{{{
1391 run_hooks(savestate => sub { shift->() });
1394 foreach my $type (keys %hooks) {
1395 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1397 my @hookids=keys %hookids;
1399 if (! -d $config{wikistatedir}) {
1400 mkdir($config{wikistatedir});
1402 my $newfile="$config{wikistatedir}/indexdb.new";
1403 my $cleanup = sub { unlink($newfile) };
1404 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1407 foreach my $page (keys %pagemtime) {
1408 next unless $pagemtime{$page};
1409 my $src=$pagesources{$page};
1411 $index{page}{$src}={
1412 ctime => $pagectime{$page},
1413 mtime => $pagemtime{$page},
1414 dest => $renderedfiles{$page},
1415 links => $links{$page},
1418 if (exists $depends{$page}) {
1419 $index{page}{$src}{depends} = $depends{$page};
1422 if (exists $pagestate{$page}) {
1423 foreach my $id (@hookids) {
1424 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1425 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1432 foreach my $id (@hookids) {
1433 foreach my $key (keys %{$wikistate{$id}}) {
1434 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1438 $index{version}="3";
1439 my $ret=Storable::nstore_fd(\%index, $out);
1440 return if ! defined $ret || ! $ret;
1441 close $out || error("failed saving to $newfile: $!", $cleanup);
1442 rename($newfile, "$config{wikistatedir}/indexdb") ||
1443 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1448 sub template_file ($) { #{{{
1451 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1452 return "$dir/$template" if -e "$dir/$template";
1457 sub template_params (@) { #{{{
1458 my $filename=template_file(shift);
1460 if (! defined $filename) {
1461 return if wantarray;
1467 my $text_ref = shift;
1468 ${$text_ref} = decode_utf8(${$text_ref});
1470 filename => $filename,
1471 loop_context_vars => 1,
1472 die_on_bad_params => 0,
1475 return wantarray ? @ret : {@ret};
1478 sub template ($;@) { #{{{
1479 require HTML::Template;
1480 return HTML::Template->new(template_params(@_));
1483 sub misctemplate ($$;@) { #{{{
1487 my $template=template("misc.tmpl");
1490 indexlink => indexlink(),
1491 wikiname => $config{wikiname},
1492 pagebody => $pagebody,
1493 baseurl => baseurl(),
1496 run_hooks(pagetemplate => sub {
1497 shift->(page => "", destpage => "", template => $template);
1499 return $template->output;
1502 sub hook (@) { # {{{
1505 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1506 error 'hook requires type, call, and id parameters';
1509 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1511 $hooks{$param{type}}{$param{id}}=\%param;
1515 sub run_hooks ($$) { # {{{
1516 # Calls the given sub for each hook of the given type,
1517 # passing it the hook function to call.
1521 if (exists $hooks{$type}) {
1523 foreach my $id (keys %{$hooks{$type}}) {
1524 if ($hooks{$type}{$id}{last}) {
1525 push @deferred, $id;
1528 $sub->($hooks{$type}{$id}{call});
1530 foreach my $id (@deferred) {
1531 $sub->($hooks{$type}{$id}{call});
1538 sub rcs_update () { #{{{
1539 $hooks{rcs}{rcs_update}{call}->(@_);
1542 sub rcs_prepedit ($) { #{{{
1543 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1546 sub rcs_commit ($$$;$$) { #{{{
1547 $hooks{rcs}{rcs_commit}{call}->(@_);
1550 sub rcs_commit_staged ($$$) { #{{{
1551 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1554 sub rcs_add ($) { #{{{
1555 $hooks{rcs}{rcs_add}{call}->(@_);
1558 sub rcs_remove ($) { #{{{
1559 $hooks{rcs}{rcs_remove}{call}->(@_);
1562 sub rcs_rename ($$) { #{{{
1563 $hooks{rcs}{rcs_rename}{call}->(@_);
1566 sub rcs_recentchanges ($) { #{{{
1567 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1570 sub rcs_diff ($) { #{{{
1571 $hooks{rcs}{rcs_diff}{call}->(@_);
1574 sub rcs_getctime ($) { #{{{
1575 $hooks{rcs}{rcs_getctime}{call}->(@_);
1578 sub globlist_to_pagespec ($) { #{{{
1579 my @globlist=split(' ', shift);
1582 foreach my $glob (@globlist) {
1583 if ($glob=~/^!(.*)/) {
1591 my $spec=join(' or ', @spec);
1593 my $skip=join(' and ', @skip);
1595 $spec="$skip and ($spec)";
1604 sub is_globlist ($) { #{{{
1606 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1609 sub safequote ($) { #{{{
1615 sub add_depends ($$) { #{{{
1619 return unless pagespec_valid($pagespec);
1621 if (! exists $depends{$page}) {
1622 $depends{$page}=$pagespec;
1625 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1631 sub file_pruned ($$) { #{{{
1633 my $file=File::Spec->canonpath(shift);
1634 my $base=File::Spec->canonpath(shift);
1635 $file =~ s#^\Q$base\E/+##;
1637 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1638 return $file =~ m/$regexp/ && $file ne $base;
1642 # Only use gettext in the rare cases it's needed.
1643 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1644 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1645 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1646 if (! $gettext_obj) {
1647 $gettext_obj=eval q{
1648 use Locale::gettext q{textdomain};
1649 Locale::gettext->domain('ikiwiki')
1657 return $gettext_obj->get(shift);
1664 sub yesno ($) { #{{{
1667 return (defined $val && lc($val) eq gettext("yes"));
1671 # Injects a new function into the symbol table to replace an
1672 # exported function.
1675 # This is deep ugly perl foo, beware.
1678 if (! defined $params{parent}) {
1679 $params{parent}='::';
1680 $params{old}=\&{$params{name}};
1681 $params{name}=~s/.*:://;
1683 my $parent=$params{parent};
1684 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1685 $ns = $params{parent} . $ns;
1686 inject(%params, parent => $ns) unless $ns eq '::main::';
1687 *{$ns . $params{name}} = $params{call}
1688 if exists ${$ns}{$params{name}} &&
1689 \&{${$ns}{$params{name}}} == $params{old};
1695 sub pagespec_merge ($$) { #{{{
1699 return $a if $a eq $b;
1701 # Support for old-style GlobLists.
1702 if (is_globlist($a)) {
1703 $a=globlist_to_pagespec($a);
1705 if (is_globlist($b)) {
1706 $b=globlist_to_pagespec($b);
1709 return "($a) or ($b)";
1712 sub pagespec_translate ($) { #{{{
1715 # Support for old-style GlobLists.
1716 if (is_globlist($spec)) {
1717 $spec=globlist_to_pagespec($spec);
1720 # Convert spec to perl code.
1723 \s* # ignore whitespace
1724 ( # 1: match a single word
1731 \w+\([^\)]*\) # command(params)
1733 [^\s()]+ # any other text
1735 \s* # ignore whitespace
1738 if (lc $word eq 'and') {
1741 elsif (lc $word eq 'or') {
1744 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1747 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1748 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1749 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1756 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1760 if (! length $code) {
1765 return eval 'sub { my $page=shift; '.$code.' }';
1768 sub pagespec_match ($$;@) { #{{{
1773 # Backwards compatability with old calling convention.
1775 unshift @params, 'location';
1778 my $sub=pagespec_translate($spec);
1779 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1780 return $sub->($page, @params);
1783 sub pagespec_valid ($) { #{{{
1786 my $sub=pagespec_translate($spec);
1790 sub glob2re ($) { #{{{
1791 my $re=quotemeta(shift);
1797 package IkiWiki::FailReason;
1800 '""' => sub { ${$_[0]} },
1802 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1809 return bless \$value, $class;
1812 package IkiWiki::SuccessReason;
1815 '""' => sub { ${$_[0]} },
1817 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1824 return bless \$value, $class;
1827 package IkiWiki::PageSpec;
1829 sub match_glob ($$;@) { #{{{
1834 my $from=exists $params{location} ? $params{location} : '';
1837 if ($glob =~ m!^\./!) {
1838 $from=~s#/?[^/]+$##;
1840 $glob="$from/$glob" if length $from;
1843 my $regexp=IkiWiki::glob2re($glob);
1844 if ($page=~/^$regexp$/i) {
1845 if (! IkiWiki::isinternal($page) || $params{internal}) {
1846 return IkiWiki::SuccessReason->new("$glob matches $page");
1849 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1853 return IkiWiki::FailReason->new("$glob does not match $page");
1857 sub match_internal ($$;@) { #{{{
1858 return match_glob($_[0], $_[1], @_, internal => 1)
1861 sub match_link ($$;@) { #{{{
1866 my $from=exists $params{location} ? $params{location} : '';
1869 if ($link =~ m!^\.! && defined $from) {
1870 $from=~s#/?[^/]+$##;
1872 $link="$from/$link" if length $from;
1875 my $links = $IkiWiki::links{$page};
1876 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1877 my $bestlink = IkiWiki::bestlink($from, $link);
1878 foreach my $p (@{$links}) {
1879 if (length $bestlink) {
1880 return IkiWiki::SuccessReason->new("$page links to $link")
1881 if $bestlink eq IkiWiki::bestlink($page, $p);
1884 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1885 if match_glob($p, $link, %params);
1888 return IkiWiki::FailReason->new("$page does not link to $link");
1891 sub match_backlink ($$;@) { #{{{
1892 return match_link($_[1], $_[0], @_);
1895 sub match_created_before ($$;@) { #{{{
1899 if (exists $IkiWiki::pagectime{$testpage}) {
1900 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1901 return IkiWiki::SuccessReason->new("$page created before $testpage");
1904 return IkiWiki::FailReason->new("$page not created before $testpage");
1908 return IkiWiki::FailReason->new("$testpage has no ctime");
1912 sub match_created_after ($$;@) { #{{{
1916 if (exists $IkiWiki::pagectime{$testpage}) {
1917 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1918 return IkiWiki::SuccessReason->new("$page created after $testpage");
1921 return IkiWiki::FailReason->new("$page not created after $testpage");
1925 return IkiWiki::FailReason->new("$testpage has no ctime");
1929 sub match_creation_day ($$;@) { #{{{
1930 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1931 return IkiWiki::SuccessReason->new('creation_day matched');
1934 return IkiWiki::FailReason->new('creation_day did not match');
1938 sub match_creation_month ($$;@) { #{{{
1939 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1940 return IkiWiki::SuccessReason->new('creation_month matched');
1943 return IkiWiki::FailReason->new('creation_month did not match');
1947 sub match_creation_year ($$;@) { #{{{
1948 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1949 return IkiWiki::SuccessReason->new('creation_year matched');
1952 return IkiWiki::FailReason->new('creation_year did not match');
1956 sub match_user ($$;@) { #{{{
1961 if (! exists $params{user}) {
1962 return IkiWiki::FailReason->new("no user specified");
1965 if (defined $params{user} && lc $params{user} eq lc $user) {
1966 return IkiWiki::SuccessReason->new("user is $user");
1968 elsif (! defined $params{user}) {
1969 return IkiWiki::FailReason->new("not logged in");
1972 return IkiWiki::FailReason->new("user is $params{user}, not $user");
1976 sub match_admin ($$;@) { #{{{
1981 if (! exists $params{user}) {
1982 return IkiWiki::FailReason->new("no user specified");
1985 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
1986 return IkiWiki::SuccessReason->new("user is an admin");
1988 elsif (! defined $params{user}) {
1989 return IkiWiki::FailReason->new("not logged in");
1992 return IkiWiki::FailReason->new("user is not an admin");
1996 sub match_ip ($$;@) { #{{{
2001 if (! exists $params{ip}) {
2002 return IkiWiki::FailReason->new("no IP specified");
2005 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2006 return IkiWiki::SuccessReason->new("IP is $ip");
2009 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");