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 if (exists $hooks{checkconfig}) {
85 foreach my $id (keys %{$hooks{checkconfig}}) {
86 $hooks{checkconfig}{$id}{call}->();
91 sub loadplugins () { #{{{
92 foreach my $plugin (@{$config{plugin}}) {
93 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
96 error("Failed to load plugin $mod: $@");
103 print "Content-type: text/html\n\n";
104 print misctemplate("Error", "<p>Error: @_</p>");
110 return unless $config{verbose};
111 if (! $config{cgi}) {
119 sub possibly_foolish_untaint ($) { #{{{
121 my ($untainted)=$tainted=~/(.*)/;
125 sub basename ($) { #{{{
132 sub dirname ($) { #{{{
139 sub pagetype ($) { #{{{
142 if ($page =~ /\.([^.]+)$/) {
143 return $1 if exists $hooks{htmlize}{$1};
148 sub pagename ($) { #{{{
151 my $type=pagetype($file);
153 $page=~s/\Q.$type\E*$// if defined $type;
157 sub htmlpage ($) { #{{{
160 return $page.".html";
163 sub srcfile ($) { #{{{
166 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
167 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
168 error("internal error: $file cannot be found");
171 sub readfile ($;$) { #{{{
176 error("cannot read a symlink ($file)");
180 open (IN, $file) || error("failed to read $file: $!");
181 binmode(IN) if ($binary);
187 sub writefile ($$$;$) { #{{{
188 my $file=shift; # can include subdirs
189 my $destdir=shift; # directory to put file in
194 while (length $test) {
195 if (-l "$destdir/$test") {
196 error("cannot write to a symlink ($test)");
198 $test=dirname($test);
201 my $dir=dirname("$destdir/$file");
204 foreach my $s (split(m!/+!, $dir)) {
207 mkdir($d) || error("failed to create directory $d: $!");
212 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
213 binmode(OUT) if ($binary);
218 sub bestlink ($$) { #{{{
219 # Given a page and the text of a link on the page, determine which
220 # existing page that link best points to. Prefers pages under a
221 # subdirectory with the same name as the source page, failing that
222 # goes down the directory tree to the base looking for matching
230 $l.="/" if length $l;
233 if (exists $links{$l}) {
234 #debug("for $page, \"$link\", use $l");
237 } while $cwd=~s!/?[^/]+$!!;
239 #print STDERR "warning: page $page, broken link: $link\n";
243 sub isinlinableimage ($) { #{{{
246 $file=~/\.(png|gif|jpg|jpeg)$/i;
249 sub pagetitle ($) { #{{{
251 $page=~s/__(\d+)__/&#$1;/g;
256 sub titlepage ($) { #{{{
259 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
263 sub cgiurl (@) { #{{{
266 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
269 sub styleurl (;$) { #{{{
272 return "$config{url}/style.css" if ! defined $page;
275 $page=~s/[^\/]+\//..\//g;
276 return $page."style.css";
280 # Work around very innefficient behavior in File::Spec if abs2rel
281 # is passed two relative paths. It's much faster if paths are
287 my $ret=File::Spec->abs2rel($path, $base);
288 $ret=~s/^// if defined $ret;
292 sub htmllink ($$$;$$$) { #{{{
293 my $lpage=shift; # the page doing the linking
294 my $page=shift; # the page that will contain the link (different for inline)
296 my $noimageinline=shift; # don't turn links into inline html images
297 my $forcesubpage=shift; # force a link to a subpage
298 my $linktext=shift; # set to force the link text to something
301 if (! $forcesubpage) {
302 $bestlink=bestlink($lpage, $link);
305 $bestlink="$lpage/".lc($link);
308 $linktext=pagetitle(basename($link)) unless defined $linktext;
310 return $linktext if length $bestlink && $page eq $bestlink;
312 # TODO BUG: %renderedfiles may not have it, if the linked to page
313 # was also added and isn't yet rendered! Note that this bug is
314 # masked by the bug that makes all new files be rendered twice.
315 if (! grep { $_ eq $bestlink } values %renderedfiles) {
316 $bestlink=htmlpage($bestlink);
318 if (! grep { $_ eq $bestlink } values %renderedfiles) {
319 return "<span><a href=\"".
320 cgiurl(do => "create", page => $link, from => $page).
321 "\">?</a>$linktext</span>"
324 $bestlink=abs2rel($bestlink, dirname($page));
326 if (! $noimageinline && isinlinableimage($bestlink)) {
327 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
329 return "<a href=\"$bestlink\">$linktext</a>";
332 sub indexlink () { #{{{
333 return "<a href=\"$config{url}\">$config{wikiname}</a>";
336 sub lockwiki () { #{{{
337 # Take an exclusive lock on the wiki to prevent multiple concurrent
338 # run issues. The lock will be dropped on program exit.
339 if (! -d $config{wikistatedir}) {
340 mkdir($config{wikistatedir});
342 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
343 error ("cannot write to $config{wikistatedir}/lockfile: $!");
344 if (! flock(WIKILOCK, 2 | 4)) {
345 debug("wiki seems to be locked, waiting for lock");
346 my $wait=600; # arbitrary, but don't hang forever to
347 # prevent process pileup
349 return if flock(WIKILOCK, 2 | 4);
352 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
356 sub unlockwiki () { #{{{
360 sub loadindex () { #{{{
361 open (IN, "$config{wikistatedir}/index") || return;
363 $_=possibly_foolish_untaint($_);
367 foreach my $i (split(/ /, $_)) {
368 my ($item, $val)=split(/=/, $i, 2);
369 push @{$items{$item}}, $val;
372 next unless exists $items{src}; # skip bad lines for now
374 my $page=pagename($items{src}[0]);
375 if (! $config{rebuild}) {
376 $pagesources{$page}=$items{src}[0];
377 $oldpagemtime{$page}=$items{mtime}[0];
378 $oldlinks{$page}=[@{$items{link}}];
379 $links{$page}=[@{$items{link}}];
380 $depends{$page}=join(" ", @{$items{depends}})
381 if exists $items{depends};
382 $renderedfiles{$page}=$items{dest}[0];
384 $pagectime{$page}=$items{ctime}[0];
389 sub saveindex () { #{{{
390 if (! -d $config{wikistatedir}) {
391 mkdir($config{wikistatedir});
393 open (OUT, ">$config{wikistatedir}/index") ||
394 error("cannot write to $config{wikistatedir}/index: $!");
395 foreach my $page (keys %oldpagemtime) {
396 next unless $oldpagemtime{$page};
397 my $line="mtime=$oldpagemtime{$page} ".
398 "ctime=$pagectime{$page} ".
399 "src=$pagesources{$page} ".
400 "dest=$renderedfiles{$page}";
401 $line.=" link=$_" foreach @{$links{$page}};
402 if (exists $depends{$page}) {
403 $line.=" depends=$_" foreach split " ", $depends{$page};
405 print OUT $line."\n";
410 sub template_params (@) { #{{{
413 require HTML::Template;
414 return filter => sub {
415 my $text_ref = shift;
416 $$text_ref=&Encode::decode_utf8($$text_ref);
418 filename => "$config{templatedir}/$filename", @_;
421 sub template ($;@) { #{{{
422 HTML::Template->new(template_params(@_));
425 sub misctemplate ($$) { #{{{
429 my $template=template("misc.tmpl");
432 indexlink => indexlink(),
433 wikiname => $config{wikiname},
434 pagebody => $pagebody,
435 styleurl => styleurl(),
436 baseurl => "$config{url}/",
438 return $template->output;
441 sub glob_match ($$) { #{{{
445 if ($glob =~ /^link\((.+)\)$/) {
446 my $rev = $links{$page} or return undef;
447 foreach my $p (@$rev) {
448 return 1 if lc $p eq $1;
451 } elsif ($glob =~ /^backlink\((.+)\)$/) {
452 my $rev = $links{$1} or return undef;
453 foreach my $p (@$rev) {
454 return 1 if lc $p eq $page;
458 # turn glob into safe regexp
459 $glob=quotemeta($glob);
464 return $page=~/^$glob$/i;
468 sub globlist_match ($$) { #{{{
470 my @globlist=split(" ", shift);
472 # check any negated globs first
473 foreach my $glob (@globlist) {
474 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
477 foreach my $glob (@globlist) {
478 return 1 if glob_match($page, $glob);
487 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
488 error "hook requires type, call, and id parameters";
491 $hooks{$param{type}}{$param{id}}=\%param;