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_TIME, $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 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
135 error("Failed to load plugin $mod: $@");
141 print "Content-type: text/html\n\n";
142 print misctemplate(gettext("Error"),
143 "<p>".gettext("Error").": @_</p>");
145 log_message(error => @_);
150 return unless $config{verbose};
151 log_message(debug => @_);
155 sub log_message ($$) { #{{{
158 if ($config{syslog}) {
161 Sys::Syslog::setlogsock('unix');
162 Sys::Syslog::openlog('ikiwiki', '', 'user');
166 Sys::Syslog::syslog($type, join(" ", @_));
169 elsif (! $config{cgi}) {
177 sub possibly_foolish_untaint ($) { #{{{
179 my ($untainted)=$tainted=~/(.*)/;
183 sub basename ($) { #{{{
190 sub dirname ($) { #{{{
197 sub pagetype ($) { #{{{
200 if ($page =~ /\.([^.]+)$/) {
201 return $1 if exists $hooks{htmlize}{$1};
206 sub pagename ($) { #{{{
209 my $type=pagetype($file);
211 $page=~s/\Q.$type\E*$// if defined $type;
215 sub htmlpage ($) { #{{{
218 return $page.".html";
221 sub srcfile ($) { #{{{
224 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
225 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
226 error("internal error: $file cannot be found");
229 sub readfile ($;$) { #{{{
234 error("cannot read a symlink ($file)");
238 open (IN, $file) || error("failed to read $file: $!");
239 binmode(IN) if ($binary);
245 sub writefile ($$$;$) { #{{{
246 my $file=shift; # can include subdirs
247 my $destdir=shift; # directory to put file in
252 while (length $test) {
253 if (-l "$destdir/$test") {
254 error("cannot write to a symlink ($test)");
256 $test=dirname($test);
259 my $dir=dirname("$destdir/$file");
262 foreach my $s (split(m!/+!, $dir)) {
265 mkdir($d) || error("failed to create directory $d: $!");
270 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
271 binmode(OUT) if ($binary);
277 sub will_render ($$;$) { #{{{
282 # Important security check.
283 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
284 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
285 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
288 if (! $clear || $cleared{$page}) {
289 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
292 $renderedfiles{$page}=[$dest];
297 sub bestlink ($$) { #{{{
302 if ($link=~s/^\/+//) {
309 $l.="/" if length $l;
312 if (exists $links{$l}) {
315 elsif (exists $pagecase{lc $l}) {
316 return $pagecase{lc $l};
318 } while $cwd=~s!/?[^/]+$!!;
320 #print STDERR "warning: page $page, broken link: $link\n";
324 sub isinlinableimage ($) { #{{{
327 $file=~/\.(png|gif|jpg|jpeg)$/i;
330 sub pagetitle ($;$) { #{{{
335 $page=~s/__(\d+)__/chr($1)/eg;
338 $page=~s/__(\d+)__/&#$1;/g;
345 sub titlepage ($) { #{{{
348 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
352 sub cgiurl (@) { #{{{
355 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
358 sub baseurl (;$) { #{{{
361 return "$config{url}/" if ! defined $page;
364 $page=~s/[^\/]+\//..\//g;
368 sub abs2rel ($$) { #{{{
369 # Work around very innefficient behavior in File::Spec if abs2rel
370 # is passed two relative paths. It's much faster if paths are
371 # absolute! (Debian bug #376658; fixed in debian unstable now)
376 my $ret=File::Spec->abs2rel($path, $base);
377 $ret=~s/^// if defined $ret;
381 sub displaytime ($) { #{{{
386 # strftime doesn't know about encodings, so make sure
387 # its output is properly treated as utf8
388 return decode_utf8(POSIX::strftime(
389 $config{timeformat}, localtime($time)));
392 sub htmllink ($$$;$$$) { #{{{
393 my $lpage=shift; # the page doing the linking
394 my $page=shift; # the page that will contain the link (different for inline)
396 my $noimageinline=shift; # don't turn links into inline html images
397 my $forcesubpage=shift; # force a link to a subpage
398 my $linktext=shift; # set to force the link text to something
401 if (! $forcesubpage) {
402 $bestlink=bestlink($lpage, $link);
405 $bestlink="$lpage/".lc($link);
408 $linktext=pagetitle(basename($link)) unless defined $linktext;
410 return "<span class=\"selflink\">$linktext</span>"
411 if length $bestlink && $page eq $bestlink;
413 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
414 $bestlink=htmlpage($bestlink);
416 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
417 return $linktext unless length $config{cgiurl};
418 return "<span><a href=\"".
419 cgiurl(do => "create", page => lc($link), from => $page).
420 "\">?</a>$linktext</span>"
423 $bestlink=abs2rel($bestlink, dirname($page));
425 if (! $noimageinline && isinlinableimage($bestlink)) {
426 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
428 return "<a href=\"$bestlink\">$linktext</a>";
431 sub htmlize ($$$) { #{{{
436 if (exists $hooks{htmlize}{$type}) {
437 $content=$hooks{htmlize}{$type}{call}->(
443 error("htmlization of $type not supported");
446 run_hooks(sanitize => sub {
456 sub linkify ($$$) { #{{{
457 my $lpage=shift; # the page containing the links
458 my $page=shift; # the page the link will end up on (different for inline)
461 $content =~ s{(\\?)$config{wiki_link_regexp}}{
462 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
463 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
470 sub preprocess ($$$;$) { #{{{
471 my $page=shift; # the page the data comes from
472 my $destpage=shift; # the page the data will appear in (different for inline)
480 if (length $escape) {
481 return "[[$command $params]]";
483 elsif (exists $hooks{preprocess}{$command}) {
484 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
485 # Note: preserve order of params, some plugins may
486 # consider it significant.
488 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
505 push @params, $key, $val;
508 push @params, $val, '';
511 if ($preprocessing{$page}++ > 3) {
512 # Avoid loops of preprocessed pages preprocessing
513 # other pages that preprocess them, etc.
514 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
515 $command, $page, $preprocessing{$page}).
518 my $ret=$hooks{preprocess}{$command}{call}->(
521 destpage => $destpage,
523 $preprocessing{$page}--;
527 return "[[$command $params]]";
531 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
535 sub filter ($$) { #{{{
539 run_hooks(filter => sub {
540 $content=shift->(page => $page, content => $content);
546 sub indexlink () { #{{{
547 return "<a href=\"$config{url}\">$config{wikiname}</a>";
550 sub lockwiki () { #{{{
551 # Take an exclusive lock on the wiki to prevent multiple concurrent
552 # run issues. The lock will be dropped on program exit.
553 if (! -d $config{wikistatedir}) {
554 mkdir($config{wikistatedir});
556 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
557 error ("cannot write to $config{wikistatedir}/lockfile: $!");
558 if (! flock(WIKILOCK, 2 | 4)) {
559 debug("wiki seems to be locked, waiting for lock");
560 my $wait=600; # arbitrary, but don't hang forever to
561 # prevent process pileup
563 return if flock(WIKILOCK, 2 | 4);
566 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
570 sub unlockwiki () { #{{{
574 sub loadindex () { #{{{
575 open (IN, "$config{wikistatedir}/index") || return;
577 $_=possibly_foolish_untaint($_);
582 foreach my $i (split(/ /, $_)) {
583 my ($item, $val)=split(/=/, $i, 2);
584 push @{$items{$item}}, decode_entities($val);
587 next unless exists $items{src}; # skip bad lines for now
589 my $page=pagename($items{src}[0]);
590 if (! $config{rebuild}) {
591 $pagesources{$page}=$items{src}[0];
592 $oldpagemtime{$page}=$items{mtime}[0];
593 $oldlinks{$page}=[@{$items{link}}];
594 $links{$page}=[@{$items{link}}];
595 $depends{$page}=$items{depends}[0] if exists $items{depends};
596 $renderedfiles{$page}=[@{$items{dest}}];
597 $oldrenderedfiles{$page}=[@{$items{dest}}];
598 $pagecase{lc $page}=$page;
600 $pagectime{$page}=$items{ctime}[0];
605 sub saveindex () { #{{{
606 run_hooks(savestate => sub { shift->() });
608 if (! -d $config{wikistatedir}) {
609 mkdir($config{wikistatedir});
611 open (OUT, ">$config{wikistatedir}/index") ||
612 error("cannot write to $config{wikistatedir}/index: $!");
613 foreach my $page (keys %oldpagemtime) {
614 next unless $oldpagemtime{$page};
615 my $line="mtime=$oldpagemtime{$page} ".
616 "ctime=$pagectime{$page} ".
617 "src=$pagesources{$page}";
618 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
620 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
621 if (exists $depends{$page}) {
622 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
624 print OUT $line."\n";
629 sub template_params (@) { #{{{
632 require HTML::Template;
633 return filter => sub {
634 my $text_ref = shift;
635 $$text_ref=&Encode::decode_utf8($$text_ref);
637 filename => "$config{templatedir}/$filename",
638 loop_context_vars => 1,
639 die_on_bad_params => 0,
643 sub template ($;@) { #{{{
644 HTML::Template->new(template_params(@_));
647 sub misctemplate ($$;@) { #{{{
651 my $template=template("misc.tmpl");
654 indexlink => indexlink(),
655 wikiname => $config{wikiname},
656 pagebody => $pagebody,
657 baseurl => baseurl(),
660 run_hooks(pagetemplate => sub {
661 shift->(page => "", destpage => "", template => $template);
663 return $template->output;
669 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
670 error "hook requires type, call, and id parameters";
673 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
675 $hooks{$param{type}}{$param{id}}=\%param;
678 sub run_hooks ($$) { # {{{
679 # Calls the given sub for each hook of the given type,
680 # passing it the hook function to call.
684 if (exists $hooks{$type}) {
686 foreach my $id (keys %{$hooks{$type}}) {
687 if ($hooks{$type}{$id}{last}) {
691 $sub->($hooks{$type}{$id}{call});
693 foreach my $id (@deferred) {
694 $sub->($hooks{$type}{$id}{call});
699 sub globlist_to_pagespec ($) { #{{{
700 my @globlist=split(' ', shift);
703 foreach my $glob (@globlist) {
704 if ($glob=~/^!(.*)/) {
712 my $spec=join(" or ", @spec);
714 my $skip=join(" and ", @skip);
716 $spec="$skip and ($spec)";
725 sub is_globlist ($) { #{{{
727 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
730 sub safequote ($) { #{{{
736 sub pagespec_merge ($$) { #{{{
740 return $a if $a eq $b;
742 # Support for old-style GlobLists.
743 if (is_globlist($a)) {
744 $a=globlist_to_pagespec($a);
746 if (is_globlist($b)) {
747 $b=globlist_to_pagespec($b);
750 return "($a) or ($b)";
753 sub pagespec_translate ($) { #{{{
754 # This assumes that $page is in scope in the function
755 # that evalulates the translated pagespec code.
758 # Support for old-style GlobLists.
759 if (is_globlist($spec)) {
760 $spec=globlist_to_pagespec($spec);
763 # Convert spec to perl code.
765 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
767 if (lc $word eq "and") {
770 elsif (lc $word eq "or") {
773 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
776 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
777 $code.=" match_$1(\$page, ".safequote($2).")";
780 $code.=" match_glob(\$page, ".safequote($word).")";
787 sub add_depends ($$) { #{{{
791 if (! exists $depends{$page}) {
792 $depends{$page}=$pagespec;
795 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
799 sub file_pruned ($$) { #{{{
801 my $file=File::Spec->canonpath(shift);
802 my $base=File::Spec->canonpath(shift);
803 $file=~s#^\Q$base\E/*##;
805 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
810 # Only use gettext in the rare cases it's needed.
811 # This overrides future calls of this function.
812 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
813 eval q{use Locale::gettext};
814 textdomain('ikiwiki');
815 return Locale::gettext::gettext(shift);
822 sub pagespec_match ($$) { #{{{
826 return eval pagespec_translate($spec);
829 sub match_glob ($$) { #{{{
833 # turn glob into safe regexp
834 $glob=quotemeta($glob);
838 return $page=~/^$glob$/i;
841 sub match_link ($$) { #{{{
845 my $links = $links{$page} or return undef;
846 foreach my $p (@$links) {
847 return 1 if lc $p eq $link;
852 sub match_backlink ($$) { #{{{
853 match_link(pop, pop);
856 sub match_created_before ($$) { #{{{
860 if (exists $pagectime{$testpage}) {
861 return $pagectime{$page} < $pagectime{$testpage};
868 sub match_created_after ($$) { #{{{
872 if (exists $pagectime{$testpage}) {
873 return $pagectime{$page} > $pagectime{$testpage};
880 sub match_creation_day ($$) { #{{{
881 return ((gmtime($pagectime{shift()}))[3] == shift);
884 sub match_creation_month ($$) { #{{{
885 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
888 sub match_creation_year ($$) { #{{{
889 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);