8 use open qw{:utf8 :std};
10 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
11 %renderedfiles %oldrenderedfiles %pagesources %depends %hooks
14 use Exporter q{import};
15 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
16 bestlink htmllink readfile writefile pagetype srcfile pagename
17 displaytime will_render gettext
18 %config %links %renderedfiles %pagesources);
19 our $VERSION = 1.01; # plugin interface version
24 memoize("pagespec_translate");
25 memoize("file_pruned");
27 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 sub defaultconfig () { #{{{
31 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./, qr/\.x?html?$/,
32 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
33 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
34 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
35 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
39 default_pageext => "mdwn",
62 templatedir => "$installdir/share/ikiwiki/templates",
63 underlaydir => "$installdir/share/ikiwiki/basewiki",
67 plugin => [qw{mdwn inline htmlscrubber passwordauth}],
75 sub checkconfig () { #{{{
76 # locale stuff; avoid LC_ALL since it overrides everything
77 if (defined $ENV{LC_ALL}) {
78 $ENV{LANG} = $ENV{LC_ALL};
81 if (defined $config{locale}) {
84 $ENV{LANG} = $config{locale}
85 if POSIX::setlocale(&POSIX::LC_ALL, $config{locale});
88 if ($config{w3mmode}) {
89 eval q{use Cwd q{abs_path}};
91 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
92 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
93 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
94 unless $config{cgiurl} =~ m!file:///!;
95 $config{url}="file://".$config{destdir};
98 if ($config{cgi} && ! length $config{url}) {
99 error(gettext("Must specify url to wiki with --url when using --cgi"));
102 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
103 unless exists $config{wikistatedir};
106 eval qq{require IkiWiki::Rcs::$config{rcs}};
108 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
112 require IkiWiki::Rcs::Stub;
115 run_hooks(checkconfig => sub { shift->() });
118 sub loadplugins () { #{{{
119 loadplugin($_) foreach @{$config{plugin}};
121 run_hooks(getopt => sub { shift->() });
122 if (grep /^-/, @ARGV) {
123 print STDERR "Unknown option: $_\n"
124 foreach grep /^-/, @ARGV;
129 sub loadplugin ($) { #{{{
132 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
134 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
137 error("Failed to load plugin $mod: $@");
143 print "Content-type: text/html\n\n";
144 print misctemplate(gettext("Error"),
145 "<p>".gettext("Error").": @_</p>");
147 log_message(error => @_);
152 return unless $config{verbose};
153 log_message(debug => @_);
157 sub log_message ($$) { #{{{
160 if ($config{syslog}) {
163 Sys::Syslog::setlogsock('unix');
164 Sys::Syslog::openlog('ikiwiki', '', 'user');
168 Sys::Syslog::syslog($type, join(" ", @_));
171 elsif (! $config{cgi}) {
179 sub possibly_foolish_untaint ($) { #{{{
181 my ($untainted)=$tainted=~/(.*)/;
185 sub basename ($) { #{{{
192 sub dirname ($) { #{{{
199 sub pagetype ($) { #{{{
202 if ($page =~ /\.([^.]+)$/) {
203 return $1 if exists $hooks{htmlize}{$1};
208 sub pagename ($) { #{{{
211 my $type=pagetype($file);
213 $page=~s/\Q.$type\E*$// if defined $type;
217 sub htmlpage ($) { #{{{
220 return $page.".html";
223 sub srcfile ($) { #{{{
226 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
227 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
228 error("internal error: $file cannot be found");
231 sub readfile ($;$) { #{{{
236 error("cannot read a symlink ($file)");
240 open (IN, $file) || error("failed to read $file: $!");
241 binmode(IN) if ($binary);
247 sub writefile ($$$;$) { #{{{
248 my $file=shift; # can include subdirs
249 my $destdir=shift; # directory to put file in
254 while (length $test) {
255 if (-l "$destdir/$test") {
256 error("cannot write to a symlink ($test)");
258 $test=dirname($test);
261 my $dir=dirname("$destdir/$file");
264 foreach my $s (split(m!/+!, $dir)) {
267 mkdir($d) || error("failed to create directory $d: $!");
272 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
273 binmode(OUT) if ($binary);
279 sub will_render ($$;$) { #{{{
284 # Important security check.
285 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
286 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
287 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
290 if (! $clear || $cleared{$page}) {
291 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
294 $renderedfiles{$page}=[$dest];
299 sub bestlink ($$) { #{{{
304 if ($link=~s/^\/+//) {
311 $l.="/" if length $l;
314 if (exists $links{$l}) {
317 elsif (exists $pagecase{lc $l}) {
318 return $pagecase{lc $l};
320 } while $cwd=~s!/?[^/]+$!!;
322 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
323 return "$config{userdir}/".lc($link);
326 #print STDERR "warning: page $page, broken link: $link\n";
330 sub isinlinableimage ($) { #{{{
333 $file=~/\.(png|gif|jpg|jpeg)$/i;
336 sub pagetitle ($;$) { #{{{
341 $page=~s/__(\d+)__/chr($1)/eg;
344 $page=~s/__(\d+)__/&#$1;/g;
351 sub titlepage ($) { #{{{
354 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
358 sub cgiurl (@) { #{{{
361 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
364 sub baseurl (;$) { #{{{
367 return "$config{url}/" if ! defined $page;
370 $page=~s/[^\/]+\//..\//g;
374 sub abs2rel ($$) { #{{{
375 # Work around very innefficient behavior in File::Spec if abs2rel
376 # is passed two relative paths. It's much faster if paths are
377 # absolute! (Debian bug #376658; fixed in debian unstable now)
382 my $ret=File::Spec->abs2rel($path, $base);
383 $ret=~s/^// if defined $ret;
387 sub displaytime ($) { #{{{
392 # strftime doesn't know about encodings, so make sure
393 # its output is properly treated as utf8
394 return decode_utf8(POSIX::strftime(
395 $config{timeformat}, localtime($time)));
398 sub htmllink ($$$;$$$) { #{{{
399 my $lpage=shift; # the page doing the linking
400 my $page=shift; # the page that will contain the link (different for inline)
402 my $noimageinline=shift; # don't turn links into inline html images
403 my $forcesubpage=shift; # force a link to a subpage
404 my $linktext=shift; # set to force the link text to something
407 if (! $forcesubpage) {
408 $bestlink=bestlink($lpage, $link);
411 $bestlink="$lpage/".lc($link);
414 $linktext=pagetitle(basename($link)) unless defined $linktext;
416 return "<span class=\"selflink\">$linktext</span>"
417 if length $bestlink && $page eq $bestlink;
419 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
420 $bestlink=htmlpage($bestlink);
422 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
423 return $linktext unless length $config{cgiurl};
424 return "<span><a href=\"".
425 cgiurl(do => "create", page => lc($link), from => $page).
426 "\">?</a>$linktext</span>"
429 $bestlink=abs2rel($bestlink, dirname($page));
431 if (! $noimageinline && isinlinableimage($bestlink)) {
432 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
434 return "<a href=\"$bestlink\">$linktext</a>";
437 sub htmlize ($$$) { #{{{
442 if (exists $hooks{htmlize}{$type}) {
443 $content=$hooks{htmlize}{$type}{call}->(
449 error("htmlization of $type not supported");
452 run_hooks(sanitize => sub {
462 sub linkify ($$$) { #{{{
463 my $lpage=shift; # the page containing the links
464 my $page=shift; # the page the link will end up on (different for inline)
467 $content =~ s{(\\?)$config{wiki_link_regexp}}{
468 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
469 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
476 sub preprocess ($$$;$) { #{{{
477 my $page=shift; # the page the data comes from
478 my $destpage=shift; # the page the data will appear in (different for inline)
486 if (length $escape) {
487 return "[[$command $params]]";
489 elsif (exists $hooks{preprocess}{$command}) {
490 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
491 # Note: preserve order of params, some plugins may
492 # consider it significant.
494 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
511 push @params, $key, $val;
514 push @params, $val, '';
517 if ($preprocessing{$page}++ > 3) {
518 # Avoid loops of preprocessed pages preprocessing
519 # other pages that preprocess them, etc.
520 #translators: The first parameter is a
521 #translators: preprocessor directive name,
522 #translators: the second a page name, the
523 #translators: third a number.
524 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
525 $command, $page, $preprocessing{$page}).
528 my $ret=$hooks{preprocess}{$command}{call}->(
531 destpage => $destpage,
533 $preprocessing{$page}--;
537 return "[[$command $params]]";
541 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
545 sub filter ($$) { #{{{
549 run_hooks(filter => sub {
550 $content=shift->(page => $page, content => $content);
556 sub indexlink () { #{{{
557 return "<a href=\"$config{url}\">$config{wikiname}</a>";
560 sub lockwiki () { #{{{
561 # Take an exclusive lock on the wiki to prevent multiple concurrent
562 # run issues. The lock will be dropped on program exit.
563 if (! -d $config{wikistatedir}) {
564 mkdir($config{wikistatedir});
566 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
567 error ("cannot write to $config{wikistatedir}/lockfile: $!");
568 if (! flock(WIKILOCK, 2 | 4)) {
569 debug("wiki seems to be locked, waiting for lock");
570 my $wait=600; # arbitrary, but don't hang forever to
571 # prevent process pileup
573 return if flock(WIKILOCK, 2 | 4);
576 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
580 sub unlockwiki () { #{{{
584 sub loadindex () { #{{{
585 open (IN, "$config{wikistatedir}/index") || return;
587 $_=possibly_foolish_untaint($_);
592 foreach my $i (split(/ /, $_)) {
593 my ($item, $val)=split(/=/, $i, 2);
594 push @{$items{$item}}, decode_entities($val);
597 next unless exists $items{src}; # skip bad lines for now
599 my $page=pagename($items{src}[0]);
600 if (! $config{rebuild}) {
601 $pagesources{$page}=$items{src}[0];
602 $oldpagemtime{$page}=$items{mtime}[0];
603 $oldlinks{$page}=[@{$items{link}}];
604 $links{$page}=[@{$items{link}}];
605 $depends{$page}=$items{depends}[0] if exists $items{depends};
606 $renderedfiles{$page}=[@{$items{dest}}];
607 $oldrenderedfiles{$page}=[@{$items{dest}}];
608 $pagecase{lc $page}=$page;
610 $pagectime{$page}=$items{ctime}[0];
615 sub saveindex () { #{{{
616 run_hooks(savestate => sub { shift->() });
618 if (! -d $config{wikistatedir}) {
619 mkdir($config{wikistatedir});
621 open (OUT, ">$config{wikistatedir}/index") ||
622 error("cannot write to $config{wikistatedir}/index: $!");
623 foreach my $page (keys %oldpagemtime) {
624 next unless $oldpagemtime{$page};
625 my $line="mtime=$oldpagemtime{$page} ".
626 "ctime=$pagectime{$page} ".
627 "src=$pagesources{$page}";
628 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
630 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
631 if (exists $depends{$page}) {
632 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
634 print OUT $line."\n";
639 sub template_file ($) { #{{{
642 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
643 return "$dir/$template" if -e "$dir/$template";
648 sub template_params (@) { #{{{
649 my $filename=template_file(shift);
651 if (! defined $filename) {
656 require HTML::Template;
659 my $text_ref = shift;
660 $$text_ref=&Encode::decode_utf8($$text_ref);
662 filename => $filename,
663 loop_context_vars => 1,
664 die_on_bad_params => 0,
667 return wantarray ? @ret : {@ret};
670 sub template ($;@) { #{{{
671 HTML::Template->new(template_params(@_));
674 sub misctemplate ($$;@) { #{{{
678 my $template=template("misc.tmpl");
681 indexlink => indexlink(),
682 wikiname => $config{wikiname},
683 pagebody => $pagebody,
684 baseurl => baseurl(),
687 run_hooks(pagetemplate => sub {
688 shift->(page => "", destpage => "", template => $template);
690 return $template->output;
696 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
697 error "hook requires type, call, and id parameters";
700 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
702 $hooks{$param{type}}{$param{id}}=\%param;
705 sub run_hooks ($$) { # {{{
706 # Calls the given sub for each hook of the given type,
707 # passing it the hook function to call.
711 if (exists $hooks{$type}) {
713 foreach my $id (keys %{$hooks{$type}}) {
714 if ($hooks{$type}{$id}{last}) {
718 $sub->($hooks{$type}{$id}{call});
720 foreach my $id (@deferred) {
721 $sub->($hooks{$type}{$id}{call});
726 sub globlist_to_pagespec ($) { #{{{
727 my @globlist=split(' ', shift);
730 foreach my $glob (@globlist) {
731 if ($glob=~/^!(.*)/) {
739 my $spec=join(" or ", @spec);
741 my $skip=join(" and ", @skip);
743 $spec="$skip and ($spec)";
752 sub is_globlist ($) { #{{{
754 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
757 sub safequote ($) { #{{{
763 sub pagespec_merge ($$) { #{{{
767 return $a if $a eq $b;
769 # Support for old-style GlobLists.
770 if (is_globlist($a)) {
771 $a=globlist_to_pagespec($a);
773 if (is_globlist($b)) {
774 $b=globlist_to_pagespec($b);
777 return "($a) or ($b)";
780 sub pagespec_translate ($) { #{{{
781 # This assumes that $page is in scope in the function
782 # that evalulates the translated pagespec code.
785 # Support for old-style GlobLists.
786 if (is_globlist($spec)) {
787 $spec=globlist_to_pagespec($spec);
790 # Convert spec to perl code.
792 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
794 if (lc $word eq "and") {
797 elsif (lc $word eq "or") {
800 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
803 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
804 $code.=" match_$1(\$page, ".safequote($2).")";
807 $code.=" match_glob(\$page, ".safequote($word).")";
814 sub add_depends ($$) { #{{{
818 if (! exists $depends{$page}) {
819 $depends{$page}=$pagespec;
822 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
826 sub file_pruned ($$) { #{{{
828 my $file=File::Spec->canonpath(shift);
829 my $base=File::Spec->canonpath(shift);
830 $file=~s#^\Q$base\E/*##;
832 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
838 # Only use gettext in the rare cases it's needed.
839 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
840 if (! $gettext_obj) {
842 use Locale::gettext q{textdomain};
843 Locale::gettext->domain('ikiwiki')
851 return $gettext_obj->get(shift);
858 sub pagespec_match ($$) { #{{{
862 return eval pagespec_translate($spec);
865 sub match_glob ($$) { #{{{
869 # turn glob into safe regexp
870 $glob=quotemeta($glob);
874 return $page=~/^$glob$/i;
877 sub match_link ($$) { #{{{
881 my $links = $links{$page} or return undef;
882 foreach my $p (@$links) {
883 return 1 if lc $p eq $link;
888 sub match_backlink ($$) { #{{{
889 match_link(pop, pop);
892 sub match_created_before ($$) { #{{{
896 if (exists $pagectime{$testpage}) {
897 return $pagectime{$page} < $pagectime{$testpage};
904 sub match_created_after ($$) { #{{{
908 if (exists $pagectime{$testpage}) {
909 return $pagectime{$page} > $pagectime{$testpage};
916 sub match_creation_day ($$) { #{{{
917 return ((gmtime($pagectime{shift()}))[3] == shift);
920 sub match_creation_month ($$) { #{{{
921 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
924 sub match_creation_year ($$) { #{{{
925 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);