7 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
14 %renderedfiles %pagesources %depends %hooks %forcerebuild};
16 sub defaultconfig () { #{{{
17 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$|\.rss$)},
18 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
19 wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]*)\]\]/,
20 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
23 default_pageext => "mdwn",
45 templatedir => "/usr/share/ikiwiki/templates",
46 underlaydir => "/usr/share/ikiwiki/basewiki",
50 plugin => [qw{mdwn inline htmlscrubber}],
55 sub checkconfig () { #{{{
56 # locale stuff; avoid LC_ALL since it overrides everything
57 if (defined $ENV{LC_ALL}) {
58 $ENV{LANG} = $ENV{LC_ALL};
61 if (defined $config{locale}) {
63 $ENV{LANG} = $config{locale}
64 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
67 if ($config{w3mmode}) {
68 eval q{use Cwd q{abs_path}};
69 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
70 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
71 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
72 unless $config{cgiurl} =~ m!file:///!;
73 $config{url}="file://".$config{destdir};
76 if ($config{cgi} && ! length $config{url}) {
77 error("Must specify url to wiki with --url when using --cgi\n");
79 if ($config{rss} && ! length $config{url}) {
80 error("Must specify url to wiki with --url when using --rss\n");
83 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
84 unless exists $config{wikistatedir};
87 eval qq{require IkiWiki::Rcs::$config{rcs}};
89 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
93 require IkiWiki::Rcs::Stub;
96 run_hooks(checkconfig => sub { shift->() });
99 sub loadplugins () { #{{{
100 foreach my $plugin (@{$config{plugin}}) {
101 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
104 error("Failed to load plugin $mod: $@");
107 run_hooks(getopt => sub { shift->() });
108 if (grep /^-/, @ARGV) {
109 print STDERR "Unknown option: $_\n"
110 foreach grep /^-/, @ARGV;
117 print "Content-type: text/html\n\n";
118 print misctemplate("Error", "<p>Error: @_</p>");
124 return unless $config{verbose};
125 if (! $config{cgi}) {
133 sub possibly_foolish_untaint ($) { #{{{
135 my ($untainted)=$tainted=~/(.*)/;
139 sub basename ($) { #{{{
146 sub dirname ($) { #{{{
153 sub pagetype ($) { #{{{
156 if ($page =~ /\.([^.]+)$/) {
157 return $1 if exists $hooks{htmlize}{$1};
162 sub pagename ($) { #{{{
165 my $type=pagetype($file);
167 $page=~s/\Q.$type\E*$// if defined $type;
171 sub htmlpage ($) { #{{{
174 return $page.".html";
177 sub srcfile ($) { #{{{
180 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
181 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
182 error("internal error: $file cannot be found");
185 sub readfile ($;$) { #{{{
190 error("cannot read a symlink ($file)");
194 open (IN, $file) || error("failed to read $file: $!");
195 binmode(IN) if ($binary);
201 sub writefile ($$$;$) { #{{{
202 my $file=shift; # can include subdirs
203 my $destdir=shift; # directory to put file in
208 while (length $test) {
209 if (-l "$destdir/$test") {
210 error("cannot write to a symlink ($test)");
212 $test=dirname($test);
215 my $dir=dirname("$destdir/$file");
218 foreach my $s (split(m!/+!, $dir)) {
221 mkdir($d) || error("failed to create directory $d: $!");
226 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
227 binmode(OUT) if ($binary);
232 sub bestlink ($$) { #{{{
233 # Given a page and the text of a link on the page, determine which
234 # existing page that link best points to. Prefers pages under a
235 # subdirectory with the same name as the source page, failing that
236 # goes down the directory tree to the base looking for matching
244 $l.="/" if length $l;
247 if (exists $links{$l}) {
248 #debug("for $page, \"$link\", use $l");
251 } while $cwd=~s!/?[^/]+$!!;
253 #print STDERR "warning: page $page, broken link: $link\n";
257 sub isinlinableimage ($) { #{{{
260 $file=~/\.(png|gif|jpg|jpeg)$/i;
263 sub pagetitle ($) { #{{{
265 $page=~s/__(\d+)__/&#$1;/g;
270 sub titlepage ($) { #{{{
273 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
277 sub cgiurl (@) { #{{{
280 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
283 sub styleurl (;$) { #{{{
286 return "$config{url}/style.css" if ! defined $page;
289 $page=~s/[^\/]+\//..\//g;
290 return $page."style.css";
294 # Work around very innefficient behavior in File::Spec if abs2rel
295 # is passed two relative paths. It's much faster if paths are
301 my $ret=File::Spec->abs2rel($path, $base);
302 $ret=~s/^// if defined $ret;
306 sub htmllink ($$$;$$$) { #{{{
307 my $lpage=shift; # the page doing the linking
308 my $page=shift; # the page that will contain the link (different for inline)
310 my $noimageinline=shift; # don't turn links into inline html images
311 my $forcesubpage=shift; # force a link to a subpage
312 my $linktext=shift; # set to force the link text to something
315 if (! $forcesubpage) {
316 $bestlink=bestlink($lpage, $link);
319 $bestlink="$lpage/".lc($link);
322 $linktext=pagetitle(basename($link)) unless defined $linktext;
324 return $linktext if length $bestlink && $page eq $bestlink;
326 # TODO BUG: %renderedfiles may not have it, if the linked to page
327 # was also added and isn't yet rendered! Note that this bug is
328 # masked by the bug that makes all new files be rendered twice.
329 if (! grep { $_ eq $bestlink } values %renderedfiles) {
330 $bestlink=htmlpage($bestlink);
332 if (! grep { $_ eq $bestlink } values %renderedfiles) {
333 return "<span><a href=\"".
334 cgiurl(do => "create", page => $link, from => $page).
335 "\">?</a>$linktext</span>"
338 $bestlink=abs2rel($bestlink, dirname($page));
340 if (! $noimageinline && isinlinableimage($bestlink)) {
341 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
343 return "<a href=\"$bestlink\">$linktext</a>";
346 sub indexlink () { #{{{
347 return "<a href=\"$config{url}\">$config{wikiname}</a>";
350 sub lockwiki () { #{{{
351 # Take an exclusive lock on the wiki to prevent multiple concurrent
352 # run issues. The lock will be dropped on program exit.
353 if (! -d $config{wikistatedir}) {
354 mkdir($config{wikistatedir});
356 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
357 error ("cannot write to $config{wikistatedir}/lockfile: $!");
358 if (! flock(WIKILOCK, 2 | 4)) {
359 debug("wiki seems to be locked, waiting for lock");
360 my $wait=600; # arbitrary, but don't hang forever to
361 # prevent process pileup
363 return if flock(WIKILOCK, 2 | 4);
366 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
370 sub unlockwiki () { #{{{
374 sub loadindex () { #{{{
375 open (IN, "$config{wikistatedir}/index") || return;
377 $_=possibly_foolish_untaint($_);
381 foreach my $i (split(/ /, $_)) {
382 my ($item, $val)=split(/=/, $i, 2);
383 push @{$items{$item}}, $val;
386 next unless exists $items{src}; # skip bad lines for now
388 my $page=pagename($items{src}[0]);
389 if (! $config{rebuild}) {
390 $pagesources{$page}=$items{src}[0];
391 $oldpagemtime{$page}=$items{mtime}[0];
392 $oldlinks{$page}=[@{$items{link}}];
393 $links{$page}=[@{$items{link}}];
394 $depends{$page}=join(" ", @{$items{depends}})
395 if exists $items{depends};
396 $renderedfiles{$page}=$items{dest}[0];
398 $pagectime{$page}=$items{ctime}[0];
403 sub saveindex () { #{{{
404 run_hooks(savestate => sub { shift->() });
406 if (! -d $config{wikistatedir}) {
407 mkdir($config{wikistatedir});
409 open (OUT, ">$config{wikistatedir}/index") ||
410 error("cannot write to $config{wikistatedir}/index: $!");
411 foreach my $page (keys %oldpagemtime) {
412 next unless $oldpagemtime{$page};
413 my $line="mtime=$oldpagemtime{$page} ".
414 "ctime=$pagectime{$page} ".
415 "src=$pagesources{$page} ".
416 "dest=$renderedfiles{$page}";
417 $line.=" link=$_" foreach @{$links{$page}};
418 if (exists $depends{$page}) {
419 $line.=" depends=$_" foreach split " ", $depends{$page};
421 print OUT $line."\n";
426 sub template_params (@) { #{{{
429 require HTML::Template;
430 return filter => sub {
431 my $text_ref = shift;
432 $$text_ref=&Encode::decode_utf8($$text_ref);
434 filename => "$config{templatedir}/$filename", @_;
437 sub template ($;@) { #{{{
438 HTML::Template->new(template_params(@_));
441 sub misctemplate ($$) { #{{{
445 my $template=template("misc.tmpl");
448 indexlink => indexlink(),
449 wikiname => $config{wikiname},
450 pagebody => $pagebody,
451 styleurl => styleurl(),
452 baseurl => "$config{url}/",
454 return $template->output;
457 sub glob_match ($$) { #{{{
461 if ($glob =~ /^link\((.+)\)$/) {
462 my $rev = $links{$page} or return undef;
463 foreach my $p (@$rev) {
464 return 1 if lc $p eq $1;
467 } elsif ($glob =~ /^backlink\((.+)\)$/) {
468 my $rev = $links{$1} or return undef;
469 foreach my $p (@$rev) {
470 return 1 if lc $p eq $page;
474 # turn glob into safe regexp
475 $glob=quotemeta($glob);
480 return $page=~/^$glob$/i;
484 sub globlist_match ($$) { #{{{
486 my @globlist=split(" ", shift);
488 # check any negated globs first
489 foreach my $glob (@globlist) {
490 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
493 foreach my $glob (@globlist) {
494 return 1 if glob_match($page, $glob);
503 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
504 error "hook requires type, call, and id parameters";
507 $hooks{$param{type}}{$param{id}}=\%param;
510 sub run_hooks ($$) { # {{{
511 # Calls the given sub for each hook of the given type,
512 # passing it the hook function to call.
516 if (exists $hooks{$type}) {
517 foreach my $id (keys %{$hooks{$type}}) {
518 $sub->($hooks{$type}{$id}{call});