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:]_.:\/+]+$)/,
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>");
126 return unless $config{verbose};
127 if (! $config{cgi}) {
135 sub possibly_foolish_untaint ($) { #{{{
137 my ($untainted)=$tainted=~/(.*)/;
141 sub basename ($) { #{{{
148 sub dirname ($) { #{{{
155 sub pagetype ($) { #{{{
158 if ($page =~ /\.([^.]+)$/) {
159 return $1 if exists $hooks{htmlize}{$1};
164 sub pagename ($) { #{{{
167 my $type=pagetype($file);
169 $page=~s/\Q.$type\E*$// if defined $type;
173 sub htmlpage ($) { #{{{
176 return $page.".html";
179 sub srcfile ($) { #{{{
182 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
183 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
184 error("internal error: $file cannot be found");
187 sub readfile ($;$) { #{{{
192 error("cannot read a symlink ($file)");
196 open (IN, $file) || error("failed to read $file: $!");
197 binmode(IN) if ($binary);
203 sub writefile ($$$;$) { #{{{
204 my $file=shift; # can include subdirs
205 my $destdir=shift; # directory to put file in
210 while (length $test) {
211 if (-l "$destdir/$test") {
212 error("cannot write to a symlink ($test)");
214 $test=dirname($test);
217 my $dir=dirname("$destdir/$file");
220 foreach my $s (split(m!/+!, $dir)) {
223 mkdir($d) || error("failed to create directory $d: $!");
228 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
229 binmode(OUT) if ($binary);
234 sub bestlink ($$) { #{{{
235 # Given a page and the text of a link on the page, determine which
236 # existing page that link best points to. Prefers pages under a
237 # subdirectory with the same name as the source page, failing that
238 # goes down the directory tree to the base looking for matching
246 $l.="/" if length $l;
249 if (exists $links{$l}) {
252 elsif (exists $pagecase{lc $l}) {
253 return $pagecase{lc $l};
255 } while $cwd=~s!/?[^/]+$!!;
257 #print STDERR "warning: page $page, broken link: $link\n";
261 sub isinlinableimage ($) { #{{{
264 $file=~/\.(png|gif|jpg|jpeg)$/i;
267 sub pagetitle ($) { #{{{
269 $page=~s/__(\d+)__/&#$1;/g;
274 sub titlepage ($) { #{{{
277 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
281 sub cgiurl (@) { #{{{
284 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
287 sub styleurl (;$) { #{{{
290 return "$config{url}/style.css" if ! defined $page;
293 $page=~s/[^\/]+\//..\//g;
294 return $page."style.css";
297 sub abs2rel ($$) { #{{{
298 # Work around very innefficient behavior in File::Spec if abs2rel
299 # is passed two relative paths. It's much faster if paths are
305 my $ret=File::Spec->abs2rel($path, $base);
306 $ret=~s/^// if defined $ret;
310 sub htmllink ($$$;$$$) { #{{{
311 my $lpage=shift; # the page doing the linking
312 my $page=shift; # the page that will contain the link (different for inline)
314 my $noimageinline=shift; # don't turn links into inline html images
315 my $forcesubpage=shift; # force a link to a subpage
316 my $linktext=shift; # set to force the link text to something
319 if (! $forcesubpage) {
320 $bestlink=bestlink($lpage, $link);
323 $bestlink="$lpage/".lc($link);
326 $linktext=pagetitle(basename($link)) unless defined $linktext;
328 return $linktext if length $bestlink && $page eq $bestlink;
330 # TODO BUG: %renderedfiles may not have it, if the linked to page
331 # was also added and isn't yet rendered! Note that this bug is
332 # masked by the bug that makes all new files be rendered twice.
333 if (! grep { $_ eq $bestlink } values %renderedfiles) {
334 $bestlink=htmlpage($bestlink);
336 if (! grep { $_ eq $bestlink } values %renderedfiles) {
337 return "<span><a href=\"".
338 cgiurl(do => "create", page => lc($link), from => $page).
339 "\">?</a>$linktext</span>"
342 $bestlink=abs2rel($bestlink, dirname($page));
344 if (! $noimageinline && isinlinableimage($bestlink)) {
345 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
347 return "<a href=\"$bestlink\">$linktext</a>";
350 sub indexlink () { #{{{
351 return "<a href=\"$config{url}\">$config{wikiname}</a>";
354 sub lockwiki () { #{{{
355 # Take an exclusive lock on the wiki to prevent multiple concurrent
356 # run issues. The lock will be dropped on program exit.
357 if (! -d $config{wikistatedir}) {
358 mkdir($config{wikistatedir});
360 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
361 error ("cannot write to $config{wikistatedir}/lockfile: $!");
362 if (! flock(WIKILOCK, 2 | 4)) {
363 debug("wiki seems to be locked, waiting for lock");
364 my $wait=600; # arbitrary, but don't hang forever to
365 # prevent process pileup
367 return if flock(WIKILOCK, 2 | 4);
370 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
374 sub unlockwiki () { #{{{
378 sub loadindex () { #{{{
379 open (IN, "$config{wikistatedir}/index") || return;
381 $_=possibly_foolish_untaint($_);
385 foreach my $i (split(/ /, $_)) {
386 my ($item, $val)=split(/=/, $i, 2);
387 push @{$items{$item}}, decode_entities($val);
390 next unless exists $items{src}; # skip bad lines for now
392 my $page=pagename($items{src}[0]);
393 if (! $config{rebuild}) {
394 $pagesources{$page}=$items{src}[0];
395 $oldpagemtime{$page}=$items{mtime}[0];
396 $oldlinks{$page}=[@{$items{link}}];
397 $links{$page}=[@{$items{link}}];
398 $depends{$page}=$items{depends}[0] if exists $items{depends};
399 $renderedfiles{$page}=$items{dest}[0];
400 $pagecase{lc $page}=$page;
402 $pagectime{$page}=$items{ctime}[0];
407 sub saveindex () { #{{{
408 run_hooks(savestate => sub { shift->() });
410 if (! -d $config{wikistatedir}) {
411 mkdir($config{wikistatedir});
413 open (OUT, ">$config{wikistatedir}/index") ||
414 error("cannot write to $config{wikistatedir}/index: $!");
415 foreach my $page (keys %oldpagemtime) {
416 next unless $oldpagemtime{$page};
417 my $line="mtime=$oldpagemtime{$page} ".
418 "ctime=$pagectime{$page} ".
419 "src=$pagesources{$page} ".
420 "dest=$renderedfiles{$page}";
421 $line.=" link=$_" foreach @{$links{$page}};
422 if (exists $depends{$page}) {
423 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
425 print OUT $line."\n";
430 sub template_params (@) { #{{{
433 require HTML::Template;
434 return filter => sub {
435 my $text_ref = shift;
436 $$text_ref=&Encode::decode_utf8($$text_ref);
438 filename => "$config{templatedir}/$filename",
439 loop_context_vars => 1,
440 die_on_bad_params => 0,
444 sub template ($;@) { #{{{
445 HTML::Template->new(template_params(@_));
448 sub misctemplate ($$) { #{{{
452 my $template=template("misc.tmpl");
455 indexlink => indexlink(),
456 wikiname => $config{wikiname},
457 pagebody => $pagebody,
458 styleurl => styleurl(),
459 baseurl => "$config{url}/",
461 return $template->output;
467 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
468 error "hook requires type, call, and id parameters";
471 $hooks{$param{type}}{$param{id}}=\%param;
474 sub run_hooks ($$) { # {{{
475 # Calls the given sub for each hook of the given type,
476 # passing it the hook function to call.
480 if (exists $hooks{$type}) {
481 foreach my $id (keys %{$hooks{$type}}) {
482 $sub->($hooks{$type}{$id}{call});
487 sub globlist_to_pagespec ($) { #{{{
488 my @globlist=split(' ', shift);
491 foreach my $glob (@globlist) {
492 if ($glob=~/^!(.*)/) {
500 my $spec=join(" or ", @spec);
502 my $skip=join(" and ", @skip);
504 $spec="$skip and ($spec)";
513 sub is_globlist ($) { #{{{
515 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
518 sub safequote ($) { #{{{
524 sub pagespec_merge ($$) { #{{{
528 # Support for old-style GlobLists.
529 if (is_globlist($a)) {
530 $a=globlist_to_pagespec($a);
532 if (is_globlist($b)) {
533 $b=globlist_to_pagespec($b);
536 return "($a) or ($b)";
539 sub pagespec_translate ($) { #{{{
540 # This assumes that $page is in scope in the function
541 # that evalulates the translated pagespec code.
544 # Support for old-style GlobLists.
545 if (is_globlist($spec)) {
546 $spec=globlist_to_pagespec($spec);
549 # Convert spec to perl code.
551 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
553 if (lc $word eq "and") {
556 elsif (lc $word eq "or") {
559 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
562 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
563 $code.=" match_$1(\$page, ".safequote($2).")";
566 $code.=" match_glob(\$page, ".safequote($word).")";
573 sub pagespec_match ($$) { #{{{
577 return eval pagespec_translate($spec);
580 sub match_glob ($$) { #{{{
584 # turn glob into safe regexp
585 $glob=quotemeta($glob);
589 return $page=~/^$glob$/i;
592 sub match_link ($$) { #{{{
596 my $links = $links{$page} or return undef;
597 foreach my $p (@$links) {
598 return 1 if lc $p eq $link;
603 sub match_backlink ($$) { #{{{
604 match_link(pop, pop);
607 sub match_created_before ($$) { #{{{
611 if (exists $pagectime{$testpage}) {
612 return $pagectime{$page} < $pagectime{$testpage};
619 sub match_created_after ($$) { #{{{
623 if (exists $pagectime{$testpage}) {
624 return $pagectime{$page} > $pagectime{$testpage};
631 sub match_creation_day ($$) { #{{{
632 return ((gmtime($pagectime{shift()}))[3] == shift);
635 sub match_creation_month ($$) { #{{{
636 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
639 sub match_creation_year ($$) { #{{{
640 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);