8 use open qw{:utf8 :std};
10 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
11 %renderedfiles %pagesources %depends %hooks %forcerebuild};
13 use Exporter q{import};
14 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
15 bestlink htmllink readfile writefile pagetype srcfile pagename
16 %config %links %renderedfiles %pagesources);
21 memoize("pagespec_translate");
23 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
25 sub defaultconfig () { #{{{
26 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$)},
27 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
28 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
32 default_pageext => "mdwn",
54 templatedir => "$installdir/share/ikiwiki/templates",
55 underlaydir => "$installdir/share/ikiwiki/basewiki",
59 plugin => [qw{mdwn inline htmlscrubber}],
65 sub checkconfig () { #{{{
66 # locale stuff; avoid LC_ALL since it overrides everything
67 if (defined $ENV{LC_ALL}) {
68 $ENV{LANG} = $ENV{LC_ALL};
71 if (defined $config{locale}) {
73 $ENV{LANG} = $config{locale}
74 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
77 if ($config{w3mmode}) {
78 eval q{use Cwd q{abs_path}};
79 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
80 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
81 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
82 unless $config{cgiurl} =~ m!file:///!;
83 $config{url}="file://".$config{destdir};
86 if ($config{cgi} && ! length $config{url}) {
87 error("Must specify url to wiki with --url when using --cgi\n");
89 if ($config{rss} && ! length $config{url}) {
90 error("Must specify url to wiki with --url when using --rss\n");
93 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
94 unless exists $config{wikistatedir};
97 eval qq{require IkiWiki::Rcs::$config{rcs}};
99 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
103 require IkiWiki::Rcs::Stub;
106 run_hooks(checkconfig => sub { shift->() });
109 sub loadplugins () { #{{{
110 foreach my $plugin (@{$config{plugin}}) {
111 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
114 error("Failed to load plugin $mod: $@");
117 run_hooks(getopt => sub { shift->() });
118 if (grep /^-/, @ARGV) {
119 print STDERR "Unknown option: $_\n"
120 foreach grep /^-/, @ARGV;
127 print "Content-type: text/html\n\n";
128 print misctemplate("Error", "<p>Error: @_</p>");
130 log_message(error => @_);
135 return unless $config{verbose};
136 log_message(debug => @_);
140 sub log_message ($$) { #{{{
143 if ($config{syslog}) {
146 Sys::Syslog::setlogsock('unix');
147 Sys::Syslog::openlog('ikiwiki', '', 'user');
151 Sys::Syslog::syslog($type, join(" ", @_));
154 elsif (! $config{cgi}) {
162 sub possibly_foolish_untaint ($) { #{{{
164 my ($untainted)=$tainted=~/(.*)/;
168 sub basename ($) { #{{{
175 sub dirname ($) { #{{{
182 sub pagetype ($) { #{{{
185 if ($page =~ /\.([^.]+)$/) {
186 return $1 if exists $hooks{htmlize}{$1};
191 sub pagename ($) { #{{{
194 my $type=pagetype($file);
196 $page=~s/\Q.$type\E*$// if defined $type;
200 sub htmlpage ($) { #{{{
203 return $page.".html";
206 sub srcfile ($) { #{{{
209 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
210 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
211 error("internal error: $file cannot be found");
214 sub readfile ($;$) { #{{{
219 error("cannot read a symlink ($file)");
223 open (IN, $file) || error("failed to read $file: $!");
224 binmode(IN) if ($binary);
230 sub writefile ($$$;$) { #{{{
231 my $file=shift; # can include subdirs
232 my $destdir=shift; # directory to put file in
237 while (length $test) {
238 if (-l "$destdir/$test") {
239 error("cannot write to a symlink ($test)");
241 $test=dirname($test);
244 my $dir=dirname("$destdir/$file");
247 foreach my $s (split(m!/+!, $dir)) {
250 mkdir($d) || error("failed to create directory $d: $!");
255 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
256 binmode(OUT) if ($binary);
261 sub bestlink ($$) { #{{{
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 displaytime ($) { #{{{
336 # strftime doesn't know about encodings, so make sure
337 # its output is properly treated as utf8
338 return decode_utf8(POSIX::strftime(
339 $config{timeformat}, localtime($time)));
342 sub htmllink ($$$;$$$) { #{{{
343 my $lpage=shift; # the page doing the linking
344 my $page=shift; # the page that will contain the link (different for inline)
346 my $noimageinline=shift; # don't turn links into inline html images
347 my $forcesubpage=shift; # force a link to a subpage
348 my $linktext=shift; # set to force the link text to something
351 if (! $forcesubpage) {
352 $bestlink=bestlink($lpage, $link);
355 $bestlink="$lpage/".lc($link);
358 $linktext=pagetitle(basename($link)) unless defined $linktext;
360 return "<span class=\"selflink\">$linktext</span>"
361 if length $bestlink && $page eq $bestlink;
363 # TODO BUG: %renderedfiles may not have it, if the linked to page
364 # was also added and isn't yet rendered! Note that this bug is
365 # masked by the bug that makes all new files be rendered twice.
366 if (! grep { $_ eq $bestlink } values %renderedfiles) {
367 $bestlink=htmlpage($bestlink);
369 if (! grep { $_ eq $bestlink } values %renderedfiles) {
370 return "<span><a href=\"".
371 cgiurl(do => "create", page => lc($link), from => $page).
372 "\">?</a>$linktext</span>"
375 $bestlink=abs2rel($bestlink, dirname($page));
377 if (! $noimageinline && isinlinableimage($bestlink)) {
378 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
380 return "<a href=\"$bestlink\">$linktext</a>";
383 sub htmlize ($$$) { #{{{
388 if (exists $hooks{htmlize}{$type}) {
389 $content=$hooks{htmlize}{$type}{call}->(
395 error("htmlization of $type not supported");
398 run_hooks(sanitize => sub {
408 sub linkify ($$$) { #{{{
409 my $lpage=shift; # the page containing the links
410 my $page=shift; # the page the link will end up on (different for inline)
413 $content =~ s{(\\?)$config{wiki_link_regexp}}{
414 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
415 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
422 sub preprocess ($$$) { #{{{
423 my $page=shift; # the page the data comes from
424 my $destpage=shift; # the page the data will appear in (different for inline)
431 if (length $escape) {
432 return "[[$command $params]]";
434 elsif (exists $hooks{preprocess}{$command}) {
435 # Note: preserve order of params, some plugins may
436 # consider it significant.
438 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
455 push @params, $key, $val;
458 push @params, $val, '';
461 if ($preprocessing{$page}++ > 3) {
462 # Avoid loops of preprocessed pages preprocessing
463 # other pages that preprocess them, etc.
464 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
466 my $ret=$hooks{preprocess}{$command}{call}->(
469 destpage => $destpage,
471 $preprocessing{$page}--;
475 return "[[$command $params]]";
479 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
487 run_hooks(filter => sub {
488 $content=shift->(page => $page, content => $content);
494 sub indexlink () { #{{{
495 return "<a href=\"$config{url}\">$config{wikiname}</a>";
498 sub lockwiki () { #{{{
499 # Take an exclusive lock on the wiki to prevent multiple concurrent
500 # run issues. The lock will be dropped on program exit.
501 if (! -d $config{wikistatedir}) {
502 mkdir($config{wikistatedir});
504 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
505 error ("cannot write to $config{wikistatedir}/lockfile: $!");
506 if (! flock(WIKILOCK, 2 | 4)) {
507 debug("wiki seems to be locked, waiting for lock");
508 my $wait=600; # arbitrary, but don't hang forever to
509 # prevent process pileup
511 return if flock(WIKILOCK, 2 | 4);
514 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
518 sub unlockwiki () { #{{{
522 sub loadindex () { #{{{
523 open (IN, "$config{wikistatedir}/index") || return;
525 $_=possibly_foolish_untaint($_);
529 foreach my $i (split(/ /, $_)) {
530 my ($item, $val)=split(/=/, $i, 2);
531 push @{$items{$item}}, decode_entities($val);
534 next unless exists $items{src}; # skip bad lines for now
536 my $page=pagename($items{src}[0]);
537 if (! $config{rebuild}) {
538 $pagesources{$page}=$items{src}[0];
539 $oldpagemtime{$page}=$items{mtime}[0];
540 $oldlinks{$page}=[@{$items{link}}];
541 $links{$page}=[@{$items{link}}];
542 $depends{$page}=$items{depends}[0] if exists $items{depends};
543 $renderedfiles{$page}=$items{dest}[0];
544 $pagecase{lc $page}=$page;
546 $pagectime{$page}=$items{ctime}[0];
551 sub saveindex () { #{{{
552 run_hooks(savestate => sub { shift->() });
554 if (! -d $config{wikistatedir}) {
555 mkdir($config{wikistatedir});
557 open (OUT, ">$config{wikistatedir}/index") ||
558 error("cannot write to $config{wikistatedir}/index: $!");
559 foreach my $page (keys %oldpagemtime) {
560 next unless $oldpagemtime{$page};
561 my $line="mtime=$oldpagemtime{$page} ".
562 "ctime=$pagectime{$page} ".
563 "src=$pagesources{$page} ".
564 "dest=$renderedfiles{$page}";
565 $line.=" link=$_" foreach @{$links{$page}};
566 if (exists $depends{$page}) {
567 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
569 print OUT $line."\n";
574 sub template_params (@) { #{{{
577 require HTML::Template;
578 return filter => sub {
579 my $text_ref = shift;
580 $$text_ref=&Encode::decode_utf8($$text_ref);
582 filename => "$config{templatedir}/$filename",
583 loop_context_vars => 1,
584 die_on_bad_params => 0,
588 sub template ($;@) { #{{{
589 HTML::Template->new(template_params(@_));
592 sub misctemplate ($$) { #{{{
596 my $template=template("misc.tmpl");
599 indexlink => indexlink(),
600 wikiname => $config{wikiname},
601 pagebody => $pagebody,
602 baseurl => baseurl(),
604 return $template->output;
610 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
611 error "hook requires type, call, and id parameters";
614 $hooks{$param{type}}{$param{id}}=\%param;
617 sub run_hooks ($$) { # {{{
618 # Calls the given sub for each hook of the given type,
619 # passing it the hook function to call.
623 if (exists $hooks{$type}) {
624 foreach my $id (keys %{$hooks{$type}}) {
625 $sub->($hooks{$type}{$id}{call});
630 sub globlist_to_pagespec ($) { #{{{
631 my @globlist=split(' ', shift);
634 foreach my $glob (@globlist) {
635 if ($glob=~/^!(.*)/) {
643 my $spec=join(" or ", @spec);
645 my $skip=join(" and ", @skip);
647 $spec="$skip and ($spec)";
656 sub is_globlist ($) { #{{{
658 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
661 sub safequote ($) { #{{{
667 sub pagespec_merge ($$) { #{{{
671 return $a if $a eq $b;
673 # Support for old-style GlobLists.
674 if (is_globlist($a)) {
675 $a=globlist_to_pagespec($a);
677 if (is_globlist($b)) {
678 $b=globlist_to_pagespec($b);
681 return "($a) or ($b)";
684 sub pagespec_translate ($) { #{{{
685 # This assumes that $page is in scope in the function
686 # that evalulates the translated pagespec code.
689 # Support for old-style GlobLists.
690 if (is_globlist($spec)) {
691 $spec=globlist_to_pagespec($spec);
694 # Convert spec to perl code.
696 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
698 if (lc $word eq "and") {
701 elsif (lc $word eq "or") {
704 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
707 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
708 $code.=" match_$1(\$page, ".safequote($2).")";
711 $code.=" match_glob(\$page, ".safequote($word).")";
718 sub add_depends ($$) { #{{{
722 if (! exists $depends{$page}) {
723 $depends{$page}=$pagespec;
726 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
730 sub pagespec_match ($$) { #{{{
734 return eval pagespec_translate($spec);
737 sub match_glob ($$) { #{{{
741 # turn glob into safe regexp
742 $glob=quotemeta($glob);
746 return $page=~/^$glob$/i;
749 sub match_link ($$) { #{{{
753 my $links = $links{$page} or return undef;
754 foreach my $p (@$links) {
755 return 1 if lc $p eq $link;
760 sub match_backlink ($$) { #{{{
761 match_link(pop, pop);
764 sub match_created_before ($$) { #{{{
768 if (exists $pagectime{$testpage}) {
769 return $pagectime{$page} < $pagectime{$testpage};
776 sub match_created_after ($$) { #{{{
780 if (exists $pagectime{$testpage}) {
781 return $pagectime{$page} > $pagectime{$testpage};
788 sub match_creation_day ($$) { #{{{
789 return ((gmtime($pagectime{shift()}))[3] == shift);
792 sub match_creation_month ($$) { #{{{
793 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
796 sub match_creation_year ($$) { #{{{
797 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);