8 use URI::Escape q{uri_escape_utf8};
10 use open qw{:utf8 :std};
12 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
13 %renderedfiles %oldrenderedfiles %pagesources %destsources
14 %depends %hooks %forcerebuild $gettext_obj};
16 use Exporter q{import};
17 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
18 bestlink htmllink readfile writefile pagetype srcfile pagename
19 displaytime will_render gettext urlto targetpage
20 %config %links %renderedfiles %pagesources);
21 our $VERSION = 1.02; # plugin interface version, next is ikiwiki version
22 our $version="1.45";my $installdir="/usr";
26 memoize("pagespec_translate");
27 memoize("file_pruned");
29 sub defaultconfig () { #{{{
30 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
31 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
32 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
33 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\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 signinedit
70 lockedit conditional}],
80 sub checkconfig () { #{{{
81 # locale stuff; avoid LC_ALL since it overrides everything
82 if (defined $ENV{LC_ALL}) {
83 $ENV{LANG} = $ENV{LC_ALL};
86 if (defined $config{locale}) {
87 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
88 $ENV{LANG}=$config{locale};
93 if ($config{w3mmode}) {
94 eval q{use Cwd q{abs_path}};
96 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
97 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
98 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
99 unless $config{cgiurl} =~ m!file:///!;
100 $config{url}="file://".$config{destdir};
103 if ($config{cgi} && ! length $config{url}) {
104 error(gettext("Must specify url to wiki with --url when using --cgi"));
107 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
108 unless exists $config{wikistatedir};
111 eval qq{require IkiWiki::Rcs::$config{rcs}};
113 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
117 require IkiWiki::Rcs::Stub;
120 run_hooks(checkconfig => sub { shift->() });
123 sub loadplugins () { #{{{
124 loadplugin($_) foreach @{$config{plugin}};
126 run_hooks(getopt => sub { shift->() });
127 if (grep /^-/, @ARGV) {
128 print STDERR "Unknown option: $_\n"
129 foreach grep /^-/, @ARGV;
134 sub loadplugin ($) { #{{{
137 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
139 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
142 error("Failed to load plugin $mod: $@");
146 sub error ($;$) { #{{{
150 print "Content-type: text/html\n\n";
151 print misctemplate(gettext("Error"),
152 "<p>".gettext("Error").": $message</p>");
154 log_message('err' => $message) if $config{syslog};
155 if (defined $cleaner) {
162 return unless $config{verbose};
163 log_message(debug => @_);
167 sub log_message ($$) { #{{{
170 if ($config{syslog}) {
173 Sys::Syslog::setlogsock('unix');
174 Sys::Syslog::openlog('ikiwiki', '', 'user');
178 Sys::Syslog::syslog($type, "%s", join(" ", @_));
181 elsif (! $config{cgi}) {
189 sub possibly_foolish_untaint ($) { #{{{
191 my ($untainted)=$tainted=~/(.*)/;
195 sub basename ($) { #{{{
202 sub dirname ($) { #{{{
209 sub pagetype ($) { #{{{
212 if ($page =~ /\.([^.]+)$/) {
213 return $1 if exists $hooks{htmlize}{$1};
218 sub pagename ($) { #{{{
221 my $type=pagetype($file);
223 $page=~s/\Q.$type\E*$// if defined $type;
227 sub targetpage ($$) { #{{{
231 if (! $config{usedirs} || $page =~ /^index$/ ) {
232 return $page.".".$ext;
234 return $page."/index.".$ext;
238 sub htmlpage ($) { #{{{
241 return targetpage($page, "html");
244 sub srcfile ($) { #{{{
247 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
248 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
249 error("internal error: $file cannot be found");
252 sub readfile ($;$$) { #{{{
258 error("cannot read a symlink ($file)");
262 open (IN, $file) || error("failed to read $file: $!");
263 binmode(IN) if ($binary);
264 return \*IN if $wantfd;
266 close IN || error("failed to read $file: $!");
270 sub writefile ($$$;$$) { #{{{
271 my $file=shift; # can include subdirs
272 my $destdir=shift; # directory to put file in
278 while (length $test) {
279 if (-l "$destdir/$test") {
280 error("cannot write to a symlink ($test)");
282 $test=dirname($test);
284 my $newfile="$destdir/$file.ikiwiki-new";
286 error("cannot write to a symlink ($newfile)");
289 my $dir=dirname($newfile);
292 foreach my $s (split(m!/+!, $dir)) {
295 mkdir($d) || error("failed to create directory $d: $!");
300 my $cleanup = sub { unlink($newfile) };
301 open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
302 binmode(OUT) if ($binary);
304 $writer->(\*OUT, $cleanup);
307 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
309 close OUT || error("failed saving $newfile: $!", $cleanup);
310 rename($newfile, "$destdir/$file") ||
311 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
315 sub will_render ($$;$) { #{{{
320 # Important security check.
321 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
322 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
323 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
326 if (! $clear || $cleared{$page}) {
327 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
330 foreach my $old (@{$renderedfiles{$page}}) {
331 delete $destsources{$old};
333 $renderedfiles{$page}=[$dest];
336 $destsources{$dest}=$page;
339 sub bestlink ($$) { #{{{
344 if ($link=~s/^\/+//) {
351 $l.="/" if length $l;
354 if (exists $links{$l}) {
357 elsif (exists $pagecase{lc $l}) {
358 return $pagecase{lc $l};
360 } while $cwd=~s!/?[^/]+$!!;
362 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
363 return "$config{userdir}/".lc($link);
366 #print STDERR "warning: page $page, broken link: $link\n";
370 sub isinlinableimage ($) { #{{{
373 $file=~/\.(png|gif|jpg|jpeg)$/i;
376 sub pagetitle ($;$) { #{{{
381 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
384 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
390 sub titlepage ($) { #{{{
392 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
396 sub linkpage ($) { #{{{
398 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
402 sub cgiurl (@) { #{{{
405 return $config{cgiurl}."?".
406 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
409 sub baseurl (;$) { #{{{
412 return "$config{url}/" if ! defined $page;
414 $page=htmlpage($page);
416 $page=~s/[^\/]+\//..\//g;
420 sub abs2rel ($$) { #{{{
421 # Work around very innefficient behavior in File::Spec if abs2rel
422 # is passed two relative paths. It's much faster if paths are
423 # absolute! (Debian bug #376658; fixed in debian unstable now)
428 my $ret=File::Spec->abs2rel($path, $base);
429 $ret=~s/^// if defined $ret;
433 sub displaytime ($) { #{{{
436 # strftime doesn't know about encodings, so make sure
437 # its output is properly treated as utf8
438 return decode_utf8(POSIX::strftime(
439 $config{timeformat}, localtime($time)));
442 sub beautify_url ($) { #{{{
445 $url =~ s!/index.html$!/!;
446 $url =~ s!^$!./!; # Browsers don't like empty links...
451 sub urlto ($$) { #{{{
456 return beautify_url(baseurl($from));
459 if (! $destsources{$to}) {
463 my $link = abs2rel($to, dirname(htmlpage($from)));
465 return beautify_url($link);
468 sub htmllink ($$$;@) { #{{{
469 my $lpage=shift; # the page doing the linking
470 my $page=shift; # the page that will contain the link (different for inline)
475 if (! $opts{forcesubpage}) {
476 $bestlink=bestlink($lpage, $link);
479 $bestlink="$lpage/".lc($link);
483 if (defined $opts{linktext}) {
484 $linktext=$opts{linktext};
487 $linktext=pagetitle(basename($link));
490 return "<span class=\"selflink\">$linktext</span>"
491 if length $bestlink && $page eq $bestlink;
493 if (! $destsources{$bestlink}) {
494 $bestlink=htmlpage($bestlink);
496 if (! $destsources{$bestlink}) {
497 return $linktext unless length $config{cgiurl};
498 return "<span><a href=\"".
501 page => pagetitle(lc($link), 1),
504 "\">?</a>$linktext</span>"
508 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
509 $bestlink=beautify_url($bestlink);
511 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
512 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
515 if (defined $opts{anchor}) {
516 $bestlink.="#".$opts{anchor};
519 return "<a href=\"$bestlink\">$linktext</a>";
522 sub htmlize ($$$) { #{{{
527 if (exists $hooks{htmlize}{$type}) {
528 $content=$hooks{htmlize}{$type}{call}->(
534 error("htmlization of $type not supported");
537 run_hooks(sanitize => sub {
547 sub linkify ($$$) { #{{{
548 my $lpage=shift; # the page containing the links
549 my $page=shift; # the page the link will end up on (different for inline)
552 $content =~ s{(\\?)$config{wiki_link_regexp}}{
555 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
556 : htmllink($lpage, $page, linkpage($3),
557 anchor => $4, linktext => pagetitle($2)))
559 ? "[[$3".($4 ? "#$4" : "")."]]"
560 : htmllink($lpage, $page, linkpage($3),
568 our $preprocess_preview=0;
569 sub preprocess ($$$;$$) { #{{{
570 my $page=shift; # the page the data comes from
571 my $destpage=shift; # the page the data will appear in (different for inline)
576 # Using local because it needs to be set within any nested calls
578 local $preprocess_preview=$preview if defined $preview;
584 if (length $escape) {
585 return "[[$command $params]]";
587 elsif (exists $hooks{preprocess}{$command}) {
588 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
589 # Note: preserve order of params, some plugins may
590 # consider it significant.
592 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
609 push @params, $key, $val;
612 push @params, $val, '';
615 if ($preprocessing{$page}++ > 3) {
616 # Avoid loops of preprocessed pages preprocessing
617 # other pages that preprocess them, etc.
618 #translators: The first parameter is a
619 #translators: preprocessor directive name,
620 #translators: the second a page name, the
621 #translators: third a number.
622 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
623 $command, $page, $preprocessing{$page}).
626 my $ret=$hooks{preprocess}{$command}{call}->(
629 destpage => $destpage,
630 preview => $preprocess_preview,
632 $preprocessing{$page}--;
636 return "[[$command $params]]";
640 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
644 sub filter ($$) { #{{{
648 run_hooks(filter => sub {
649 $content=shift->(page => $page, content => $content);
655 sub indexlink () { #{{{
656 return "<a href=\"$config{url}\">$config{wikiname}</a>";
659 sub lockwiki () { #{{{
660 # Take an exclusive lock on the wiki to prevent multiple concurrent
661 # run issues. The lock will be dropped on program exit.
662 if (! -d $config{wikistatedir}) {
663 mkdir($config{wikistatedir});
665 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
666 error ("cannot write to $config{wikistatedir}/lockfile: $!");
667 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
668 debug("wiki seems to be locked, waiting for lock");
669 my $wait=600; # arbitrary, but don't hang forever to
670 # prevent process pileup
672 return if flock(WIKILOCK, 2 | 4);
675 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
679 sub unlockwiki () { #{{{
683 sub commit_hook_enabled () { #{{{
684 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
685 error ("cannot write to $config{wikistatedir}/commitlock: $!");
686 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
694 sub disable_commit_hook () { #{{{
695 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
696 error ("cannot write to $config{wikistatedir}/commitlock: $!");
697 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
698 error("failed to get commit lock");
702 sub enable_commit_hook () { #{{{
706 sub loadindex () { #{{{
707 open (IN, "$config{wikistatedir}/index") || return;
709 $_=possibly_foolish_untaint($_);
714 foreach my $i (split(/ /, $_)) {
715 my ($item, $val)=split(/=/, $i, 2);
716 push @{$items{$item}}, decode_entities($val);
719 next unless exists $items{src}; # skip bad lines for now
721 my $page=pagename($items{src}[0]);
722 if (! $config{rebuild}) {
723 $pagesources{$page}=$items{src}[0];
724 $pagemtime{$page}=$items{mtime}[0];
725 $oldlinks{$page}=[@{$items{link}}];
726 $links{$page}=[@{$items{link}}];
727 $depends{$page}=$items{depends}[0] if exists $items{depends};
728 $destsources{$_}=$page foreach @{$items{dest}};
729 $renderedfiles{$page}=[@{$items{dest}}];
730 $oldrenderedfiles{$page}=[@{$items{dest}}];
731 $pagecase{lc $page}=$page;
733 $pagectime{$page}=$items{ctime}[0];
738 sub saveindex () { #{{{
739 run_hooks(savestate => sub { shift->() });
741 if (! -d $config{wikistatedir}) {
742 mkdir($config{wikistatedir});
744 my $newfile="$config{wikistatedir}/index.new";
745 my $cleanup = sub { unlink($newfile) };
746 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
747 foreach my $page (keys %pagemtime) {
748 next unless $pagemtime{$page};
749 my $line="mtime=$pagemtime{$page} ".
750 "ctime=$pagectime{$page} ".
751 "src=$pagesources{$page}";
752 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
754 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
755 if (exists $depends{$page}) {
756 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
758 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
760 close OUT || error("failed saving to $newfile: $!", $cleanup);
761 rename($newfile, "$config{wikistatedir}/index") ||
762 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
765 sub template_file ($) { #{{{
768 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
769 return "$dir/$template" if -e "$dir/$template";
774 sub template_params (@) { #{{{
775 my $filename=template_file(shift);
777 if (! defined $filename) {
782 require HTML::Template;
785 my $text_ref = shift;
786 $$text_ref=&Encode::decode_utf8($$text_ref);
788 filename => $filename,
789 loop_context_vars => 1,
790 die_on_bad_params => 0,
793 return wantarray ? @ret : {@ret};
796 sub template ($;@) { #{{{
797 HTML::Template->new(template_params(@_));
800 sub misctemplate ($$;@) { #{{{
804 my $template=template("misc.tmpl");
807 indexlink => indexlink(),
808 wikiname => $config{wikiname},
809 pagebody => $pagebody,
810 baseurl => baseurl(),
813 run_hooks(pagetemplate => sub {
814 shift->(page => "", destpage => "", template => $template);
816 return $template->output;
822 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
823 error "hook requires type, call, and id parameters";
826 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
828 $hooks{$param{type}}{$param{id}}=\%param;
831 sub run_hooks ($$) { # {{{
832 # Calls the given sub for each hook of the given type,
833 # passing it the hook function to call.
837 if (exists $hooks{$type}) {
839 foreach my $id (keys %{$hooks{$type}}) {
840 if ($hooks{$type}{$id}{last}) {
844 $sub->($hooks{$type}{$id}{call});
846 foreach my $id (@deferred) {
847 $sub->($hooks{$type}{$id}{call});
852 sub globlist_to_pagespec ($) { #{{{
853 my @globlist=split(' ', shift);
856 foreach my $glob (@globlist) {
857 if ($glob=~/^!(.*)/) {
865 my $spec=join(" or ", @spec);
867 my $skip=join(" and ", @skip);
869 $spec="$skip and ($spec)";
878 sub is_globlist ($) { #{{{
880 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
883 sub safequote ($) { #{{{
889 sub add_depends ($$) { #{{{
893 if (! exists $depends{$page}) {
894 $depends{$page}=$pagespec;
897 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
901 sub file_pruned ($$) { #{{{
903 my $file=File::Spec->canonpath(shift);
904 my $base=File::Spec->canonpath(shift);
905 $file=~s#^\Q$base\E/*##;
907 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
912 # Only use gettext in the rare cases it's needed.
913 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
914 if (! $gettext_obj) {
916 use Locale::gettext q{textdomain};
917 Locale::gettext->domain('ikiwiki')
925 return $gettext_obj->get(shift);
932 sub pagespec_merge ($$) { #{{{
936 return $a if $a eq $b;
938 # Support for old-style GlobLists.
939 if (is_globlist($a)) {
940 $a=globlist_to_pagespec($a);
942 if (is_globlist($b)) {
943 $b=globlist_to_pagespec($b);
946 return "($a) or ($b)";
949 sub pagespec_translate ($) { #{{{
950 # This assumes that $page is in scope in the function
951 # that evalulates the translated pagespec code.
954 # Support for old-style GlobLists.
955 if (is_globlist($spec)) {
956 $spec=globlist_to_pagespec($spec);
959 # Convert spec to perl code.
961 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
963 if (lc $word eq "and") {
966 elsif (lc $word eq "or") {
969 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
972 elsif ($word =~ /^(\w+)\((.*)\)$/) {
973 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
974 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
981 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
988 sub pagespec_match ($$;$) { #{{{
993 return eval pagespec_translate($spec);
996 package IkiWiki::PageSpec;
998 sub match_glob ($$$) { #{{{
1002 if (! defined $from){
1007 if ($glob =~ m!^\./!) {
1008 $from=~s!/?[^/]+$!!;
1010 $glob="$from/$glob" if length $from;
1013 # turn glob into safe regexp
1014 $glob=quotemeta($glob);
1018 return $page=~/^$glob$/i;
1021 sub match_link ($$$) { #{{{
1025 if (! defined $from){
1030 if ($link =~ m!^\.! && defined $from) {
1031 $from=~s!/?[^/]+$!!;
1033 $link="$from/$link" if length $from;
1036 my $links = $IkiWiki::links{$page} or return undef;
1037 return 0 unless @$links;
1038 my $bestlink = IkiWiki::bestlink($from, $link);
1039 return 0 unless length $bestlink;
1040 foreach my $p (@$links) {
1041 return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
1046 sub match_backlink ($$$) { #{{{
1047 match_link($_[1], $_[0], $_[3]);
1050 sub match_created_before ($$$) { #{{{
1054 if (exists $IkiWiki::pagectime{$testpage}) {
1055 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
1062 sub match_created_after ($$$) { #{{{
1066 if (exists $IkiWiki::pagectime{$testpage}) {
1067 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1074 sub match_creation_day ($$$) { #{{{
1075 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1078 sub match_creation_month ($$$) { #{{{
1079 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1082 sub match_creation_year ($$$) { #{{{
1083 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);