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 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
20 sub defaultconfig () { #{{{
21 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$)},
22 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
23 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
27 default_pageext => "mdwn",
49 templatedir => "$installdir/share/ikiwiki/templates",
50 underlaydir => "$installdir/share/ikiwiki/basewiki",
54 plugin => [qw{mdwn inline htmlscrubber}],
59 sub checkconfig () { #{{{
60 # locale stuff; avoid LC_ALL since it overrides everything
61 if (defined $ENV{LC_ALL}) {
62 $ENV{LANG} = $ENV{LC_ALL};
65 if (defined $config{locale}) {
67 $ENV{LANG} = $config{locale}
68 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
71 if ($config{w3mmode}) {
72 eval q{use Cwd q{abs_path}};
73 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
74 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
75 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
76 unless $config{cgiurl} =~ m!file:///!;
77 $config{url}="file://".$config{destdir};
80 if ($config{cgi} && ! length $config{url}) {
81 error("Must specify url to wiki with --url when using --cgi\n");
83 if ($config{rss} && ! length $config{url}) {
84 error("Must specify url to wiki with --url when using --rss\n");
87 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
88 unless exists $config{wikistatedir};
91 eval qq{require IkiWiki::Rcs::$config{rcs}};
93 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
97 require IkiWiki::Rcs::Stub;
100 run_hooks(checkconfig => sub { shift->() });
103 sub loadplugins () { #{{{
104 foreach my $plugin (@{$config{plugin}}) {
105 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
108 error("Failed to load plugin $mod: $@");
111 run_hooks(getopt => sub { shift->() });
112 if (grep /^-/, @ARGV) {
113 print STDERR "Unknown option: $_\n"
114 foreach grep /^-/, @ARGV;
121 print "Content-type: text/html\n\n";
122 print misctemplate("Error", "<p>Error: @_</p>");
124 log_message(error => @_);
129 return unless $config{verbose};
130 log_message(debug => @_);
134 sub log_message ($$) { #{{{
137 if ($config{syslog}) {
140 Sys::Syslog::setlogsock('unix');
141 Sys::Syslog::openlog('ikiwiki', '', 'user');
145 Sys::Syslog::syslog($type, join(" ", @_));
148 elsif (! $config{cgi}) {
156 sub possibly_foolish_untaint ($) { #{{{
158 my ($untainted)=$tainted=~/(.*)/;
162 sub basename ($) { #{{{
169 sub dirname ($) { #{{{
176 sub pagetype ($) { #{{{
179 if ($page =~ /\.([^.]+)$/) {
180 return $1 if exists $hooks{htmlize}{$1};
185 sub pagename ($) { #{{{
188 my $type=pagetype($file);
190 $page=~s/\Q.$type\E*$// if defined $type;
194 sub htmlpage ($) { #{{{
197 return $page.".html";
200 sub srcfile ($) { #{{{
203 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
204 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
205 error("internal error: $file cannot be found");
208 sub readfile ($;$) { #{{{
213 error("cannot read a symlink ($file)");
217 open (IN, $file) || error("failed to read $file: $!");
218 binmode(IN) if ($binary);
224 sub writefile ($$$;$) { #{{{
225 my $file=shift; # can include subdirs
226 my $destdir=shift; # directory to put file in
231 while (length $test) {
232 if (-l "$destdir/$test") {
233 error("cannot write to a symlink ($test)");
235 $test=dirname($test);
238 my $dir=dirname("$destdir/$file");
241 foreach my $s (split(m!/+!, $dir)) {
244 mkdir($d) || error("failed to create directory $d: $!");
249 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
250 binmode(OUT) if ($binary);
255 sub bestlink ($$) { #{{{
256 # Given a page and the text of a link on the page, determine which
257 # existing page that link best points to. Prefers pages under a
258 # subdirectory with the same name as the source page, failing that
259 # goes down the directory tree to the base looking for matching
267 $l.="/" if length $l;
270 if (exists $links{$l}) {
273 elsif (exists $pagecase{lc $l}) {
274 return $pagecase{lc $l};
276 } while $cwd=~s!/?[^/]+$!!;
278 #print STDERR "warning: page $page, broken link: $link\n";
282 sub isinlinableimage ($) { #{{{
285 $file=~/\.(png|gif|jpg|jpeg)$/i;
288 sub pagetitle ($) { #{{{
290 $page=~s/__(\d+)__/&#$1;/g;
295 sub titlepage ($) { #{{{
298 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
302 sub cgiurl (@) { #{{{
305 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
308 sub baseurl (;$) { #{{{
311 return "$config{url}/" if ! defined $page;
314 $page=~s/[^\/]+\//..\//g;
318 sub abs2rel ($$) { #{{{
319 # Work around very innefficient behavior in File::Spec if abs2rel
320 # is passed two relative paths. It's much faster if paths are
326 my $ret=File::Spec->abs2rel($path, $base);
327 $ret=~s/^// if defined $ret;
331 sub htmllink ($$$;$$$) { #{{{
332 my $lpage=shift; # the page doing the linking
333 my $page=shift; # the page that will contain the link (different for inline)
335 my $noimageinline=shift; # don't turn links into inline html images
336 my $forcesubpage=shift; # force a link to a subpage
337 my $linktext=shift; # set to force the link text to something
340 if (! $forcesubpage) {
341 $bestlink=bestlink($lpage, $link);
344 $bestlink="$lpage/".lc($link);
347 $linktext=pagetitle(basename($link)) unless defined $linktext;
349 return "<span class=\"selflink\">$linktext</span>"
350 if length $bestlink && $page eq $bestlink;
352 # TODO BUG: %renderedfiles may not have it, if the linked to page
353 # was also added and isn't yet rendered! Note that this bug is
354 # masked by the bug that makes all new files be rendered twice.
355 if (! grep { $_ eq $bestlink } values %renderedfiles) {
356 $bestlink=htmlpage($bestlink);
358 if (! grep { $_ eq $bestlink } values %renderedfiles) {
359 return "<span><a href=\"".
360 cgiurl(do => "create", page => lc($link), from => $page).
361 "\">?</a>$linktext</span>"
364 $bestlink=abs2rel($bestlink, dirname($page));
366 if (! $noimageinline && isinlinableimage($bestlink)) {
367 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
369 return "<a href=\"$bestlink\">$linktext</a>";
372 sub indexlink () { #{{{
373 return "<a href=\"$config{url}\">$config{wikiname}</a>";
376 sub lockwiki () { #{{{
377 # Take an exclusive lock on the wiki to prevent multiple concurrent
378 # run issues. The lock will be dropped on program exit.
379 if (! -d $config{wikistatedir}) {
380 mkdir($config{wikistatedir});
382 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
383 error ("cannot write to $config{wikistatedir}/lockfile: $!");
384 if (! flock(WIKILOCK, 2 | 4)) {
385 debug("wiki seems to be locked, waiting for lock");
386 my $wait=600; # arbitrary, but don't hang forever to
387 # prevent process pileup
389 return if flock(WIKILOCK, 2 | 4);
392 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
396 sub unlockwiki () { #{{{
400 sub loadindex () { #{{{
401 open (IN, "$config{wikistatedir}/index") || return;
403 $_=possibly_foolish_untaint($_);
407 foreach my $i (split(/ /, $_)) {
408 my ($item, $val)=split(/=/, $i, 2);
409 push @{$items{$item}}, decode_entities($val);
412 next unless exists $items{src}; # skip bad lines for now
414 my $page=pagename($items{src}[0]);
415 if (! $config{rebuild}) {
416 $pagesources{$page}=$items{src}[0];
417 $oldpagemtime{$page}=$items{mtime}[0];
418 $oldlinks{$page}=[@{$items{link}}];
419 $links{$page}=[@{$items{link}}];
420 $depends{$page}=$items{depends}[0] if exists $items{depends};
421 $renderedfiles{$page}=$items{dest}[0];
422 $pagecase{lc $page}=$page;
424 $pagectime{$page}=$items{ctime}[0];
429 sub saveindex () { #{{{
430 run_hooks(savestate => sub { shift->() });
432 if (! -d $config{wikistatedir}) {
433 mkdir($config{wikistatedir});
435 open (OUT, ">$config{wikistatedir}/index") ||
436 error("cannot write to $config{wikistatedir}/index: $!");
437 foreach my $page (keys %oldpagemtime) {
438 next unless $oldpagemtime{$page};
439 my $line="mtime=$oldpagemtime{$page} ".
440 "ctime=$pagectime{$page} ".
441 "src=$pagesources{$page} ".
442 "dest=$renderedfiles{$page}";
443 $line.=" link=$_" foreach @{$links{$page}};
444 if (exists $depends{$page}) {
445 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
447 print OUT $line."\n";
452 sub template_params (@) { #{{{
455 require HTML::Template;
456 return filter => sub {
457 my $text_ref = shift;
458 $$text_ref=&Encode::decode_utf8($$text_ref);
460 filename => "$config{templatedir}/$filename",
461 loop_context_vars => 1,
462 die_on_bad_params => 0,
466 sub template ($;@) { #{{{
467 HTML::Template->new(template_params(@_));
470 sub misctemplate ($$) { #{{{
474 my $template=template("misc.tmpl");
477 indexlink => indexlink(),
478 wikiname => $config{wikiname},
479 pagebody => $pagebody,
480 baseurl => baseurl(),
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 return $a if $a eq $b;
551 # Support for old-style GlobLists.
552 if (is_globlist($a)) {
553 $a=globlist_to_pagespec($a);
555 if (is_globlist($b)) {
556 $b=globlist_to_pagespec($b);
559 return "($a) or ($b)";
562 sub pagespec_translate ($) { #{{{
563 # This assumes that $page is in scope in the function
564 # that evalulates the translated pagespec code.
567 # Support for old-style GlobLists.
568 if (is_globlist($spec)) {
569 $spec=globlist_to_pagespec($spec);
572 # Convert spec to perl code.
574 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
576 if (lc $word eq "and") {
579 elsif (lc $word eq "or") {
582 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
585 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
586 $code.=" match_$1(\$page, ".safequote($2).")";
589 $code.=" match_glob(\$page, ".safequote($word).")";
596 sub pagespec_match ($$) { #{{{
600 return eval pagespec_translate($spec);
603 sub match_glob ($$) { #{{{
607 # turn glob into safe regexp
608 $glob=quotemeta($glob);
612 return $page=~/^$glob$/i;
615 sub match_link ($$) { #{{{
619 my $links = $links{$page} or return undef;
620 foreach my $p (@$links) {
621 return 1 if lc $p eq $link;
626 sub match_backlink ($$) { #{{{
627 match_link(pop, pop);
630 sub match_created_before ($$) { #{{{
634 if (exists $pagectime{$testpage}) {
635 return $pagectime{$page} < $pagectime{$testpage};
642 sub match_created_after ($$) { #{{{
646 if (exists $pagectime{$testpage}) {
647 return $pagectime{$page} > $pagectime{$testpage};
654 sub match_creation_day ($$) { #{{{
655 return ((gmtime($pagectime{shift()}))[3] == shift);
658 sub match_creation_month ($$) { #{{{
659 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
662 sub match_creation_year ($$) { #{{{
663 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);