8 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
15 %renderedfiles %pagesources %depends %hooks %forcerebuild};
17 sub defaultconfig () { #{{{
18 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$|\.rss$)},
19 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
20 wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]*)\]\]/,
21 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
24 default_pageext => "mdwn",
46 templatedir => "/usr/share/ikiwiki/templates",
47 underlaydir => "/usr/share/ikiwiki/basewiki",
51 plugin => [qw{mdwn inline htmlscrubber}],
56 sub checkconfig () { #{{{
57 # locale stuff; avoid LC_ALL since it overrides everything
58 if (defined $ENV{LC_ALL}) {
59 $ENV{LANG} = $ENV{LC_ALL};
62 if (defined $config{locale}) {
64 $ENV{LANG} = $config{locale}
65 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
68 if ($config{w3mmode}) {
69 eval q{use Cwd q{abs_path}};
70 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
71 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
72 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
73 unless $config{cgiurl} =~ m!file:///!;
74 $config{url}="file://".$config{destdir};
77 if ($config{cgi} && ! length $config{url}) {
78 error("Must specify url to wiki with --url when using --cgi\n");
80 if ($config{rss} && ! length $config{url}) {
81 error("Must specify url to wiki with --url when using --rss\n");
84 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
85 unless exists $config{wikistatedir};
88 eval qq{require IkiWiki::Rcs::$config{rcs}};
90 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
94 require IkiWiki::Rcs::Stub;
97 run_hooks(checkconfig => sub { shift->() });
100 sub loadplugins () { #{{{
101 foreach my $plugin (@{$config{plugin}}) {
102 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
105 error("Failed to load plugin $mod: $@");
108 run_hooks(getopt => sub { shift->() });
109 if (grep /^-/, @ARGV) {
110 print STDERR "Unknown option: $_\n"
111 foreach grep /^-/, @ARGV;
118 print "Content-type: text/html\n\n";
119 print misctemplate("Error", "<p>Error: @_</p>");
125 return unless $config{verbose};
126 if (! $config{cgi}) {
134 sub possibly_foolish_untaint ($) { #{{{
136 my ($untainted)=$tainted=~/(.*)/;
140 sub basename ($) { #{{{
147 sub dirname ($) { #{{{
154 sub pagetype ($) { #{{{
157 if ($page =~ /\.([^.]+)$/) {
158 return $1 if exists $hooks{htmlize}{$1};
163 sub pagename ($) { #{{{
166 my $type=pagetype($file);
168 $page=~s/\Q.$type\E*$// if defined $type;
172 sub htmlpage ($) { #{{{
175 return $page.".html";
178 sub srcfile ($) { #{{{
181 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
182 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
183 error("internal error: $file cannot be found");
186 sub readfile ($;$) { #{{{
191 error("cannot read a symlink ($file)");
195 open (IN, $file) || error("failed to read $file: $!");
196 binmode(IN) if ($binary);
202 sub writefile ($$$;$) { #{{{
203 my $file=shift; # can include subdirs
204 my $destdir=shift; # directory to put file in
209 while (length $test) {
210 if (-l "$destdir/$test") {
211 error("cannot write to a symlink ($test)");
213 $test=dirname($test);
216 my $dir=dirname("$destdir/$file");
219 foreach my $s (split(m!/+!, $dir)) {
222 mkdir($d) || error("failed to create directory $d: $!");
227 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
228 binmode(OUT) if ($binary);
233 sub bestlink ($$) { #{{{
234 # Given a page and the text of a link on the page, determine which
235 # existing page that link best points to. Prefers pages under a
236 # subdirectory with the same name as the source page, failing that
237 # goes down the directory tree to the base looking for matching
245 $l.="/" if length $l;
248 if (exists $links{$l}) {
249 #debug("for $page, \"$link\", use $l");
252 } while $cwd=~s!/?[^/]+$!!;
254 #print STDERR "warning: page $page, broken link: $link\n";
258 sub isinlinableimage ($) { #{{{
261 $file=~/\.(png|gif|jpg|jpeg)$/i;
264 sub pagetitle ($) { #{{{
266 $page=~s/__(\d+)__/&#$1;/g;
271 sub titlepage ($) { #{{{
274 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
278 sub cgiurl (@) { #{{{
281 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
284 sub styleurl (;$) { #{{{
287 return "$config{url}/style.css" if ! defined $page;
290 $page=~s/[^\/]+\//..\//g;
291 return $page."style.css";
294 sub abs2rel ($$) { #{{{
295 # Work around very innefficient behavior in File::Spec if abs2rel
296 # is passed two relative paths. It's much faster if paths are
302 my $ret=File::Spec->abs2rel($path, $base);
303 $ret=~s/^// if defined $ret;
307 sub htmllink ($$$;$$$) { #{{{
308 my $lpage=shift; # the page doing the linking
309 my $page=shift; # the page that will contain the link (different for inline)
311 my $noimageinline=shift; # don't turn links into inline html images
312 my $forcesubpage=shift; # force a link to a subpage
313 my $linktext=shift; # set to force the link text to something
316 if (! $forcesubpage) {
317 $bestlink=bestlink($lpage, $link);
320 $bestlink="$lpage/".lc($link);
323 $linktext=pagetitle(basename($link)) unless defined $linktext;
325 return $linktext if length $bestlink && $page eq $bestlink;
327 # TODO BUG: %renderedfiles may not have it, if the linked to page
328 # was also added and isn't yet rendered! Note that this bug is
329 # masked by the bug that makes all new files be rendered twice.
330 if (! grep { $_ eq $bestlink } values %renderedfiles) {
331 $bestlink=htmlpage($bestlink);
333 if (! grep { $_ eq $bestlink } values %renderedfiles) {
334 return "<span><a href=\"".
335 cgiurl(do => "create", page => $link, from => $page).
336 "\">?</a>$linktext</span>"
339 $bestlink=abs2rel($bestlink, dirname($page));
341 if (! $noimageinline && isinlinableimage($bestlink)) {
342 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
344 return "<a href=\"$bestlink\">$linktext</a>";
347 sub indexlink () { #{{{
348 return "<a href=\"$config{url}\">$config{wikiname}</a>";
351 sub lockwiki () { #{{{
352 # Take an exclusive lock on the wiki to prevent multiple concurrent
353 # run issues. The lock will be dropped on program exit.
354 if (! -d $config{wikistatedir}) {
355 mkdir($config{wikistatedir});
357 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
358 error ("cannot write to $config{wikistatedir}/lockfile: $!");
359 if (! flock(WIKILOCK, 2 | 4)) {
360 debug("wiki seems to be locked, waiting for lock");
361 my $wait=600; # arbitrary, but don't hang forever to
362 # prevent process pileup
364 return if flock(WIKILOCK, 2 | 4);
367 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
371 sub unlockwiki () { #{{{
375 sub loadindex () { #{{{
376 open (IN, "$config{wikistatedir}/index") || return;
378 $_=possibly_foolish_untaint($_);
382 foreach my $i (split(/ /, $_)) {
383 my ($item, $val)=split(/=/, $i, 2);
384 push @{$items{$item}}, decode_entities($val);
387 next unless exists $items{src}; # skip bad lines for now
389 my $page=pagename($items{src}[0]);
390 if (! $config{rebuild}) {
391 $pagesources{$page}=$items{src}[0];
392 $oldpagemtime{$page}=$items{mtime}[0];
393 $oldlinks{$page}=[@{$items{link}}];
394 $links{$page}=[@{$items{link}}];
395 $depends{$page}=$items{depends}[0] 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=".encode_entities($depends{$page}, " \t\n");
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;
460 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
461 error "hook requires type, call, and id parameters";
464 $hooks{$param{type}}{$param{id}}=\%param;
467 sub run_hooks ($$) { # {{{
468 # Calls the given sub for each hook of the given type,
469 # passing it the hook function to call.
473 if (exists $hooks{$type}) {
474 foreach my $id (keys %{$hooks{$type}}) {
475 $sub->($hooks{$type}{$id}{call});
480 sub globlist_to_pagespec ($) { #{{{
481 my @globlist=split(' ', shift);
484 foreach my $glob (@globlist) {
485 if ($glob=~/^!(.*)/) {
493 my $spec=join(" or ", @spec);
495 my $skip=join(" and ", @skip);
497 $spec="$skip and ($spec)";
506 sub is_globlist ($) { #{{{
508 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
511 sub safequote ($) { #{{{
517 sub pagespec_merge ($$) { #{{{
521 # Support for old-style GlobLists.
522 if (is_globlist($a)) {
523 $a=globlist_to_pagespec($a);
525 if (is_globlist($b)) {
526 $b=globlist_to_pagespec($b);
529 return "($a) or ($b)";
532 sub pagespec_match ($$) { #{{{
536 # Support for old-style GlobLists.
537 if (is_globlist($spec)) {
538 $spec=globlist_to_pagespec($spec);
541 # Convert spec to perl code.
543 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
545 if (lc $word eq "and") {
548 elsif (lc $word eq "or") {
551 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
554 elsif ($word =~ /^(link|backlink|creation_month|creation_year|creation_day)\((.+)\)$/) {
555 $code.=" match_$1(\$page, ".safequote($2).")";
558 $code.=" match_glob(\$page, ".safequote($word).")";
565 sub match_glob ($$) { #{{{
569 # turn glob into safe regexp
570 $glob=quotemeta($glob);
574 return $page=~/^$glob$/;
577 sub match_link ($$) { #{{{
581 my $links = $links{$page} or return undef;
582 foreach my $p (@$links) {
583 return 1 if lc $p eq $link;
588 sub match_backlink ($$) { #{{{
592 my $links = $links{$linkto} or return undef;
593 foreach my $p (@$links) {
594 return 1 if lc $p eq $page;
599 sub match_creation_day ($$) { #{{{
600 return if (localtime($pagectime{shift()}))[3] == shift;
603 sub match_creation_month ($$) { #{{{
604 return if (localtime($pagectime{shift()}))[4] + 1 == shift;
607 sub match_creation_year ($$) { #{{{
608 return if (localtime($pagectime{shift()}))[5] + 1900 == shift;