8 use open qw{:utf8 :std};
10 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
11 %renderedfiles %oldrenderedfiles %pagesources %depends %hooks
12 %forcerebuild $gettext_obj};
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",
59 gitorigin_branch => "origin",
60 gitmaster_branch => "master",
64 templatedir => "$installdir/share/ikiwiki/templates",
65 underlaydir => "$installdir/share/ikiwiki/basewiki",
69 plugin => [qw{mdwn inline htmlscrubber passwordauth}],
77 sub checkconfig () { #{{{
78 # locale stuff; avoid LC_ALL since it overrides everything
79 if (defined $ENV{LC_ALL}) {
80 $ENV{LANG} = $ENV{LC_ALL};
83 if (defined $config{locale}) {
86 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
87 $ENV{LANG}=$config{locale};
92 if ($config{w3mmode}) {
93 eval q{use Cwd q{abs_path}};
95 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
96 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
97 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
98 unless $config{cgiurl} =~ m!file:///!;
99 $config{url}="file://".$config{destdir};
102 if ($config{cgi} && ! length $config{url}) {
103 error(gettext("Must specify url to wiki with --url when using --cgi"));
106 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
107 unless exists $config{wikistatedir};
110 eval qq{require IkiWiki::Rcs::$config{rcs}};
112 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
116 require IkiWiki::Rcs::Stub;
119 run_hooks(checkconfig => sub { shift->() });
122 sub loadplugins () { #{{{
123 loadplugin($_) foreach @{$config{plugin}};
125 run_hooks(getopt => sub { shift->() });
126 if (grep /^-/, @ARGV) {
127 print STDERR "Unknown option: $_\n"
128 foreach grep /^-/, @ARGV;
133 sub loadplugin ($) { #{{{
136 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
138 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
141 error("Failed to load plugin $mod: $@");
147 print "Content-type: text/html\n\n";
148 print misctemplate(gettext("Error"),
149 "<p>".gettext("Error").": @_</p>");
151 log_message(error => @_);
156 return unless $config{verbose};
157 log_message(debug => @_);
161 sub log_message ($$) { #{{{
164 if ($config{syslog}) {
167 Sys::Syslog::setlogsock('unix');
168 Sys::Syslog::openlog('ikiwiki', '', 'user');
172 Sys::Syslog::syslog($type, join(" ", @_));
175 elsif (! $config{cgi}) {
183 sub possibly_foolish_untaint ($) { #{{{
185 my ($untainted)=$tainted=~/(.*)/;
189 sub basename ($) { #{{{
196 sub dirname ($) { #{{{
203 sub pagetype ($) { #{{{
206 if ($page =~ /\.([^.]+)$/) {
207 return $1 if exists $hooks{htmlize}{$1};
212 sub pagename ($) { #{{{
215 my $type=pagetype($file);
217 $page=~s/\Q.$type\E*$// if defined $type;
221 sub htmlpage ($) { #{{{
224 return $page.".html";
227 sub srcfile ($) { #{{{
230 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
231 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
232 error("internal error: $file cannot be found");
235 sub readfile ($;$) { #{{{
240 error("cannot read a symlink ($file)");
244 open (IN, $file) || error("failed to read $file: $!");
245 binmode(IN) if ($binary);
251 sub writefile ($$$;$) { #{{{
252 my $file=shift; # can include subdirs
253 my $destdir=shift; # directory to put file in
258 while (length $test) {
259 if (-l "$destdir/$test") {
260 error("cannot write to a symlink ($test)");
262 $test=dirname($test);
265 my $dir=dirname("$destdir/$file");
268 foreach my $s (split(m!/+!, $dir)) {
271 mkdir($d) || error("failed to create directory $d: $!");
276 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
277 binmode(OUT) if ($binary);
283 sub will_render ($$;$) { #{{{
288 # Important security check.
289 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
290 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
291 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
294 if (! $clear || $cleared{$page}) {
295 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
298 $renderedfiles{$page}=[$dest];
303 sub bestlink ($$) { #{{{
308 if ($link=~s/^\/+//) {
315 $l.="/" if length $l;
318 if (exists $links{$l}) {
321 elsif (exists $pagecase{lc $l}) {
322 return $pagecase{lc $l};
324 } while $cwd=~s!/?[^/]+$!!;
326 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
327 return "$config{userdir}/".lc($link);
330 #print STDERR "warning: page $page, broken link: $link\n";
334 sub isinlinableimage ($) { #{{{
337 $file=~/\.(png|gif|jpg|jpeg)$/i;
340 sub pagetitle ($;$) { #{{{
345 $page=~s/__(\d+)__/chr($1)/eg;
348 $page=~s/__(\d+)__/&#$1;/g;
355 sub titlepage ($) { #{{{
358 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
362 sub cgiurl (@) { #{{{
365 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
368 sub baseurl (;$) { #{{{
371 return "$config{url}/" if ! defined $page;
374 $page=~s/[^\/]+\//..\//g;
378 sub abs2rel ($$) { #{{{
379 # Work around very innefficient behavior in File::Spec if abs2rel
380 # is passed two relative paths. It's much faster if paths are
381 # absolute! (Debian bug #376658; fixed in debian unstable now)
386 my $ret=File::Spec->abs2rel($path, $base);
387 $ret=~s/^// if defined $ret;
391 sub displaytime ($) { #{{{
396 # strftime doesn't know about encodings, so make sure
397 # its output is properly treated as utf8
398 return decode_utf8(POSIX::strftime(
399 $config{timeformat}, localtime($time)));
402 sub htmllink ($$$;$$$) { #{{{
403 my $lpage=shift; # the page doing the linking
404 my $page=shift; # the page that will contain the link (different for inline)
406 my $noimageinline=shift; # don't turn links into inline html images
407 my $forcesubpage=shift; # force a link to a subpage
408 my $linktext=shift; # set to force the link text to something
411 if (! $forcesubpage) {
412 $bestlink=bestlink($lpage, $link);
415 $bestlink="$lpage/".lc($link);
418 $linktext=pagetitle(basename($link)) unless defined $linktext;
420 return "<span class=\"selflink\">$linktext</span>"
421 if length $bestlink && $page eq $bestlink;
423 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
424 $bestlink=htmlpage($bestlink);
426 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
427 return $linktext unless length $config{cgiurl};
428 return "<span><a href=\"".
429 cgiurl(do => "create", page => lc($link), from => $page).
430 "\">?</a>$linktext</span>"
433 $bestlink=abs2rel($bestlink, dirname($page));
435 if (! $noimageinline && isinlinableimage($bestlink)) {
436 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
438 return "<a href=\"$bestlink\">$linktext</a>";
441 sub htmlize ($$$) { #{{{
446 if (exists $hooks{htmlize}{$type}) {
447 $content=$hooks{htmlize}{$type}{call}->(
453 error("htmlization of $type not supported");
456 run_hooks(sanitize => sub {
466 sub linkify ($$$) { #{{{
467 my $lpage=shift; # the page containing the links
468 my $page=shift; # the page the link will end up on (different for inline)
471 $content =~ s{(\\?)$config{wiki_link_regexp}}{
472 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
473 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
480 sub preprocess ($$$;$) { #{{{
481 my $page=shift; # the page the data comes from
482 my $destpage=shift; # the page the data will appear in (different for inline)
490 if (length $escape) {
491 return "[[$command $params]]";
493 elsif (exists $hooks{preprocess}{$command}) {
494 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
495 # Note: preserve order of params, some plugins may
496 # consider it significant.
498 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
515 push @params, $key, $val;
518 push @params, $val, '';
521 if ($preprocessing{$page}++ > 3) {
522 # Avoid loops of preprocessed pages preprocessing
523 # other pages that preprocess them, etc.
524 #translators: The first parameter is a
525 #translators: preprocessor directive name,
526 #translators: the second a page name, the
527 #translators: third a number.
528 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
529 $command, $page, $preprocessing{$page}).
532 my $ret=$hooks{preprocess}{$command}{call}->(
535 destpage => $destpage,
537 $preprocessing{$page}--;
541 return "[[$command $params]]";
545 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
549 sub filter ($$) { #{{{
553 run_hooks(filter => sub {
554 $content=shift->(page => $page, content => $content);
560 sub indexlink () { #{{{
561 return "<a href=\"$config{url}\">$config{wikiname}</a>";
564 sub lockwiki () { #{{{
565 # Take an exclusive lock on the wiki to prevent multiple concurrent
566 # run issues. The lock will be dropped on program exit.
567 if (! -d $config{wikistatedir}) {
568 mkdir($config{wikistatedir});
570 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
571 error ("cannot write to $config{wikistatedir}/lockfile: $!");
572 if (! flock(WIKILOCK, 2 | 4)) {
573 debug("wiki seems to be locked, waiting for lock");
574 my $wait=600; # arbitrary, but don't hang forever to
575 # prevent process pileup
577 return if flock(WIKILOCK, 2 | 4);
580 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
584 sub unlockwiki () { #{{{
588 sub loadindex () { #{{{
589 open (IN, "$config{wikistatedir}/index") || return;
591 $_=possibly_foolish_untaint($_);
596 foreach my $i (split(/ /, $_)) {
597 my ($item, $val)=split(/=/, $i, 2);
598 push @{$items{$item}}, decode_entities($val);
601 next unless exists $items{src}; # skip bad lines for now
603 my $page=pagename($items{src}[0]);
604 if (! $config{rebuild}) {
605 $pagesources{$page}=$items{src}[0];
606 $oldpagemtime{$page}=$items{mtime}[0];
607 $oldlinks{$page}=[@{$items{link}}];
608 $links{$page}=[@{$items{link}}];
609 $depends{$page}=$items{depends}[0] if exists $items{depends};
610 $renderedfiles{$page}=[@{$items{dest}}];
611 $oldrenderedfiles{$page}=[@{$items{dest}}];
612 $pagecase{lc $page}=$page;
614 $pagectime{$page}=$items{ctime}[0];
619 sub saveindex () { #{{{
620 run_hooks(savestate => sub { shift->() });
622 if (! -d $config{wikistatedir}) {
623 mkdir($config{wikistatedir});
625 open (OUT, ">$config{wikistatedir}/index") ||
626 error("cannot write to $config{wikistatedir}/index: $!");
627 foreach my $page (keys %oldpagemtime) {
628 next unless $oldpagemtime{$page};
629 my $line="mtime=$oldpagemtime{$page} ".
630 "ctime=$pagectime{$page} ".
631 "src=$pagesources{$page}";
632 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
634 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
635 if (exists $depends{$page}) {
636 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
638 print OUT $line."\n";
643 sub template_file ($) { #{{{
646 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
647 return "$dir/$template" if -e "$dir/$template";
652 sub template_params (@) { #{{{
653 my $filename=template_file(shift);
655 if (! defined $filename) {
660 require HTML::Template;
663 my $text_ref = shift;
664 $$text_ref=&Encode::decode_utf8($$text_ref);
666 filename => $filename,
667 loop_context_vars => 1,
668 die_on_bad_params => 0,
671 return wantarray ? @ret : {@ret};
674 sub template ($;@) { #{{{
675 HTML::Template->new(template_params(@_));
678 sub misctemplate ($$;@) { #{{{
682 my $template=template("misc.tmpl");
685 indexlink => indexlink(),
686 wikiname => $config{wikiname},
687 pagebody => $pagebody,
688 baseurl => baseurl(),
691 run_hooks(pagetemplate => sub {
692 shift->(page => "", destpage => "", template => $template);
694 return $template->output;
700 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
701 error "hook requires type, call, and id parameters";
704 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
706 $hooks{$param{type}}{$param{id}}=\%param;
709 sub run_hooks ($$) { # {{{
710 # Calls the given sub for each hook of the given type,
711 # passing it the hook function to call.
715 if (exists $hooks{$type}) {
717 foreach my $id (keys %{$hooks{$type}}) {
718 if ($hooks{$type}{$id}{last}) {
722 $sub->($hooks{$type}{$id}{call});
724 foreach my $id (@deferred) {
725 $sub->($hooks{$type}{$id}{call});
730 sub globlist_to_pagespec ($) { #{{{
731 my @globlist=split(' ', shift);
734 foreach my $glob (@globlist) {
735 if ($glob=~/^!(.*)/) {
743 my $spec=join(" or ", @spec);
745 my $skip=join(" and ", @skip);
747 $spec="$skip and ($spec)";
756 sub is_globlist ($) { #{{{
758 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
761 sub safequote ($) { #{{{
767 sub add_depends ($$) { #{{{
771 if (! exists $depends{$page}) {
772 $depends{$page}=$pagespec;
775 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
779 sub file_pruned ($$) { #{{{
781 my $file=File::Spec->canonpath(shift);
782 my $base=File::Spec->canonpath(shift);
783 $file=~s#^\Q$base\E/*##;
785 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
790 # Only use gettext in the rare cases it's needed.
791 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
792 if (! $gettext_obj) {
794 use Locale::gettext q{textdomain};
795 Locale::gettext->domain('ikiwiki')
803 return $gettext_obj->get(shift);
810 sub pagespec_merge ($$) { #{{{
814 return $a if $a eq $b;
816 # Support for old-style GlobLists.
817 if (is_globlist($a)) {
818 $a=globlist_to_pagespec($a);
820 if (is_globlist($b)) {
821 $b=globlist_to_pagespec($b);
824 return "($a) or ($b)";
827 sub pagespec_translate ($) { #{{{
828 # This assumes that $page is in scope in the function
829 # that evalulates the translated pagespec code.
832 # Support for old-style GlobLists.
833 if (is_globlist($spec)) {
834 $spec=globlist_to_pagespec($spec);
837 # Convert spec to perl code.
839 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
841 if (lc $word eq "and") {
844 elsif (lc $word eq "or") {
847 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
850 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
851 $code.=" match_$1(\$page, ".safequote($2).")";
854 $code.=" match_glob(\$page, ".safequote($word).")";
861 sub pagespec_match ($$) { #{{{
865 return eval pagespec_translate($spec);
868 sub match_glob ($$) { #{{{
872 # turn glob into safe regexp
873 $glob=quotemeta($glob);
877 return $page=~/^$glob$/i;
880 sub match_link ($$) { #{{{
884 my $links = $links{$page} or return undef;
885 foreach my $p (@$links) {
886 return 1 if lc $p eq $link;
891 sub match_backlink ($$) { #{{{
892 match_link(pop, pop);
895 sub match_created_before ($$) { #{{{
899 if (exists $pagectime{$testpage}) {
900 return $pagectime{$page} < $pagectime{$testpage};
907 sub match_created_after ($$) { #{{{
911 if (exists $pagectime{$testpage}) {
912 return $pagectime{$page} > $pagectime{$testpage};
919 sub match_creation_day ($$) { #{{{
920 return ((gmtime($pagectime{shift()}))[3] == shift);
923 sub match_creation_month ($$) { #{{{
924 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
927 sub match_creation_year ($$) { #{{{
928 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);