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
17 %config %links %renderedfiles %pagesources);
23 memoize("pagespec_translate");
25 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
27 sub defaultconfig () { #{{{
28 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$|.arch-ids/|{arch}/)},
29 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
30 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
34 default_pageext => "mdwn",
56 templatedir => "$installdir/share/ikiwiki/templates",
57 underlaydir => "$installdir/share/ikiwiki/basewiki",
61 plugin => [qw{mdwn inline htmlscrubber}],
68 sub checkconfig () { #{{{
69 # locale stuff; avoid LC_ALL since it overrides everything
70 if (defined $ENV{LC_ALL}) {
71 $ENV{LANG} = $ENV{LC_ALL};
74 if (defined $config{locale}) {
76 $ENV{LANG} = $config{locale}
77 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
80 if ($config{w3mmode}) {
81 eval q{use Cwd q{abs_path}};
82 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
83 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
84 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
85 unless $config{cgiurl} =~ m!file:///!;
86 $config{url}="file://".$config{destdir};
89 if ($config{cgi} && ! length $config{url}) {
90 error("Must specify url to wiki with --url when using --cgi\n");
92 if ($config{rss} && ! length $config{url}) {
93 error("Must specify url to wiki with --url when using --rss\n");
96 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
97 unless exists $config{wikistatedir};
100 eval qq{require IkiWiki::Rcs::$config{rcs}};
102 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
106 require IkiWiki::Rcs::Stub;
109 run_hooks(checkconfig => sub { shift->() });
112 sub loadplugins () { #{{{
113 foreach my $plugin (@{$config{plugin}}) {
114 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
117 error("Failed to load plugin $mod: $@");
120 run_hooks(getopt => sub { shift->() });
121 if (grep /^-/, @ARGV) {
122 print STDERR "Unknown option: $_\n"
123 foreach grep /^-/, @ARGV;
130 print "Content-type: text/html\n\n";
131 print misctemplate("Error", "<p>Error: @_</p>");
133 log_message(error => @_);
138 return unless $config{verbose};
139 log_message(debug => @_);
143 sub log_message ($$) { #{{{
146 if ($config{syslog}) {
149 Sys::Syslog::setlogsock('unix');
150 Sys::Syslog::openlog('ikiwiki', '', 'user');
154 Sys::Syslog::syslog($type, join(" ", @_));
157 elsif (! $config{cgi}) {
165 sub possibly_foolish_untaint ($) { #{{{
167 my ($untainted)=$tainted=~/(.*)/;
171 sub basename ($) { #{{{
178 sub dirname ($) { #{{{
185 sub pagetype ($) { #{{{
188 if ($page =~ /\.([^.]+)$/) {
189 return $1 if exists $hooks{htmlize}{$1};
194 sub pagename ($) { #{{{
197 my $type=pagetype($file);
199 $page=~s/\Q.$type\E*$// if defined $type;
203 sub htmlpage ($) { #{{{
206 return $page.".html";
209 sub srcfile ($) { #{{{
212 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
213 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
214 error("internal error: $file cannot be found");
217 sub readfile ($;$) { #{{{
222 error("cannot read a symlink ($file)");
226 open (IN, $file) || error("failed to read $file: $!");
227 binmode(IN) if ($binary);
233 sub writefile ($$$;$) { #{{{
234 my $file=shift; # can include subdirs
235 my $destdir=shift; # directory to put file in
240 while (length $test) {
241 if (-l "$destdir/$test") {
242 error("cannot write to a symlink ($test)");
244 $test=dirname($test);
247 my $dir=dirname("$destdir/$file");
250 foreach my $s (split(m!/+!, $dir)) {
253 mkdir($d) || error("failed to create directory $d: $!");
258 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
259 binmode(OUT) if ($binary);
264 sub bestlink ($$) { #{{{
271 $l.="/" if length $l;
274 if (exists $links{$l}) {
277 elsif (exists $pagecase{lc $l}) {
278 return $pagecase{lc $l};
280 } while $cwd=~s!/?[^/]+$!!;
282 #print STDERR "warning: page $page, broken link: $link\n";
286 sub isinlinableimage ($) { #{{{
289 $file=~/\.(png|gif|jpg|jpeg)$/i;
292 sub pagetitle ($) { #{{{
294 $page=~s/__(\d+)__/&#$1;/g;
299 sub titlepage ($) { #{{{
302 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
306 sub cgiurl (@) { #{{{
309 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
312 sub baseurl (;$) { #{{{
315 return "$config{url}/" if ! defined $page;
318 $page=~s/[^\/]+\//..\//g;
322 sub abs2rel ($$) { #{{{
323 # Work around very innefficient behavior in File::Spec if abs2rel
324 # is passed two relative paths. It's much faster if paths are
325 # absolute! (Debian bug #376658)
330 my $ret=File::Spec->abs2rel($path, $base);
331 $ret=~s/^// if defined $ret;
335 sub displaytime ($) { #{{{
339 # strftime doesn't know about encodings, so make sure
340 # its output is properly treated as utf8
341 return decode_utf8(POSIX::strftime(
342 $config{timeformat}, localtime($time)));
345 sub htmllink ($$$;$$$) { #{{{
346 my $lpage=shift; # the page doing the linking
347 my $page=shift; # the page that will contain the link (different for inline)
349 my $noimageinline=shift; # don't turn links into inline html images
350 my $forcesubpage=shift; # force a link to a subpage
351 my $linktext=shift; # set to force the link text to something
354 if (! $forcesubpage) {
355 $bestlink=bestlink($lpage, $link);
358 $bestlink="$lpage/".lc($link);
361 $linktext=pagetitle(basename($link)) unless defined $linktext;
363 return "<span class=\"selflink\">$linktext</span>"
364 if length $bestlink && $page eq $bestlink;
366 # TODO BUG: %renderedfiles may not have it, if the linked to page
367 # was also added and isn't yet rendered! Note that this bug is
368 # masked by the bug that makes all new files be rendered twice.
369 if (! grep { $_ eq $bestlink } values %renderedfiles) {
370 $bestlink=htmlpage($bestlink);
372 if (! grep { $_ eq $bestlink } values %renderedfiles) {
373 return "<span><a href=\"".
374 cgiurl(do => "create", page => lc($link), from => $page).
375 "\">?</a>$linktext</span>"
378 $bestlink=abs2rel($bestlink, dirname($page));
380 if (! $noimageinline && isinlinableimage($bestlink)) {
381 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
383 return "<a href=\"$bestlink\">$linktext</a>";
386 sub htmlize ($$$) { #{{{
391 if (exists $hooks{htmlize}{$type}) {
392 $content=$hooks{htmlize}{$type}{call}->(
398 error("htmlization of $type not supported");
401 run_hooks(sanitize => sub {
411 sub linkify ($$$) { #{{{
412 my $lpage=shift; # the page containing the links
413 my $page=shift; # the page the link will end up on (different for inline)
416 $content =~ s{(\\?)$config{wiki_link_regexp}}{
417 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
418 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
425 sub preprocess ($$$) { #{{{
426 my $page=shift; # the page the data comes from
427 my $destpage=shift; # the page the data will appear in (different for inline)
434 if (length $escape) {
435 return "[[$command $params]]";
437 elsif (exists $hooks{preprocess}{$command}) {
438 # Note: preserve order of params, some plugins may
439 # consider it significant.
441 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
458 push @params, $key, $val;
461 push @params, $val, '';
464 if ($preprocessing{$page}++ > 3) {
465 # Avoid loops of preprocessed pages preprocessing
466 # other pages that preprocess them, etc.
467 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
469 my $ret=$hooks{preprocess}{$command}{call}->(
472 destpage => $destpage,
474 $preprocessing{$page}--;
478 return "[[$command $params]]";
482 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
490 run_hooks(filter => sub {
491 $content=shift->(page => $page, content => $content);
497 sub indexlink () { #{{{
498 return "<a href=\"$config{url}\">$config{wikiname}</a>";
501 sub lockwiki () { #{{{
502 # Take an exclusive lock on the wiki to prevent multiple concurrent
503 # run issues. The lock will be dropped on program exit.
504 if (! -d $config{wikistatedir}) {
505 mkdir($config{wikistatedir});
507 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
508 error ("cannot write to $config{wikistatedir}/lockfile: $!");
509 if (! flock(WIKILOCK, 2 | 4)) {
510 debug("wiki seems to be locked, waiting for lock");
511 my $wait=600; # arbitrary, but don't hang forever to
512 # prevent process pileup
514 return if flock(WIKILOCK, 2 | 4);
517 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
521 sub unlockwiki () { #{{{
525 sub loadindex () { #{{{
526 open (IN, "$config{wikistatedir}/index") || return;
528 $_=possibly_foolish_untaint($_);
532 foreach my $i (split(/ /, $_)) {
533 my ($item, $val)=split(/=/, $i, 2);
534 push @{$items{$item}}, decode_entities($val);
537 next unless exists $items{src}; # skip bad lines for now
539 my $page=pagename($items{src}[0]);
540 if (! $config{rebuild}) {
541 $pagesources{$page}=$items{src}[0];
542 $oldpagemtime{$page}=$items{mtime}[0];
543 $oldlinks{$page}=[@{$items{link}}];
544 $links{$page}=[@{$items{link}}];
545 $depends{$page}=$items{depends}[0] if exists $items{depends};
546 $renderedfiles{$page}=$items{dest}[0];
547 $pagecase{lc $page}=$page;
549 $pagectime{$page}=$items{ctime}[0];
554 sub saveindex () { #{{{
555 run_hooks(savestate => sub { shift->() });
557 if (! -d $config{wikistatedir}) {
558 mkdir($config{wikistatedir});
560 open (OUT, ">$config{wikistatedir}/index") ||
561 error("cannot write to $config{wikistatedir}/index: $!");
562 foreach my $page (keys %oldpagemtime) {
563 next unless $oldpagemtime{$page};
564 my $line="mtime=$oldpagemtime{$page} ".
565 "ctime=$pagectime{$page} ".
566 "src=$pagesources{$page} ".
567 "dest=$renderedfiles{$page}";
568 $line.=" link=$_" foreach @{$links{$page}};
569 if (exists $depends{$page}) {
570 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
572 print OUT $line."\n";
577 sub template_params (@) { #{{{
580 require HTML::Template;
581 return filter => sub {
582 my $text_ref = shift;
583 $$text_ref=&Encode::decode_utf8($$text_ref);
585 filename => "$config{templatedir}/$filename",
586 loop_context_vars => 1,
587 die_on_bad_params => 0,
591 sub template ($;@) { #{{{
592 HTML::Template->new(template_params(@_));
595 sub misctemplate ($$;@) { #{{{
599 my $template=template("misc.tmpl");
602 indexlink => indexlink(),
603 wikiname => $config{wikiname},
604 pagebody => $pagebody,
605 baseurl => baseurl(),
608 run_hooks(pagetemplate => sub {
609 shift->(page => "", destpage => "", template => $template);
611 return $template->output;
617 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
618 error "hook requires type, call, and id parameters";
621 $hooks{$param{type}}{$param{id}}=\%param;
624 sub run_hooks ($$) { # {{{
625 # Calls the given sub for each hook of the given type,
626 # passing it the hook function to call.
630 if (exists $hooks{$type}) {
631 foreach my $id (keys %{$hooks{$type}}) {
632 $sub->($hooks{$type}{$id}{call});
637 sub globlist_to_pagespec ($) { #{{{
638 my @globlist=split(' ', shift);
641 foreach my $glob (@globlist) {
642 if ($glob=~/^!(.*)/) {
650 my $spec=join(" or ", @spec);
652 my $skip=join(" and ", @skip);
654 $spec="$skip and ($spec)";
663 sub is_globlist ($) { #{{{
665 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
668 sub safequote ($) { #{{{
674 sub pagespec_merge ($$) { #{{{
678 return $a if $a eq $b;
680 # Support for old-style GlobLists.
681 if (is_globlist($a)) {
682 $a=globlist_to_pagespec($a);
684 if (is_globlist($b)) {
685 $b=globlist_to_pagespec($b);
688 return "($a) or ($b)";
691 sub pagespec_translate ($) { #{{{
692 # This assumes that $page is in scope in the function
693 # that evalulates the translated pagespec code.
696 # Support for old-style GlobLists.
697 if (is_globlist($spec)) {
698 $spec=globlist_to_pagespec($spec);
701 # Convert spec to perl code.
703 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
705 if (lc $word eq "and") {
708 elsif (lc $word eq "or") {
711 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
714 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
715 $code.=" match_$1(\$page, ".safequote($2).")";
718 $code.=" match_glob(\$page, ".safequote($word).")";
725 sub add_depends ($$) { #{{{
729 if (! exists $depends{$page}) {
730 $depends{$page}=$pagespec;
733 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
737 sub pagespec_match ($$) { #{{{
741 return eval pagespec_translate($spec);
744 sub match_glob ($$) { #{{{
748 # turn glob into safe regexp
749 $glob=quotemeta($glob);
753 return $page=~/^$glob$/i;
756 sub match_link ($$) { #{{{
760 my $links = $links{$page} or return undef;
761 foreach my $p (@$links) {
762 return 1 if lc $p eq $link;
767 sub match_backlink ($$) { #{{{
768 match_link(pop, pop);
771 sub match_created_before ($$) { #{{{
775 if (exists $pagectime{$testpage}) {
776 return $pagectime{$page} < $pagectime{$testpage};
783 sub match_created_after ($$) { #{{{
787 if (exists $pagectime{$testpage}) {
788 return $pagectime{$page} > $pagectime{$testpage};
795 sub match_creation_day ($$) { #{{{
796 return ((gmtime($pagectime{shift()}))[3] == shift);
799 sub match_creation_month ($$) { #{{{
800 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
803 sub match_creation_year ($$) { #{{{
804 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);