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 styleurl (;$) { #{{{
310 return "$config{url}/style.css" if ! defined $page;
313 $page=~s/[^\/]+\//..\//g;
314 return $page."style.css";
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 styleurl => styleurl(),
480 baseurl => "$config{url}/",
482 return $template->output;
488 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
489 error "hook requires type, call, and id parameters";
492 $hooks{$param{type}}{$param{id}}=\%param;
495 sub run_hooks ($$) { # {{{
496 # Calls the given sub for each hook of the given type,
497 # passing it the hook function to call.
501 if (exists $hooks{$type}) {
502 foreach my $id (keys %{$hooks{$type}}) {
503 $sub->($hooks{$type}{$id}{call});
508 sub globlist_to_pagespec ($) { #{{{
509 my @globlist=split(' ', shift);
512 foreach my $glob (@globlist) {
513 if ($glob=~/^!(.*)/) {
521 my $spec=join(" or ", @spec);
523 my $skip=join(" and ", @skip);
525 $spec="$skip and ($spec)";
534 sub is_globlist ($) { #{{{
536 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
539 sub safequote ($) { #{{{
545 sub pagespec_merge ($$) { #{{{
549 # Support for old-style GlobLists.
550 if (is_globlist($a)) {
551 $a=globlist_to_pagespec($a);
553 if (is_globlist($b)) {
554 $b=globlist_to_pagespec($b);
557 return "($a) or ($b)";
560 sub pagespec_translate ($) { #{{{
561 # This assumes that $page is in scope in the function
562 # that evalulates the translated pagespec code.
565 # Support for old-style GlobLists.
566 if (is_globlist($spec)) {
567 $spec=globlist_to_pagespec($spec);
570 # Convert spec to perl code.
572 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
574 if (lc $word eq "and") {
577 elsif (lc $word eq "or") {
580 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
583 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
584 $code.=" match_$1(\$page, ".safequote($2).")";
587 $code.=" match_glob(\$page, ".safequote($word).")";
594 sub pagespec_match ($$) { #{{{
598 return eval pagespec_translate($spec);
601 sub match_glob ($$) { #{{{
605 # turn glob into safe regexp
606 $glob=quotemeta($glob);
610 return $page=~/^$glob$/i;
613 sub match_link ($$) { #{{{
617 my $links = $links{$page} or return undef;
618 foreach my $p (@$links) {
619 return 1 if lc $p eq $link;
624 sub match_backlink ($$) { #{{{
625 match_link(pop, pop);
628 sub match_created_before ($$) { #{{{
632 if (exists $pagectime{$testpage}) {
633 return $pagectime{$page} < $pagectime{$testpage};
640 sub match_created_after ($$) { #{{{
644 if (exists $pagectime{$testpage}) {
645 return $pagectime{$page} > $pagectime{$testpage};
652 sub match_creation_day ($$) { #{{{
653 return ((gmtime($pagectime{shift()}))[3] == shift);
656 sub match_creation_month ($$) { #{{{
657 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
660 sub match_creation_year ($$) { #{{{
661 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);