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}],
54 sub checkconfig () { #{{{
55 if ($config{w3mmode}) {
56 eval q{use Cwd q{abs_path}};
57 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
58 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
59 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
60 unless $config{cgiurl} =~ m!file:///!;
61 $config{url}="file://".$config{destdir};
64 if ($config{cgi} && ! length $config{url}) {
65 error("Must specify url to wiki with --url when using --cgi\n");
67 if ($config{rss} && ! length $config{url}) {
68 error("Must specify url to wiki with --url when using --rss\n");
71 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
72 unless exists $config{wikistatedir};
75 eval qq{require IkiWiki::Rcs::$config{rcs}};
77 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
81 require IkiWiki::Rcs::Stub;
84 foreach my $plugin (@{$config{plugin}}) {
85 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
88 error("Failed to load plugin $mod: $@");
92 if (exists $hooks{checkconfig}) {
93 foreach my $id (keys %{$hooks{checkconfig}}) {
94 $hooks{checkconfig}{$id}{call}->();
101 print "Content-type: text/html\n\n";
102 print misctemplate("Error", "<p>Error: @_</p>");
108 return unless $config{verbose};
109 if (! $config{cgi}) {
117 sub possibly_foolish_untaint ($) { #{{{
119 my ($untainted)=$tainted=~/(.*)/;
123 sub basename ($) { #{{{
130 sub dirname ($) { #{{{
137 sub pagetype ($) { #{{{
140 if ($page =~ /\.([^.]+)$/) {
141 return $1 if exists $hooks{htmlize}{$1};
146 sub pagename ($) { #{{{
149 my $type=pagetype($file);
151 $page=~s/\Q.$type\E*$// if defined $type;
155 sub htmlpage ($) { #{{{
158 return $page.".html";
161 sub srcfile ($) { #{{{
164 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
165 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
166 error("internal error: $file cannot be found");
169 sub readfile ($;$) { #{{{
174 error("cannot read a symlink ($file)");
178 open (IN, $file) || error("failed to read $file: $!");
179 binmode(IN) if ($binary);
185 sub writefile ($$$;$) { #{{{
186 my $file=shift; # can include subdirs
187 my $destdir=shift; # directory to put file in
192 while (length $test) {
193 if (-l "$destdir/$test") {
194 error("cannot write to a symlink ($test)");
196 $test=dirname($test);
199 my $dir=dirname("$destdir/$file");
202 foreach my $s (split(m!/+!, $dir)) {
205 mkdir($d) || error("failed to create directory $d: $!");
210 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
211 binmode(OUT) if ($binary);
216 sub bestlink ($$) { #{{{
217 # Given a page and the text of a link on the page, determine which
218 # existing page that link best points to. Prefers pages under a
219 # subdirectory with the same name as the source page, failing that
220 # goes down the directory tree to the base looking for matching
228 $l.="/" if length $l;
231 if (exists $links{$l}) {
232 #debug("for $page, \"$link\", use $l");
235 } while $cwd=~s!/?[^/]+$!!;
237 #print STDERR "warning: page $page, broken link: $link\n";
241 sub isinlinableimage ($) { #{{{
244 $file=~/\.(png|gif|jpg|jpeg)$/i;
247 sub pagetitle ($) { #{{{
249 $page=~s/__(\d+)__/&#$1;/g;
254 sub titlepage ($) { #{{{
257 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
261 sub cgiurl (@) { #{{{
264 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
267 sub styleurl (;$) { #{{{
270 return "$config{url}/style.css" if ! defined $page;
273 $page=~s/[^\/]+\//..\//g;
274 return $page."style.css";
278 # Work around very innefficient behavior in File::Spec if abs2rel
279 # is passed two relative paths. It's much faster if paths are
285 my $ret=File::Spec->abs2rel($path, $base);
286 $ret=~s/^// if defined $ret;
290 sub htmllink ($$$;$$$) { #{{{
291 my $lpage=shift; # the page doing the linking
292 my $page=shift; # the page that will contain the link (different for inline)
294 my $noimageinline=shift; # don't turn links into inline html images
295 my $forcesubpage=shift; # force a link to a subpage
296 my $linktext=shift; # set to force the link text to something
299 if (! $forcesubpage) {
300 $bestlink=bestlink($lpage, $link);
303 $bestlink="$lpage/".lc($link);
306 $linktext=pagetitle(basename($link)) unless defined $linktext;
308 return $linktext if length $bestlink && $page eq $bestlink;
310 # TODO BUG: %renderedfiles may not have it, if the linked to page
311 # was also added and isn't yet rendered! Note that this bug is
312 # masked by the bug that makes all new files be rendered twice.
313 if (! grep { $_ eq $bestlink } values %renderedfiles) {
314 $bestlink=htmlpage($bestlink);
316 if (! grep { $_ eq $bestlink } values %renderedfiles) {
317 return "<span><a href=\"".
318 cgiurl(do => "create", page => $link, from => $page).
319 "\">?</a>$linktext</span>"
322 $bestlink=abs2rel($bestlink, dirname($page));
324 if (! $noimageinline && isinlinableimage($bestlink)) {
325 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
327 return "<a href=\"$bestlink\">$linktext</a>";
330 sub indexlink () { #{{{
331 return "<a href=\"$config{url}\">$config{wikiname}</a>";
334 sub lockwiki () { #{{{
335 # Take an exclusive lock on the wiki to prevent multiple concurrent
336 # run issues. The lock will be dropped on program exit.
337 if (! -d $config{wikistatedir}) {
338 mkdir($config{wikistatedir});
340 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
341 error ("cannot write to $config{wikistatedir}/lockfile: $!");
342 if (! flock(WIKILOCK, 2 | 4)) {
343 debug("wiki seems to be locked, waiting for lock");
344 my $wait=600; # arbitrary, but don't hang forever to
345 # prevent process pileup
347 return if flock(WIKILOCK, 2 | 4);
350 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
354 sub unlockwiki () { #{{{
358 sub loadindex () { #{{{
359 open (IN, "$config{wikistatedir}/index") || return;
361 $_=possibly_foolish_untaint($_);
365 foreach my $i (split(/ /, $_)) {
366 my ($item, $val)=split(/=/, $i, 2);
367 push @{$items{$item}}, $val;
370 next unless exists $items{src}; # skip bad lines for now
372 my $page=pagename($items{src}[0]);
373 if (! $config{rebuild}) {
374 $pagesources{$page}=$items{src}[0];
375 $oldpagemtime{$page}=$items{mtime}[0];
376 $oldlinks{$page}=[@{$items{link}}];
377 $links{$page}=[@{$items{link}}];
378 $depends{$page}=join(" ", @{$items{depends}})
379 if exists $items{depends};
380 $renderedfiles{$page}=$items{dest}[0];
382 $pagectime{$page}=$items{ctime}[0];
387 sub saveindex () { #{{{
388 if (! -d $config{wikistatedir}) {
389 mkdir($config{wikistatedir});
391 open (OUT, ">$config{wikistatedir}/index") ||
392 error("cannot write to $config{wikistatedir}/index: $!");
393 foreach my $page (keys %oldpagemtime) {
394 next unless $oldpagemtime{$page};
395 my $line="mtime=$oldpagemtime{$page} ".
396 "ctime=$pagectime{$page} ".
397 "src=$pagesources{$page} ".
398 "dest=$renderedfiles{$page}";
399 $line.=" link=$_" foreach @{$links{$page}};
400 if (exists $depends{$page}) {
401 $line.=" depends=$_" foreach split " ", $depends{$page};
403 print OUT $line."\n";
408 sub template_params (@) { #{{{
411 require HTML::Template;
412 return filter => sub {
413 my $text_ref = shift;
414 $$text_ref=&Encode::decode_utf8($$text_ref);
416 filename => "$config{templatedir}/$filename", @_;
419 sub template ($;@) { #{{{
420 HTML::Template->new(template_params(@_));
423 sub misctemplate ($$) { #{{{
427 my $template=template("misc.tmpl");
430 indexlink => indexlink(),
431 wikiname => $config{wikiname},
432 pagebody => $pagebody,
433 styleurl => styleurl(),
434 baseurl => "$config{url}/",
436 return $template->output;
439 sub glob_match ($$) { #{{{
443 if ($glob =~ /^link\((.+)\)$/) {
444 my $rev = $links{$page} or return undef;
445 foreach my $p (@$rev) {
446 return 1 if lc $p eq $1;
449 } elsif ($glob =~ /^backlink\((.+)\)$/) {
450 my $rev = $links{$1} or return undef;
451 foreach my $p (@$rev) {
452 return 1 if lc $p eq $page;
456 # turn glob into safe regexp
457 $glob=quotemeta($glob);
462 return $page=~/^$glob$/i;
466 sub globlist_match ($$) { #{{{
468 my @globlist=split(" ", shift);
470 # check any negated globs first
471 foreach my $glob (@globlist) {
472 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
475 foreach my $glob (@globlist) {
476 return 1 if glob_match($page, $glob);
485 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
486 error "hook requires type, call, and id parameters";
489 $hooks{$param{type}}{$param{id}}=\%param;