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);
22 memoize("pagespec_translate");
24 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
26 sub defaultconfig () { #{{{
27 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$)},
28 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
29 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
33 default_pageext => "mdwn",
55 templatedir => "$installdir/share/ikiwiki/templates",
56 underlaydir => "$installdir/share/ikiwiki/basewiki",
60 plugin => [qw{mdwn inline htmlscrubber}],
66 sub checkconfig () { #{{{
67 # locale stuff; avoid LC_ALL since it overrides everything
68 if (defined $ENV{LC_ALL}) {
69 $ENV{LANG} = $ENV{LC_ALL};
72 if (defined $config{locale}) {
74 $ENV{LANG} = $config{locale}
75 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
78 if ($config{w3mmode}) {
79 eval q{use Cwd q{abs_path}};
80 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
81 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
82 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
83 unless $config{cgiurl} =~ m!file:///!;
84 $config{url}="file://".$config{destdir};
87 if ($config{cgi} && ! length $config{url}) {
88 error("Must specify url to wiki with --url when using --cgi\n");
90 if ($config{rss} && ! length $config{url}) {
91 error("Must specify url to wiki with --url when using --rss\n");
94 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
95 unless exists $config{wikistatedir};
98 eval qq{require IkiWiki::Rcs::$config{rcs}};
100 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
104 require IkiWiki::Rcs::Stub;
107 run_hooks(checkconfig => sub { shift->() });
110 sub loadplugins () { #{{{
111 foreach my $plugin (@{$config{plugin}}) {
112 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
115 error("Failed to load plugin $mod: $@");
118 run_hooks(getopt => sub { shift->() });
119 if (grep /^-/, @ARGV) {
120 print STDERR "Unknown option: $_\n"
121 foreach grep /^-/, @ARGV;
128 print "Content-type: text/html\n\n";
129 print misctemplate("Error", "<p>Error: @_</p>");
131 log_message(error => @_);
136 return unless $config{verbose};
137 log_message(debug => @_);
141 sub log_message ($$) { #{{{
144 if ($config{syslog}) {
147 Sys::Syslog::setlogsock('unix');
148 Sys::Syslog::openlog('ikiwiki', '', 'user');
152 Sys::Syslog::syslog($type, join(" ", @_));
155 elsif (! $config{cgi}) {
163 sub possibly_foolish_untaint ($) { #{{{
165 my ($untainted)=$tainted=~/(.*)/;
169 sub basename ($) { #{{{
176 sub dirname ($) { #{{{
183 sub pagetype ($) { #{{{
186 if ($page =~ /\.([^.]+)$/) {
187 return $1 if exists $hooks{htmlize}{$1};
192 sub pagename ($) { #{{{
195 my $type=pagetype($file);
197 $page=~s/\Q.$type\E*$// if defined $type;
201 sub htmlpage ($) { #{{{
204 return $page.".html";
207 sub srcfile ($) { #{{{
210 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
211 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
212 error("internal error: $file cannot be found");
215 sub readfile ($;$) { #{{{
220 error("cannot read a symlink ($file)");
224 open (IN, $file) || error("failed to read $file: $!");
225 binmode(IN) if ($binary);
231 sub writefile ($$$;$) { #{{{
232 my $file=shift; # can include subdirs
233 my $destdir=shift; # directory to put file in
238 while (length $test) {
239 if (-l "$destdir/$test") {
240 error("cannot write to a symlink ($test)");
242 $test=dirname($test);
245 my $dir=dirname("$destdir/$file");
248 foreach my $s (split(m!/+!, $dir)) {
251 mkdir($d) || error("failed to create directory $d: $!");
256 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
257 binmode(OUT) if ($binary);
262 sub bestlink ($$) { #{{{
269 $l.="/" if length $l;
272 if (exists $links{$l}) {
275 elsif (exists $pagecase{lc $l}) {
276 return $pagecase{lc $l};
278 } while $cwd=~s!/?[^/]+$!!;
280 #print STDERR "warning: page $page, broken link: $link\n";
284 sub isinlinableimage ($) { #{{{
287 $file=~/\.(png|gif|jpg|jpeg)$/i;
290 sub pagetitle ($) { #{{{
292 $page=~s/__(\d+)__/&#$1;/g;
297 sub titlepage ($) { #{{{
300 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
304 sub cgiurl (@) { #{{{
307 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
310 sub baseurl (;$) { #{{{
313 return "$config{url}/" if ! defined $page;
316 $page=~s/[^\/]+\//..\//g;
320 sub abs2rel ($$) { #{{{
321 # Work around very innefficient behavior in File::Spec if abs2rel
322 # is passed two relative paths. It's much faster if paths are
323 # absolute! (Debian bug #376658)
328 my $ret=File::Spec->abs2rel($path, $base);
329 $ret=~s/^// if defined $ret;
333 sub displaytime ($) { #{{{
337 # strftime doesn't know about encodings, so make sure
338 # its output is properly treated as utf8
339 return decode_utf8(POSIX::strftime(
340 $config{timeformat}, localtime($time)));
343 sub htmllink ($$$;$$$) { #{{{
344 my $lpage=shift; # the page doing the linking
345 my $page=shift; # the page that will contain the link (different for inline)
347 my $noimageinline=shift; # don't turn links into inline html images
348 my $forcesubpage=shift; # force a link to a subpage
349 my $linktext=shift; # set to force the link text to something
352 if (! $forcesubpage) {
353 $bestlink=bestlink($lpage, $link);
356 $bestlink="$lpage/".lc($link);
359 $linktext=pagetitle(basename($link)) unless defined $linktext;
361 return "<span class=\"selflink\">$linktext</span>"
362 if length $bestlink && $page eq $bestlink;
364 # TODO BUG: %renderedfiles may not have it, if the linked to page
365 # was also added and isn't yet rendered! Note that this bug is
366 # masked by the bug that makes all new files be rendered twice.
367 if (! grep { $_ eq $bestlink } values %renderedfiles) {
368 $bestlink=htmlpage($bestlink);
370 if (! grep { $_ eq $bestlink } values %renderedfiles) {
371 return "<span><a href=\"".
372 cgiurl(do => "create", page => lc($link), from => $page).
373 "\">?</a>$linktext</span>"
376 $bestlink=abs2rel($bestlink, dirname($page));
378 if (! $noimageinline && isinlinableimage($bestlink)) {
379 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
381 return "<a href=\"$bestlink\">$linktext</a>";
384 sub htmlize ($$$) { #{{{
389 if (exists $hooks{htmlize}{$type}) {
390 $content=$hooks{htmlize}{$type}{call}->(
396 error("htmlization of $type not supported");
399 run_hooks(sanitize => sub {
409 sub linkify ($$$) { #{{{
410 my $lpage=shift; # the page containing the links
411 my $page=shift; # the page the link will end up on (different for inline)
414 $content =~ s{(\\?)$config{wiki_link_regexp}}{
415 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
416 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
423 sub preprocess ($$$) { #{{{
424 my $page=shift; # the page the data comes from
425 my $destpage=shift; # the page the data will appear in (different for inline)
432 if (length $escape) {
433 return "[[$command $params]]";
435 elsif (exists $hooks{preprocess}{$command}) {
436 # Note: preserve order of params, some plugins may
437 # consider it significant.
439 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
456 push @params, $key, $val;
459 push @params, $val, '';
462 if ($preprocessing{$page}++ > 3) {
463 # Avoid loops of preprocessed pages preprocessing
464 # other pages that preprocess them, etc.
465 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
467 my $ret=$hooks{preprocess}{$command}{call}->(
470 destpage => $destpage,
472 $preprocessing{$page}--;
476 return "[[$command $params]]";
480 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
488 run_hooks(filter => sub {
489 $content=shift->(page => $page, content => $content);
495 sub indexlink () { #{{{
496 return "<a href=\"$config{url}\">$config{wikiname}</a>";
499 sub lockwiki () { #{{{
500 # Take an exclusive lock on the wiki to prevent multiple concurrent
501 # run issues. The lock will be dropped on program exit.
502 if (! -d $config{wikistatedir}) {
503 mkdir($config{wikistatedir});
505 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
506 error ("cannot write to $config{wikistatedir}/lockfile: $!");
507 if (! flock(WIKILOCK, 2 | 4)) {
508 debug("wiki seems to be locked, waiting for lock");
509 my $wait=600; # arbitrary, but don't hang forever to
510 # prevent process pileup
512 return if flock(WIKILOCK, 2 | 4);
515 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
519 sub unlockwiki () { #{{{
523 sub loadindex () { #{{{
524 open (IN, "$config{wikistatedir}/index") || return;
526 $_=possibly_foolish_untaint($_);
530 foreach my $i (split(/ /, $_)) {
531 my ($item, $val)=split(/=/, $i, 2);
532 push @{$items{$item}}, decode_entities($val);
535 next unless exists $items{src}; # skip bad lines for now
537 my $page=pagename($items{src}[0]);
538 if (! $config{rebuild}) {
539 $pagesources{$page}=$items{src}[0];
540 $oldpagemtime{$page}=$items{mtime}[0];
541 $oldlinks{$page}=[@{$items{link}}];
542 $links{$page}=[@{$items{link}}];
543 $depends{$page}=$items{depends}[0] if exists $items{depends};
544 $renderedfiles{$page}=$items{dest}[0];
545 $pagecase{lc $page}=$page;
547 $pagectime{$page}=$items{ctime}[0];
552 sub saveindex () { #{{{
553 run_hooks(savestate => sub { shift->() });
555 if (! -d $config{wikistatedir}) {
556 mkdir($config{wikistatedir});
558 open (OUT, ">$config{wikistatedir}/index") ||
559 error("cannot write to $config{wikistatedir}/index: $!");
560 foreach my $page (keys %oldpagemtime) {
561 next unless $oldpagemtime{$page};
562 my $line="mtime=$oldpagemtime{$page} ".
563 "ctime=$pagectime{$page} ".
564 "src=$pagesources{$page} ".
565 "dest=$renderedfiles{$page}";
566 $line.=" link=$_" foreach @{$links{$page}};
567 if (exists $depends{$page}) {
568 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
570 print OUT $line."\n";
575 sub template_params (@) { #{{{
578 require HTML::Template;
579 return filter => sub {
580 my $text_ref = shift;
581 $$text_ref=&Encode::decode_utf8($$text_ref);
583 filename => "$config{templatedir}/$filename",
584 loop_context_vars => 1,
585 die_on_bad_params => 0,
589 sub template ($;@) { #{{{
590 HTML::Template->new(template_params(@_));
593 sub misctemplate ($$) { #{{{
597 my $template=template("misc.tmpl");
600 indexlink => indexlink(),
601 wikiname => $config{wikiname},
602 pagebody => $pagebody,
603 baseurl => baseurl(),
605 return $template->output;
611 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
612 error "hook requires type, call, and id parameters";
615 $hooks{$param{type}}{$param{id}}=\%param;
618 sub run_hooks ($$) { # {{{
619 # Calls the given sub for each hook of the given type,
620 # passing it the hook function to call.
624 if (exists $hooks{$type}) {
625 foreach my $id (keys %{$hooks{$type}}) {
626 $sub->($hooks{$type}{$id}{call});
631 sub globlist_to_pagespec ($) { #{{{
632 my @globlist=split(' ', shift);
635 foreach my $glob (@globlist) {
636 if ($glob=~/^!(.*)/) {
644 my $spec=join(" or ", @spec);
646 my $skip=join(" and ", @skip);
648 $spec="$skip and ($spec)";
657 sub is_globlist ($) { #{{{
659 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
662 sub safequote ($) { #{{{
668 sub pagespec_merge ($$) { #{{{
672 return $a if $a eq $b;
674 # Support for old-style GlobLists.
675 if (is_globlist($a)) {
676 $a=globlist_to_pagespec($a);
678 if (is_globlist($b)) {
679 $b=globlist_to_pagespec($b);
682 return "($a) or ($b)";
685 sub pagespec_translate ($) { #{{{
686 # This assumes that $page is in scope in the function
687 # that evalulates the translated pagespec code.
690 # Support for old-style GlobLists.
691 if (is_globlist($spec)) {
692 $spec=globlist_to_pagespec($spec);
695 # Convert spec to perl code.
697 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
699 if (lc $word eq "and") {
702 elsif (lc $word eq "or") {
705 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
708 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
709 $code.=" match_$1(\$page, ".safequote($2).")";
712 $code.=" match_glob(\$page, ".safequote($word).")";
719 sub add_depends ($$) { #{{{
723 if (! exists $depends{$page}) {
724 $depends{$page}=$pagespec;
727 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
731 sub pagespec_match ($$) { #{{{
735 return eval pagespec_translate($spec);
738 sub match_glob ($$) { #{{{
742 # turn glob into safe regexp
743 $glob=quotemeta($glob);
747 return $page=~/^$glob$/i;
750 sub match_link ($$) { #{{{
754 my $links = $links{$page} or return undef;
755 foreach my $p (@$links) {
756 return 1 if lc $p eq $link;
761 sub match_backlink ($$) { #{{{
762 match_link(pop, pop);
765 sub match_created_before ($$) { #{{{
769 if (exists $pagectime{$testpage}) {
770 return $pagectime{$page} < $pagectime{$testpage};
777 sub match_created_after ($$) { #{{{
781 if (exists $pagectime{$testpage}) {
782 return $pagectime{$page} > $pagectime{$testpage};
789 sub match_creation_day ($$) { #{{{
790 return ((gmtime($pagectime{shift()}))[3] == shift);
793 sub match_creation_month ($$) { #{{{
794 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
797 sub match_creation_year ($$) { #{{{
798 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);