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_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
25 default_pageext => "mdwn",
47 templatedir => "/usr/share/ikiwiki/templates",
48 underlaydir => "/usr/share/ikiwiki/basewiki",
52 plugin => [qw{mdwn inline htmlscrubber}],
57 sub checkconfig () { #{{{
58 # locale stuff; avoid LC_ALL since it overrides everything
59 if (defined $ENV{LC_ALL}) {
60 $ENV{LANG} = $ENV{LC_ALL};
63 if (defined $config{locale}) {
65 $ENV{LANG} = $config{locale}
66 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
69 if ($config{w3mmode}) {
70 eval q{use Cwd q{abs_path}};
71 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
72 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
73 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
74 unless $config{cgiurl} =~ m!file:///!;
75 $config{url}="file://".$config{destdir};
78 if ($config{cgi} && ! length $config{url}) {
79 error("Must specify url to wiki with --url when using --cgi\n");
81 if ($config{rss} && ! length $config{url}) {
82 error("Must specify url to wiki with --url when using --rss\n");
85 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
86 unless exists $config{wikistatedir};
89 eval qq{require IkiWiki::Rcs::$config{rcs}};
91 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
95 require IkiWiki::Rcs::Stub;
98 run_hooks(checkconfig => sub { shift->() });
101 sub loadplugins () { #{{{
102 foreach my $plugin (@{$config{plugin}}) {
103 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
106 error("Failed to load plugin $mod: $@");
109 run_hooks(getopt => sub { shift->() });
110 if (grep /^-/, @ARGV) {
111 print STDERR "Unknown option: $_\n"
112 foreach grep /^-/, @ARGV;
119 print "Content-type: text/html\n\n";
120 print misctemplate("Error", "<p>Error: @_</p>");
122 log_message(error => @_);
127 return unless $config{verbose};
128 log_message(debug => @_);
132 sub log_message ($$) { #{{{
135 if ($config{syslog}) {
138 Sys::Syslog::setlogsock('unix');
139 Sys::Syslog::openlog('ikiwiki', '', 'user');
143 Sys::Syslog::syslog($type, join(" ", @_));
146 elsif (! $config{cgi}) {
154 sub possibly_foolish_untaint ($) { #{{{
156 my ($untainted)=$tainted=~/(.*)/;
160 sub basename ($) { #{{{
167 sub dirname ($) { #{{{
174 sub pagetype ($) { #{{{
177 if ($page =~ /\.([^.]+)$/) {
178 return $1 if exists $hooks{htmlize}{$1};
183 sub pagename ($) { #{{{
186 my $type=pagetype($file);
188 $page=~s/\Q.$type\E*$// if defined $type;
192 sub htmlpage ($) { #{{{
195 return $page.".html";
198 sub srcfile ($) { #{{{
201 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
202 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
203 error("internal error: $file cannot be found");
206 sub readfile ($;$) { #{{{
211 error("cannot read a symlink ($file)");
215 open (IN, $file) || error("failed to read $file: $!");
216 binmode(IN) if ($binary);
222 sub writefile ($$$;$) { #{{{
223 my $file=shift; # can include subdirs
224 my $destdir=shift; # directory to put file in
229 while (length $test) {
230 if (-l "$destdir/$test") {
231 error("cannot write to a symlink ($test)");
233 $test=dirname($test);
236 my $dir=dirname("$destdir/$file");
239 foreach my $s (split(m!/+!, $dir)) {
242 mkdir($d) || error("failed to create directory $d: $!");
247 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
248 binmode(OUT) if ($binary);
253 sub bestlink ($$) { #{{{
254 # Given a page and the text of a link on the page, determine which
255 # existing page that link best points to. Prefers pages under a
256 # subdirectory with the same name as the source page, failing that
257 # goes down the directory tree to the base looking for matching
265 $l.="/" if length $l;
268 if (exists $links{$l}) {
271 elsif (exists $pagecase{lc $l}) {
272 return $pagecase{lc $l};
274 } while $cwd=~s!/?[^/]+$!!;
276 #print STDERR "warning: page $page, broken link: $link\n";
280 sub isinlinableimage ($) { #{{{
283 $file=~/\.(png|gif|jpg|jpeg)$/i;
286 sub pagetitle ($) { #{{{
288 $page=~s/__(\d+)__/&#$1;/g;
293 sub titlepage ($) { #{{{
296 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
300 sub cgiurl (@) { #{{{
303 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
306 sub baseurl (;$) { #{{{
309 return "$config{url}/" if ! defined $page;
312 $page=~s/[^\/]+\//..\//g;
316 sub abs2rel ($$) { #{{{
317 # Work around very innefficient behavior in File::Spec if abs2rel
318 # is passed two relative paths. It's much faster if paths are
324 my $ret=File::Spec->abs2rel($path, $base);
325 $ret=~s/^// if defined $ret;
329 sub htmllink ($$$;$$$) { #{{{
330 my $lpage=shift; # the page doing the linking
331 my $page=shift; # the page that will contain the link (different for inline)
333 my $noimageinline=shift; # don't turn links into inline html images
334 my $forcesubpage=shift; # force a link to a subpage
335 my $linktext=shift; # set to force the link text to something
338 if (! $forcesubpage) {
339 $bestlink=bestlink($lpage, $link);
342 $bestlink="$lpage/".lc($link);
345 $linktext=pagetitle(basename($link)) unless defined $linktext;
347 return "<span class=\"selflink\">$linktext</span>"
348 if length $bestlink && $page eq $bestlink;
350 # TODO BUG: %renderedfiles may not have it, if the linked to page
351 # was also added and isn't yet rendered! Note that this bug is
352 # masked by the bug that makes all new files be rendered twice.
353 if (! grep { $_ eq $bestlink } values %renderedfiles) {
354 $bestlink=htmlpage($bestlink);
356 if (! grep { $_ eq $bestlink } values %renderedfiles) {
357 return "<span><a href=\"".
358 cgiurl(do => "create", page => lc($link), from => $page).
359 "\">?</a>$linktext</span>"
362 $bestlink=abs2rel($bestlink, dirname($page));
364 if (! $noimageinline && isinlinableimage($bestlink)) {
365 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
367 return "<a href=\"$bestlink\">$linktext</a>";
370 sub indexlink () { #{{{
371 return "<a href=\"$config{url}\">$config{wikiname}</a>";
374 sub lockwiki () { #{{{
375 # Take an exclusive lock on the wiki to prevent multiple concurrent
376 # run issues. The lock will be dropped on program exit.
377 if (! -d $config{wikistatedir}) {
378 mkdir($config{wikistatedir});
380 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
381 error ("cannot write to $config{wikistatedir}/lockfile: $!");
382 if (! flock(WIKILOCK, 2 | 4)) {
383 debug("wiki seems to be locked, waiting for lock");
384 my $wait=600; # arbitrary, but don't hang forever to
385 # prevent process pileup
387 return if flock(WIKILOCK, 2 | 4);
390 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
394 sub unlockwiki () { #{{{
398 sub loadindex () { #{{{
399 open (IN, "$config{wikistatedir}/index") || return;
401 $_=possibly_foolish_untaint($_);
405 foreach my $i (split(/ /, $_)) {
406 my ($item, $val)=split(/=/, $i, 2);
407 push @{$items{$item}}, decode_entities($val);
410 next unless exists $items{src}; # skip bad lines for now
412 my $page=pagename($items{src}[0]);
413 if (! $config{rebuild}) {
414 $pagesources{$page}=$items{src}[0];
415 $oldpagemtime{$page}=$items{mtime}[0];
416 $oldlinks{$page}=[@{$items{link}}];
417 $links{$page}=[@{$items{link}}];
418 $depends{$page}=$items{depends}[0] if exists $items{depends};
419 $renderedfiles{$page}=$items{dest}[0];
420 $pagecase{lc $page}=$page;
422 $pagectime{$page}=$items{ctime}[0];
427 sub saveindex () { #{{{
428 run_hooks(savestate => sub { shift->() });
430 if (! -d $config{wikistatedir}) {
431 mkdir($config{wikistatedir});
433 open (OUT, ">$config{wikistatedir}/index") ||
434 error("cannot write to $config{wikistatedir}/index: $!");
435 foreach my $page (keys %oldpagemtime) {
436 next unless $oldpagemtime{$page};
437 my $line="mtime=$oldpagemtime{$page} ".
438 "ctime=$pagectime{$page} ".
439 "src=$pagesources{$page} ".
440 "dest=$renderedfiles{$page}";
441 $line.=" link=$_" foreach @{$links{$page}};
442 if (exists $depends{$page}) {
443 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
445 print OUT $line."\n";
450 sub template_params (@) { #{{{
453 require HTML::Template;
454 return filter => sub {
455 my $text_ref = shift;
456 $$text_ref=&Encode::decode_utf8($$text_ref);
458 filename => "$config{templatedir}/$filename",
459 loop_context_vars => 1,
460 die_on_bad_params => 0,
464 sub template ($;@) { #{{{
465 HTML::Template->new(template_params(@_));
468 sub misctemplate ($$) { #{{{
472 my $template=template("misc.tmpl");
475 indexlink => indexlink(),
476 wikiname => $config{wikiname},
477 pagebody => $pagebody,
478 baseurl => baseurl(),
480 return $template->output;
486 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
487 error "hook requires type, call, and id parameters";
490 $hooks{$param{type}}{$param{id}}=\%param;
493 sub run_hooks ($$) { # {{{
494 # Calls the given sub for each hook of the given type,
495 # passing it the hook function to call.
499 if (exists $hooks{$type}) {
500 foreach my $id (keys %{$hooks{$type}}) {
501 $sub->($hooks{$type}{$id}{call});
506 sub globlist_to_pagespec ($) { #{{{
507 my @globlist=split(' ', shift);
510 foreach my $glob (@globlist) {
511 if ($glob=~/^!(.*)/) {
519 my $spec=join(" or ", @spec);
521 my $skip=join(" and ", @skip);
523 $spec="$skip and ($spec)";
532 sub is_globlist ($) { #{{{
534 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
537 sub safequote ($) { #{{{
543 sub pagespec_merge ($$) { #{{{
547 return $a if $a eq $b;
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);