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}],
60 sub checkconfig () { #{{{
61 # locale stuff; avoid LC_ALL since it overrides everything
62 if (defined $ENV{LC_ALL}) {
63 $ENV{LANG} = $ENV{LC_ALL};
66 if (defined $config{locale}) {
68 $ENV{LANG} = $config{locale}
69 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
72 if ($config{w3mmode}) {
73 eval q{use Cwd q{abs_path}};
74 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
75 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
76 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
77 unless $config{cgiurl} =~ m!file:///!;
78 $config{url}="file://".$config{destdir};
81 if ($config{cgi} && ! length $config{url}) {
82 error("Must specify url to wiki with --url when using --cgi\n");
84 if ($config{rss} && ! length $config{url}) {
85 error("Must specify url to wiki with --url when using --rss\n");
88 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
89 unless exists $config{wikistatedir};
92 eval qq{require IkiWiki::Rcs::$config{rcs}};
94 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
98 require IkiWiki::Rcs::Stub;
101 run_hooks(checkconfig => sub { shift->() });
104 sub loadplugins () { #{{{
105 foreach my $plugin (@{$config{plugin}}) {
106 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
109 error("Failed to load plugin $mod: $@");
112 run_hooks(getopt => sub { shift->() });
113 if (grep /^-/, @ARGV) {
114 print STDERR "Unknown option: $_\n"
115 foreach grep /^-/, @ARGV;
122 print "Content-type: text/html\n\n";
123 print misctemplate("Error", "<p>Error: @_</p>");
125 log_message(error => @_);
130 return unless $config{verbose};
131 log_message(debug => @_);
135 sub log_message ($$) { #{{{
138 if ($config{syslog}) {
141 Sys::Syslog::setlogsock('unix');
142 Sys::Syslog::openlog('ikiwiki', '', 'user');
146 Sys::Syslog::syslog($type, join(" ", @_));
149 elsif (! $config{cgi}) {
157 sub possibly_foolish_untaint ($) { #{{{
159 my ($untainted)=$tainted=~/(.*)/;
163 sub basename ($) { #{{{
170 sub dirname ($) { #{{{
177 sub pagetype ($) { #{{{
180 if ($page =~ /\.([^.]+)$/) {
181 return $1 if exists $hooks{htmlize}{$1};
186 sub pagename ($) { #{{{
189 my $type=pagetype($file);
191 $page=~s/\Q.$type\E*$// if defined $type;
195 sub htmlpage ($) { #{{{
198 return $page.".html";
201 sub srcfile ($) { #{{{
204 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
205 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
206 error("internal error: $file cannot be found");
209 sub readfile ($;$) { #{{{
214 error("cannot read a symlink ($file)");
218 open (IN, $file) || error("failed to read $file: $!");
219 binmode(IN) if ($binary);
225 sub writefile ($$$;$) { #{{{
226 my $file=shift; # can include subdirs
227 my $destdir=shift; # directory to put file in
232 while (length $test) {
233 if (-l "$destdir/$test") {
234 error("cannot write to a symlink ($test)");
236 $test=dirname($test);
239 my $dir=dirname("$destdir/$file");
242 foreach my $s (split(m!/+!, $dir)) {
245 mkdir($d) || error("failed to create directory $d: $!");
250 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
251 binmode(OUT) if ($binary);
256 sub bestlink ($$) { #{{{
257 # Given a page and the text of a link on the page, determine which
258 # existing page that link best points to. Prefers pages under a
259 # subdirectory with the same name as the source page, failing that
260 # goes down the directory tree to the base looking for matching
268 $l.="/" if length $l;
271 if (exists $links{$l}) {
274 elsif (exists $pagecase{lc $l}) {
275 return $pagecase{lc $l};
277 } while $cwd=~s!/?[^/]+$!!;
279 #print STDERR "warning: page $page, broken link: $link\n";
283 sub isinlinableimage ($) { #{{{
286 $file=~/\.(png|gif|jpg|jpeg)$/i;
289 sub pagetitle ($) { #{{{
291 $page=~s/__(\d+)__/&#$1;/g;
296 sub titlepage ($) { #{{{
299 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
303 sub cgiurl (@) { #{{{
306 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
309 sub baseurl (;$) { #{{{
312 return "$config{url}/" if ! defined $page;
315 $page=~s/[^\/]+\//..\//g;
319 sub abs2rel ($$) { #{{{
320 # Work around very innefficient behavior in File::Spec if abs2rel
321 # is passed two relative paths. It's much faster if paths are
327 my $ret=File::Spec->abs2rel($path, $base);
328 $ret=~s/^// if defined $ret;
332 sub htmllink ($$$;$$$) { #{{{
333 my $lpage=shift; # the page doing the linking
334 my $page=shift; # the page that will contain the link (different for inline)
336 my $noimageinline=shift; # don't turn links into inline html images
337 my $forcesubpage=shift; # force a link to a subpage
338 my $linktext=shift; # set to force the link text to something
341 if (! $forcesubpage) {
342 $bestlink=bestlink($lpage, $link);
345 $bestlink="$lpage/".lc($link);
348 $linktext=pagetitle(basename($link)) unless defined $linktext;
350 return "<span class=\"selflink\">$linktext</span>"
351 if length $bestlink && $page eq $bestlink;
353 # TODO BUG: %renderedfiles may not have it, if the linked to page
354 # was also added and isn't yet rendered! Note that this bug is
355 # masked by the bug that makes all new files be rendered twice.
356 if (! grep { $_ eq $bestlink } values %renderedfiles) {
357 $bestlink=htmlpage($bestlink);
359 if (! grep { $_ eq $bestlink } values %renderedfiles) {
360 return "<span><a href=\"".
361 cgiurl(do => "create", page => lc($link), from => $page).
362 "\">?</a>$linktext</span>"
365 $bestlink=abs2rel($bestlink, dirname($page));
367 if (! $noimageinline && isinlinableimage($bestlink)) {
368 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
370 return "<a href=\"$bestlink\">$linktext</a>";
373 sub indexlink () { #{{{
374 return "<a href=\"$config{url}\">$config{wikiname}</a>";
377 sub lockwiki () { #{{{
378 # Take an exclusive lock on the wiki to prevent multiple concurrent
379 # run issues. The lock will be dropped on program exit.
380 if (! -d $config{wikistatedir}) {
381 mkdir($config{wikistatedir});
383 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
384 error ("cannot write to $config{wikistatedir}/lockfile: $!");
385 if (! flock(WIKILOCK, 2 | 4)) {
386 debug("wiki seems to be locked, waiting for lock");
387 my $wait=600; # arbitrary, but don't hang forever to
388 # prevent process pileup
390 return if flock(WIKILOCK, 2 | 4);
393 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
397 sub unlockwiki () { #{{{
401 sub loadindex () { #{{{
402 open (IN, "$config{wikistatedir}/index") || return;
404 $_=possibly_foolish_untaint($_);
408 foreach my $i (split(/ /, $_)) {
409 my ($item, $val)=split(/=/, $i, 2);
410 push @{$items{$item}}, decode_entities($val);
413 next unless exists $items{src}; # skip bad lines for now
415 my $page=pagename($items{src}[0]);
416 if (! $config{rebuild}) {
417 $pagesources{$page}=$items{src}[0];
418 $oldpagemtime{$page}=$items{mtime}[0];
419 $oldlinks{$page}=[@{$items{link}}];
420 $links{$page}=[@{$items{link}}];
421 $depends{$page}=$items{depends}[0] if exists $items{depends};
422 $renderedfiles{$page}=$items{dest}[0];
423 $pagecase{lc $page}=$page;
425 $pagectime{$page}=$items{ctime}[0];
430 sub saveindex () { #{{{
431 run_hooks(savestate => sub { shift->() });
433 if (! -d $config{wikistatedir}) {
434 mkdir($config{wikistatedir});
436 open (OUT, ">$config{wikistatedir}/index") ||
437 error("cannot write to $config{wikistatedir}/index: $!");
438 foreach my $page (keys %oldpagemtime) {
439 next unless $oldpagemtime{$page};
440 my $line="mtime=$oldpagemtime{$page} ".
441 "ctime=$pagectime{$page} ".
442 "src=$pagesources{$page} ".
443 "dest=$renderedfiles{$page}";
444 $line.=" link=$_" foreach @{$links{$page}};
445 if (exists $depends{$page}) {
446 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
448 print OUT $line."\n";
453 sub template_params (@) { #{{{
456 require HTML::Template;
457 return filter => sub {
458 my $text_ref = shift;
459 $$text_ref=&Encode::decode_utf8($$text_ref);
461 filename => "$config{templatedir}/$filename",
462 loop_context_vars => 1,
463 die_on_bad_params => 0,
467 sub template ($;@) { #{{{
468 HTML::Template->new(template_params(@_));
471 sub misctemplate ($$) { #{{{
475 my $template=template("misc.tmpl");
478 indexlink => indexlink(),
479 wikiname => $config{wikiname},
480 pagebody => $pagebody,
481 baseurl => baseurl(),
483 return $template->output;
489 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
490 error "hook requires type, call, and id parameters";
493 $hooks{$param{type}}{$param{id}}=\%param;
496 sub run_hooks ($$) { # {{{
497 # Calls the given sub for each hook of the given type,
498 # passing it the hook function to call.
502 if (exists $hooks{$type}) {
503 foreach my $id (keys %{$hooks{$type}}) {
504 $sub->($hooks{$type}{$id}{call});
509 sub globlist_to_pagespec ($) { #{{{
510 my @globlist=split(' ', shift);
513 foreach my $glob (@globlist) {
514 if ($glob=~/^!(.*)/) {
522 my $spec=join(" or ", @spec);
524 my $skip=join(" and ", @skip);
526 $spec="$skip and ($spec)";
535 sub is_globlist ($) { #{{{
537 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
540 sub safequote ($) { #{{{
546 sub pagespec_merge ($$) { #{{{
550 return $a if $a eq $b;
552 # Support for old-style GlobLists.
553 if (is_globlist($a)) {
554 $a=globlist_to_pagespec($a);
556 if (is_globlist($b)) {
557 $b=globlist_to_pagespec($b);
560 return "($a) or ($b)";
563 sub pagespec_translate ($) { #{{{
564 # This assumes that $page is in scope in the function
565 # that evalulates the translated pagespec code.
568 # Support for old-style GlobLists.
569 if (is_globlist($spec)) {
570 $spec=globlist_to_pagespec($spec);
573 # Convert spec to perl code.
575 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
577 if (lc $word eq "and") {
580 elsif (lc $word eq "or") {
583 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
586 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
587 $code.=" match_$1(\$page, ".safequote($2).")";
590 $code.=" match_glob(\$page, ".safequote($word).")";
597 sub pagespec_match ($$) { #{{{
601 return eval pagespec_translate($spec);
604 sub match_glob ($$) { #{{{
608 # turn glob into safe regexp
609 $glob=quotemeta($glob);
613 return $page=~/^$glob$/i;
616 sub match_link ($$) { #{{{
620 my $links = $links{$page} or return undef;
621 foreach my $p (@$links) {
622 return 1 if lc $p eq $link;
627 sub match_backlink ($$) { #{{{
628 match_link(pop, pop);
631 sub match_created_before ($$) { #{{{
635 if (exists $pagectime{$testpage}) {
636 return $pagectime{$page} < $pagectime{$testpage};
643 sub match_created_after ($$) { #{{{
647 if (exists $pagectime{$testpage}) {
648 return $pagectime{$page} > $pagectime{$testpage};
655 sub match_creation_day ($$) { #{{{
656 return ((gmtime($pagectime{shift()}))[3] == shift);
659 sub match_creation_month ($$) { #{{{
660 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
663 sub match_creation_year ($$) { #{{{
664 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);