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: $@");
111 print "Content-type: text/html\n\n";
112 print misctemplate("Error", "<p>Error: @_</p>");
118 return unless $config{verbose};
119 if (! $config{cgi}) {
127 sub possibly_foolish_untaint ($) { #{{{
129 my ($untainted)=$tainted=~/(.*)/;
133 sub basename ($) { #{{{
140 sub dirname ($) { #{{{
147 sub pagetype ($) { #{{{
150 if ($page =~ /\.([^.]+)$/) {
151 return $1 if exists $hooks{htmlize}{$1};
156 sub pagename ($) { #{{{
159 my $type=pagetype($file);
161 $page=~s/\Q.$type\E*$// if defined $type;
165 sub htmlpage ($) { #{{{
168 return $page.".html";
171 sub srcfile ($) { #{{{
174 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
175 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
176 error("internal error: $file cannot be found");
179 sub readfile ($;$) { #{{{
184 error("cannot read a symlink ($file)");
188 open (IN, $file) || error("failed to read $file: $!");
189 binmode(IN) if ($binary);
195 sub writefile ($$$;$) { #{{{
196 my $file=shift; # can include subdirs
197 my $destdir=shift; # directory to put file in
202 while (length $test) {
203 if (-l "$destdir/$test") {
204 error("cannot write to a symlink ($test)");
206 $test=dirname($test);
209 my $dir=dirname("$destdir/$file");
212 foreach my $s (split(m!/+!, $dir)) {
215 mkdir($d) || error("failed to create directory $d: $!");
220 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
221 binmode(OUT) if ($binary);
226 sub bestlink ($$) { #{{{
227 # Given a page and the text of a link on the page, determine which
228 # existing page that link best points to. Prefers pages under a
229 # subdirectory with the same name as the source page, failing that
230 # goes down the directory tree to the base looking for matching
238 $l.="/" if length $l;
241 if (exists $links{$l}) {
242 #debug("for $page, \"$link\", use $l");
245 } while $cwd=~s!/?[^/]+$!!;
247 #print STDERR "warning: page $page, broken link: $link\n";
251 sub isinlinableimage ($) { #{{{
254 $file=~/\.(png|gif|jpg|jpeg)$/i;
257 sub pagetitle ($) { #{{{
259 $page=~s/__(\d+)__/&#$1;/g;
264 sub titlepage ($) { #{{{
267 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
271 sub cgiurl (@) { #{{{
274 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
277 sub styleurl (;$) { #{{{
280 return "$config{url}/style.css" if ! defined $page;
283 $page=~s/[^\/]+\//..\//g;
284 return $page."style.css";
288 # Work around very innefficient behavior in File::Spec if abs2rel
289 # is passed two relative paths. It's much faster if paths are
295 my $ret=File::Spec->abs2rel($path, $base);
296 $ret=~s/^// if defined $ret;
300 sub htmllink ($$$;$$$) { #{{{
301 my $lpage=shift; # the page doing the linking
302 my $page=shift; # the page that will contain the link (different for inline)
304 my $noimageinline=shift; # don't turn links into inline html images
305 my $forcesubpage=shift; # force a link to a subpage
306 my $linktext=shift; # set to force the link text to something
309 if (! $forcesubpage) {
310 $bestlink=bestlink($lpage, $link);
313 $bestlink="$lpage/".lc($link);
316 $linktext=pagetitle(basename($link)) unless defined $linktext;
318 return $linktext if length $bestlink && $page eq $bestlink;
320 # TODO BUG: %renderedfiles may not have it, if the linked to page
321 # was also added and isn't yet rendered! Note that this bug is
322 # masked by the bug that makes all new files be rendered twice.
323 if (! grep { $_ eq $bestlink } values %renderedfiles) {
324 $bestlink=htmlpage($bestlink);
326 if (! grep { $_ eq $bestlink } values %renderedfiles) {
327 return "<span><a href=\"".
328 cgiurl(do => "create", page => $link, from => $page).
329 "\">?</a>$linktext</span>"
332 $bestlink=abs2rel($bestlink, dirname($page));
334 if (! $noimageinline && isinlinableimage($bestlink)) {
335 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
337 return "<a href=\"$bestlink\">$linktext</a>";
340 sub indexlink () { #{{{
341 return "<a href=\"$config{url}\">$config{wikiname}</a>";
344 sub lockwiki () { #{{{
345 # Take an exclusive lock on the wiki to prevent multiple concurrent
346 # run issues. The lock will be dropped on program exit.
347 if (! -d $config{wikistatedir}) {
348 mkdir($config{wikistatedir});
350 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
351 error ("cannot write to $config{wikistatedir}/lockfile: $!");
352 if (! flock(WIKILOCK, 2 | 4)) {
353 debug("wiki seems to be locked, waiting for lock");
354 my $wait=600; # arbitrary, but don't hang forever to
355 # prevent process pileup
357 return if flock(WIKILOCK, 2 | 4);
360 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
364 sub unlockwiki () { #{{{
368 sub loadindex () { #{{{
369 open (IN, "$config{wikistatedir}/index") || return;
371 $_=possibly_foolish_untaint($_);
375 foreach my $i (split(/ /, $_)) {
376 my ($item, $val)=split(/=/, $i, 2);
377 push @{$items{$item}}, $val;
380 next unless exists $items{src}; # skip bad lines for now
382 my $page=pagename($items{src}[0]);
383 if (! $config{rebuild}) {
384 $pagesources{$page}=$items{src}[0];
385 $oldpagemtime{$page}=$items{mtime}[0];
386 $oldlinks{$page}=[@{$items{link}}];
387 $links{$page}=[@{$items{link}}];
388 $depends{$page}=join(" ", @{$items{depends}})
389 if exists $items{depends};
390 $renderedfiles{$page}=$items{dest}[0];
392 $pagectime{$page}=$items{ctime}[0];
397 sub saveindex () { #{{{
398 run_hooks(savestate => sub { shift->() });
400 if (! -d $config{wikistatedir}) {
401 mkdir($config{wikistatedir});
403 open (OUT, ">$config{wikistatedir}/index") ||
404 error("cannot write to $config{wikistatedir}/index: $!");
405 foreach my $page (keys %oldpagemtime) {
406 next unless $oldpagemtime{$page};
407 my $line="mtime=$oldpagemtime{$page} ".
408 "ctime=$pagectime{$page} ".
409 "src=$pagesources{$page} ".
410 "dest=$renderedfiles{$page}";
411 $line.=" link=$_" foreach @{$links{$page}};
412 if (exists $depends{$page}) {
413 $line.=" depends=$_" foreach split " ", $depends{$page};
415 print OUT $line."\n";
420 sub template_params (@) { #{{{
423 require HTML::Template;
424 return filter => sub {
425 my $text_ref = shift;
426 $$text_ref=&Encode::decode_utf8($$text_ref);
428 filename => "$config{templatedir}/$filename", @_;
431 sub template ($;@) { #{{{
432 HTML::Template->new(template_params(@_));
435 sub misctemplate ($$) { #{{{
439 my $template=template("misc.tmpl");
442 indexlink => indexlink(),
443 wikiname => $config{wikiname},
444 pagebody => $pagebody,
445 styleurl => styleurl(),
446 baseurl => "$config{url}/",
448 return $template->output;
451 sub glob_match ($$) { #{{{
455 if ($glob =~ /^link\((.+)\)$/) {
456 my $rev = $links{$page} or return undef;
457 foreach my $p (@$rev) {
458 return 1 if lc $p eq $1;
461 } elsif ($glob =~ /^backlink\((.+)\)$/) {
462 my $rev = $links{$1} or return undef;
463 foreach my $p (@$rev) {
464 return 1 if lc $p eq $page;
468 # turn glob into safe regexp
469 $glob=quotemeta($glob);
474 return $page=~/^$glob$/i;
478 sub globlist_match ($$) { #{{{
480 my @globlist=split(" ", shift);
482 # check any negated globs first
483 foreach my $glob (@globlist) {
484 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
487 foreach my $glob (@globlist) {
488 return 1 if glob_match($page, $glob);
497 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
498 error "hook requires type, call, and id parameters";
501 $hooks{$param{type}}{$param{id}}=\%param;
504 sub run_hooks ($$) { # {{{
505 # Calls the given sub for each hook of the given type,
506 # passing it the hook function to call.
510 if (exists $hooks{$type}) {
511 foreach my $id (keys %{$hooks{$type}}) {
512 $sub->($hooks{$type}{$id}{call});