7 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
14 %renderedfiles %pagesources %depends %hooks};
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 if (! -d $config{wikistatedir}) {
399 mkdir($config{wikistatedir});
401 open (OUT, ">$config{wikistatedir}/index") ||
402 error("cannot write to $config{wikistatedir}/index: $!");
403 foreach my $page (keys %oldpagemtime) {
404 next unless $oldpagemtime{$page};
405 my $line="mtime=$oldpagemtime{$page} ".
406 "ctime=$pagectime{$page} ".
407 "src=$pagesources{$page} ".
408 "dest=$renderedfiles{$page}";
409 $line.=" link=$_" foreach @{$links{$page}};
410 if (exists $depends{$page}) {
411 $line.=" depends=$_" foreach split " ", $depends{$page};
413 print OUT $line."\n";
418 sub template_params (@) { #{{{
421 require HTML::Template;
422 return filter => sub {
423 my $text_ref = shift;
424 $$text_ref=&Encode::decode_utf8($$text_ref);
426 filename => "$config{templatedir}/$filename", @_;
429 sub template ($;@) { #{{{
430 HTML::Template->new(template_params(@_));
433 sub misctemplate ($$) { #{{{
437 my $template=template("misc.tmpl");
440 indexlink => indexlink(),
441 wikiname => $config{wikiname},
442 pagebody => $pagebody,
443 styleurl => styleurl(),
444 baseurl => "$config{url}/",
446 return $template->output;
449 sub glob_match ($$) { #{{{
453 if ($glob =~ /^link\((.+)\)$/) {
454 my $rev = $links{$page} or return undef;
455 foreach my $p (@$rev) {
456 return 1 if lc $p eq $1;
459 } elsif ($glob =~ /^backlink\((.+)\)$/) {
460 my $rev = $links{$1} or return undef;
461 foreach my $p (@$rev) {
462 return 1 if lc $p eq $page;
466 # turn glob into safe regexp
467 $glob=quotemeta($glob);
472 return $page=~/^$glob$/i;
476 sub globlist_match ($$) { #{{{
478 my @globlist=split(" ", shift);
480 # check any negated globs first
481 foreach my $glob (@globlist) {
482 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
485 foreach my $glob (@globlist) {
486 return 1 if glob_match($page, $glob);
495 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
496 error "hook requires type, call, and id parameters";
499 $hooks{$param{type}}{$param{id}}=\%param;
502 sub run_hooks ($$) { # {{{
503 # Calls the given sub for each hook of the given type,
504 # passing it the hook function to call.
508 if (exists $hooks{$type}) {
509 foreach my $id (keys %{$hooks{$type}}) {
510 $sub->($hooks{$type}{$id}{call});