8 use open qw{:utf8 :std};
13 memoize("pagespec_translate");
15 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
16 %renderedfiles %pagesources %depends %hooks %forcerebuild};
18 sub defaultconfig () { #{{{
19 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$)},
20 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
21 wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]*)\]\]/,
22 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
26 default_pageext => "mdwn",
48 templatedir => "/usr/share/ikiwiki/templates",
49 underlaydir => "/usr/share/ikiwiki/basewiki",
53 plugin => [qw{mdwn inline htmlscrubber}],
58 sub checkconfig () { #{{{
59 # locale stuff; avoid LC_ALL since it overrides everything
60 if (defined $ENV{LC_ALL}) {
61 $ENV{LANG} = $ENV{LC_ALL};
64 if (defined $config{locale}) {
66 $ENV{LANG} = $config{locale}
67 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
70 if ($config{w3mmode}) {
71 eval q{use Cwd q{abs_path}};
72 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
73 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
74 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
75 unless $config{cgiurl} =~ m!file:///!;
76 $config{url}="file://".$config{destdir};
79 if ($config{cgi} && ! length $config{url}) {
80 error("Must specify url to wiki with --url when using --cgi\n");
82 if ($config{rss} && ! length $config{url}) {
83 error("Must specify url to wiki with --url when using --rss\n");
86 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
87 unless exists $config{wikistatedir};
90 eval qq{require IkiWiki::Rcs::$config{rcs}};
92 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
96 require IkiWiki::Rcs::Stub;
99 run_hooks(checkconfig => sub { shift->() });
102 sub loadplugins () { #{{{
103 foreach my $plugin (@{$config{plugin}}) {
104 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
107 error("Failed to load plugin $mod: $@");
110 run_hooks(getopt => sub { shift->() });
111 if (grep /^-/, @ARGV) {
112 print STDERR "Unknown option: $_\n"
113 foreach grep /^-/, @ARGV;
120 print "Content-type: text/html\n\n";
121 print misctemplate("Error", "<p>Error: @_</p>");
123 log_message(error => @_);
128 return unless $config{verbose};
129 log_message(debug => @_);
133 sub log_message ($$) { #{{{
136 if ($config{syslog}) {
139 Sys::Syslog::setlogsock('unix');
140 Sys::Syslog::openlog('ikiwiki', '', 'user');
144 Sys::Syslog::syslog($type, join(" ", @_));
147 elsif (! $config{cgi}) {
155 sub possibly_foolish_untaint ($) { #{{{
157 my ($untainted)=$tainted=~/(.*)/;
161 sub basename ($) { #{{{
168 sub dirname ($) { #{{{
175 sub pagetype ($) { #{{{
178 if ($page =~ /\.([^.]+)$/) {
179 return $1 if exists $hooks{htmlize}{$1};
184 sub pagename ($) { #{{{
187 my $type=pagetype($file);
189 $page=~s/\Q.$type\E*$// if defined $type;
193 sub htmlpage ($) { #{{{
196 return $page.".html";
199 sub srcfile ($) { #{{{
202 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
203 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
204 error("internal error: $file cannot be found");
207 sub readfile ($;$) { #{{{
212 error("cannot read a symlink ($file)");
216 open (IN, $file) || error("failed to read $file: $!");
217 binmode(IN) if ($binary);
223 sub writefile ($$$;$) { #{{{
224 my $file=shift; # can include subdirs
225 my $destdir=shift; # directory to put file in
230 while (length $test) {
231 if (-l "$destdir/$test") {
232 error("cannot write to a symlink ($test)");
234 $test=dirname($test);
237 my $dir=dirname("$destdir/$file");
240 foreach my $s (split(m!/+!, $dir)) {
243 mkdir($d) || error("failed to create directory $d: $!");
248 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
249 binmode(OUT) if ($binary);
254 sub bestlink ($$) { #{{{
255 # Given a page and the text of a link on the page, determine which
256 # existing page that link best points to. Prefers pages under a
257 # subdirectory with the same name as the source page, failing that
258 # goes down the directory tree to the base looking for matching
266 $l.="/" if length $l;
269 if (exists $links{$l}) {
272 elsif (exists $pagecase{lc $l}) {
273 return $pagecase{lc $l};
275 } while $cwd=~s!/?[^/]+$!!;
277 #print STDERR "warning: page $page, broken link: $link\n";
281 sub isinlinableimage ($) { #{{{
284 $file=~/\.(png|gif|jpg|jpeg)$/i;
287 sub pagetitle ($) { #{{{
289 $page=~s/__(\d+)__/&#$1;/g;
294 sub titlepage ($) { #{{{
297 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
301 sub cgiurl (@) { #{{{
304 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
307 sub baseurl (;$) { #{{{
310 return "$config{url}/" if ! defined $page;
313 $page=~s/[^\/]+\//..\//g;
317 sub abs2rel ($$) { #{{{
318 # Work around very innefficient behavior in File::Spec if abs2rel
319 # is passed two relative paths. It's much faster if paths are
325 my $ret=File::Spec->abs2rel($path, $base);
326 $ret=~s/^// if defined $ret;
330 sub htmllink ($$$;$$$) { #{{{
331 my $lpage=shift; # the page doing the linking
332 my $page=shift; # the page that will contain the link (different for inline)
334 my $noimageinline=shift; # don't turn links into inline html images
335 my $forcesubpage=shift; # force a link to a subpage
336 my $linktext=shift; # set to force the link text to something
339 if (! $forcesubpage) {
340 $bestlink=bestlink($lpage, $link);
343 $bestlink="$lpage/".lc($link);
346 $linktext=pagetitle(basename($link)) unless defined $linktext;
348 return "<span class=\"selflink\">$linktext</span>"
349 if length $bestlink && $page eq $bestlink;
351 # TODO BUG: %renderedfiles may not have it, if the linked to page
352 # was also added and isn't yet rendered! Note that this bug is
353 # masked by the bug that makes all new files be rendered twice.
354 if (! grep { $_ eq $bestlink } values %renderedfiles) {
355 $bestlink=htmlpage($bestlink);
357 if (! grep { $_ eq $bestlink } values %renderedfiles) {
358 return "<span><a href=\"".
359 cgiurl(do => "create", page => lc($link), from => $page).
360 "\">?</a>$linktext</span>"
363 $bestlink=abs2rel($bestlink, dirname($page));
365 if (! $noimageinline && isinlinableimage($bestlink)) {
366 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
368 return "<a href=\"$bestlink\">$linktext</a>";
371 sub indexlink () { #{{{
372 return "<a href=\"$config{url}\">$config{wikiname}</a>";
375 sub lockwiki () { #{{{
376 # Take an exclusive lock on the wiki to prevent multiple concurrent
377 # run issues. The lock will be dropped on program exit.
378 if (! -d $config{wikistatedir}) {
379 mkdir($config{wikistatedir});
381 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
382 error ("cannot write to $config{wikistatedir}/lockfile: $!");
383 if (! flock(WIKILOCK, 2 | 4)) {
384 debug("wiki seems to be locked, waiting for lock");
385 my $wait=600; # arbitrary, but don't hang forever to
386 # prevent process pileup
388 return if flock(WIKILOCK, 2 | 4);
391 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
395 sub unlockwiki () { #{{{
399 sub loadindex () { #{{{
400 open (IN, "$config{wikistatedir}/index") || return;
402 $_=possibly_foolish_untaint($_);
406 foreach my $i (split(/ /, $_)) {
407 my ($item, $val)=split(/=/, $i, 2);
408 push @{$items{$item}}, decode_entities($val);
411 next unless exists $items{src}; # skip bad lines for now
413 my $page=pagename($items{src}[0]);
414 if (! $config{rebuild}) {
415 $pagesources{$page}=$items{src}[0];
416 $oldpagemtime{$page}=$items{mtime}[0];
417 $oldlinks{$page}=[@{$items{link}}];
418 $links{$page}=[@{$items{link}}];
419 $depends{$page}=$items{depends}[0] if exists $items{depends};
420 $renderedfiles{$page}=$items{dest}[0];
421 $pagecase{lc $page}=$page;
423 $pagectime{$page}=$items{ctime}[0];
428 sub saveindex () { #{{{
429 run_hooks(savestate => sub { shift->() });
431 if (! -d $config{wikistatedir}) {
432 mkdir($config{wikistatedir});
434 open (OUT, ">$config{wikistatedir}/index") ||
435 error("cannot write to $config{wikistatedir}/index: $!");
436 foreach my $page (keys %oldpagemtime) {
437 next unless $oldpagemtime{$page};
438 my $line="mtime=$oldpagemtime{$page} ".
439 "ctime=$pagectime{$page} ".
440 "src=$pagesources{$page} ".
441 "dest=$renderedfiles{$page}";
442 $line.=" link=$_" foreach @{$links{$page}};
443 if (exists $depends{$page}) {
444 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
446 print OUT $line."\n";
451 sub template_params (@) { #{{{
454 require HTML::Template;
455 return filter => sub {
456 my $text_ref = shift;
457 $$text_ref=&Encode::decode_utf8($$text_ref);
459 filename => "$config{templatedir}/$filename",
460 loop_context_vars => 1,
461 die_on_bad_params => 0,
465 sub template ($;@) { #{{{
466 HTML::Template->new(template_params(@_));
469 sub misctemplate ($$) { #{{{
473 my $template=template("misc.tmpl");
476 indexlink => indexlink(),
477 wikiname => $config{wikiname},
478 pagebody => $pagebody,
479 baseurl => baseurl(),
481 return $template->output;
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;
494 sub run_hooks ($$) { # {{{
495 # Calls the given sub for each hook of the given type,
496 # passing it the hook function to call.
500 if (exists $hooks{$type}) {
501 foreach my $id (keys %{$hooks{$type}}) {
502 $sub->($hooks{$type}{$id}{call});
507 sub globlist_to_pagespec ($) { #{{{
508 my @globlist=split(' ', shift);
511 foreach my $glob (@globlist) {
512 if ($glob=~/^!(.*)/) {
520 my $spec=join(" or ", @spec);
522 my $skip=join(" and ", @skip);
524 $spec="$skip and ($spec)";
533 sub is_globlist ($) { #{{{
535 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
538 sub safequote ($) { #{{{
544 sub pagespec_merge ($$) { #{{{
548 # Support for old-style GlobLists.
549 if (is_globlist($a)) {
550 $a=globlist_to_pagespec($a);
552 if (is_globlist($b)) {
553 $b=globlist_to_pagespec($b);
556 return "($a) or ($b)";
559 sub pagespec_translate ($) { #{{{
560 # This assumes that $page is in scope in the function
561 # that evalulates the translated pagespec code.
564 # Support for old-style GlobLists.
565 if (is_globlist($spec)) {
566 $spec=globlist_to_pagespec($spec);
569 # Convert spec to perl code.
571 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
573 if (lc $word eq "and") {
576 elsif (lc $word eq "or") {
579 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
582 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
583 $code.=" match_$1(\$page, ".safequote($2).")";
586 $code.=" match_glob(\$page, ".safequote($word).")";
593 sub pagespec_match ($$) { #{{{
597 return eval pagespec_translate($spec);
600 sub match_glob ($$) { #{{{
604 # turn glob into safe regexp
605 $glob=quotemeta($glob);
609 return $page=~/^$glob$/i;
612 sub match_link ($$) { #{{{
616 my $links = $links{$page} or return undef;
617 foreach my $p (@$links) {
618 return 1 if lc $p eq $link;
623 sub match_backlink ($$) { #{{{
624 match_link(pop, pop);
627 sub match_created_before ($$) { #{{{
631 if (exists $pagectime{$testpage}) {
632 return $pagectime{$page} < $pagectime{$testpage};
639 sub match_created_after ($$) { #{{{
643 if (exists $pagectime{$testpage}) {
644 return $pagectime{$page} > $pagectime{$testpage};
651 sub match_creation_day ($$) { #{{{
652 return ((gmtime($pagectime{shift()}))[3] == shift);
655 sub match_creation_month ($$) { #{{{
656 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
659 sub match_creation_year ($$) { #{{{
660 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);