8 use URI::Escape q{uri_escape_utf8};
9 use open qw{:utf8 :std};
11 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
12 %renderedfiles %oldrenderedfiles %pagesources %depends %hooks
13 %forcerebuild $gettext_obj};
15 use Exporter q{import};
16 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
17 bestlink htmllink readfile writefile pagetype srcfile pagename
18 displaytime will_render gettext
19 %config %links %renderedfiles %pagesources);
20 our $VERSION = 1.02; # plugin interface version, next is ikiwiki version
21 our $version="1.45";my $installdir="/usr";
25 memoize("pagespec_translate");
26 memoize("file_pruned");
28 sub defaultconfig () { #{{{
29 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
30 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
31 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
32 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
33 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
34 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
38 default_pageext => "mdwn",
58 gitorigin_branch => "origin",
59 gitmaster_branch => "master",
63 templatedir => "$installdir/share/ikiwiki/templates",
64 underlaydir => "$installdir/share/ikiwiki/basewiki",
68 plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
69 lockedit conditional}],
78 sub checkconfig () { #{{{
79 # locale stuff; avoid LC_ALL since it overrides everything
80 if (defined $ENV{LC_ALL}) {
81 $ENV{LANG} = $ENV{LC_ALL};
84 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(debug => $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 htmlpage ($) { #{{{
230 return $page.".html";
233 sub srcfile ($) { #{{{
236 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
237 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
238 error("internal error: $file cannot be found");
241 sub readfile ($;$$) { #{{{
247 error("cannot read a symlink ($file)");
251 open (IN, $file) || error("failed to read $file: $!");
252 binmode(IN) if ($binary);
253 return \*IN if $wantfd;
255 close IN || error("failed to read $file: $!");
259 sub writefile ($$$;$$) { #{{{
260 my $file=shift; # can include subdirs
261 my $destdir=shift; # directory to put file in
267 while (length $test) {
268 if (-l "$destdir/$test") {
269 error("cannot write to a symlink ($test)");
271 $test=dirname($test);
273 my $newfile="$destdir/$file.ikiwiki-new";
275 error("cannot write to a symlink ($newfile)");
278 my $dir=dirname($newfile);
281 foreach my $s (split(m!/+!, $dir)) {
284 mkdir($d) || error("failed to create directory $d: $!");
289 my $cleanup = sub { unlink($newfile) };
290 open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
291 binmode(OUT) if ($binary);
293 $writer->(\*OUT, $cleanup);
296 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
298 close OUT || error("failed saving $newfile: $!", $cleanup);
299 rename($newfile, "$destdir/$file") ||
300 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
304 sub will_render ($$;$) { #{{{
309 # Important security check.
310 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
311 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
312 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
315 if (! $clear || $cleared{$page}) {
316 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
319 $renderedfiles{$page}=[$dest];
324 sub bestlink ($$) { #{{{
329 if ($link=~s/^\/+//) {
336 $l.="/" if length $l;
339 if (exists $links{$l}) {
342 elsif (exists $pagecase{lc $l}) {
343 return $pagecase{lc $l};
345 } while $cwd=~s!/?[^/]+$!!;
347 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
348 return "$config{userdir}/".lc($link);
351 #print STDERR "warning: page $page, broken link: $link\n";
355 sub isinlinableimage ($) { #{{{
358 $file=~/\.(png|gif|jpg|jpeg)$/i;
361 sub pagetitle ($;$) { #{{{
366 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
369 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
375 sub titlepage ($) { #{{{
377 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
381 sub linkpage ($) { #{{{
383 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
387 sub cgiurl (@) { #{{{
390 return $config{cgiurl}."?".
391 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
394 sub baseurl (;$) { #{{{
397 return "$config{url}/" if ! defined $page;
400 $page=~s/[^\/]+\//..\//g;
404 sub abs2rel ($$) { #{{{
405 # Work around very innefficient behavior in File::Spec if abs2rel
406 # is passed two relative paths. It's much faster if paths are
407 # absolute! (Debian bug #376658; fixed in debian unstable now)
412 my $ret=File::Spec->abs2rel($path, $base);
413 $ret=~s/^// if defined $ret;
417 sub displaytime ($) { #{{{
422 # strftime doesn't know about encodings, so make sure
423 # its output is properly treated as utf8
424 return decode_utf8(POSIX::strftime(
425 $config{timeformat}, localtime($time)));
428 sub htmllink ($$$;@) { #{{{
429 my $lpage=shift; # the page doing the linking
430 my $page=shift; # the page that will contain the link (different for inline)
435 if (! $opts{forcesubpage}) {
436 $bestlink=bestlink($lpage, $link);
439 $bestlink="$lpage/".lc($link);
443 if (defined $opts{linktext}) {
444 $linktext=$opts{linktext};
447 $linktext=pagetitle(basename($link));
450 return "<span class=\"selflink\">$linktext</span>"
451 if length $bestlink && $page eq $bestlink;
453 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
454 $bestlink=htmlpage($bestlink);
456 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
457 return $linktext unless length $config{cgiurl};
458 return "<span><a href=\"".
461 page => pagetitle(lc($link), 1),
464 "\">?</a>$linktext</span>"
467 $bestlink=abs2rel($bestlink, dirname($page));
469 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
470 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
473 if (defined $opts{anchor}) {
474 $bestlink.="#".$opts{anchor};
477 return "<a href=\"$bestlink\">$linktext</a>";
480 sub htmlize ($$$) { #{{{
485 if (exists $hooks{htmlize}{$type}) {
486 $content=$hooks{htmlize}{$type}{call}->(
492 error("htmlization of $type not supported");
495 run_hooks(sanitize => sub {
505 sub linkify ($$$) { #{{{
506 my $lpage=shift; # the page containing the links
507 my $page=shift; # the page the link will end up on (different for inline)
510 $content =~ s{(\\?)$config{wiki_link_regexp}}{
512 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4, linktext => pagetitle($2)))
513 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4))
520 our $preprocess_preview=0;
521 sub preprocess ($$$;$$) { #{{{
522 my $page=shift; # the page the data comes from
523 my $destpage=shift; # the page the data will appear in (different for inline)
528 # Using local because it needs to be set within any nested calls
530 local $preprocess_preview=$preview if defined $preview;
536 if (length $escape) {
537 return "[[$command $params]]";
539 elsif (exists $hooks{preprocess}{$command}) {
540 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
541 # Note: preserve order of params, some plugins may
542 # consider it significant.
544 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
561 push @params, $key, $val;
564 push @params, $val, '';
567 if ($preprocessing{$page}++ > 3) {
568 # Avoid loops of preprocessed pages preprocessing
569 # other pages that preprocess them, etc.
570 #translators: The first parameter is a
571 #translators: preprocessor directive name,
572 #translators: the second a page name, the
573 #translators: third a number.
574 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
575 $command, $page, $preprocessing{$page}).
578 my $ret=$hooks{preprocess}{$command}{call}->(
581 destpage => $destpage,
582 preview => $preprocess_preview,
584 $preprocessing{$page}--;
588 return "[[$command $params]]";
592 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
596 sub filter ($$) { #{{{
600 run_hooks(filter => sub {
601 $content=shift->(page => $page, content => $content);
607 sub indexlink () { #{{{
608 return "<a href=\"$config{url}\">$config{wikiname}</a>";
611 sub lockwiki () { #{{{
612 # Take an exclusive lock on the wiki to prevent multiple concurrent
613 # run issues. The lock will be dropped on program exit.
614 if (! -d $config{wikistatedir}) {
615 mkdir($config{wikistatedir});
617 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
618 error ("cannot write to $config{wikistatedir}/lockfile: $!");
619 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
620 debug("wiki seems to be locked, waiting for lock");
621 my $wait=600; # arbitrary, but don't hang forever to
622 # prevent process pileup
624 return if flock(WIKILOCK, 2 | 4);
627 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
631 sub unlockwiki () { #{{{
635 sub commit_hook_enabled () { #{{{
636 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
637 error ("cannot write to $config{wikistatedir}/commitlock: $!");
638 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
646 sub disable_commit_hook () { #{{{
647 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
648 error ("cannot write to $config{wikistatedir}/commitlock: $!");
649 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
650 error("failed to get commit lock");
654 sub enable_commit_hook () { #{{{
658 sub loadindex () { #{{{
659 open (IN, "$config{wikistatedir}/index") || return;
661 $_=possibly_foolish_untaint($_);
666 foreach my $i (split(/ /, $_)) {
667 my ($item, $val)=split(/=/, $i, 2);
668 push @{$items{$item}}, decode_entities($val);
671 next unless exists $items{src}; # skip bad lines for now
673 my $page=pagename($items{src}[0]);
674 if (! $config{rebuild}) {
675 $pagesources{$page}=$items{src}[0];
676 $pagemtime{$page}=$items{mtime}[0];
677 $oldlinks{$page}=[@{$items{link}}];
678 $links{$page}=[@{$items{link}}];
679 $depends{$page}=$items{depends}[0] if exists $items{depends};
680 $renderedfiles{$page}=[@{$items{dest}}];
681 $oldrenderedfiles{$page}=[@{$items{dest}}];
682 $pagecase{lc $page}=$page;
684 $pagectime{$page}=$items{ctime}[0];
689 sub saveindex () { #{{{
690 run_hooks(savestate => sub { shift->() });
692 if (! -d $config{wikistatedir}) {
693 mkdir($config{wikistatedir});
695 my $newfile="$config{wikistatedir}/index.new";
696 my $cleanup = sub { unlink($newfile) };
697 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
698 foreach my $page (keys %pagemtime) {
699 next unless $pagemtime{$page};
700 my $line="mtime=$pagemtime{$page} ".
701 "ctime=$pagectime{$page} ".
702 "src=$pagesources{$page}";
703 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
705 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
706 if (exists $depends{$page}) {
707 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
709 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
711 close OUT || error("failed saving to $newfile: $!", $cleanup);
712 rename($newfile, "$config{wikistatedir}/index") ||
713 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
716 sub template_file ($) { #{{{
719 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
720 return "$dir/$template" if -e "$dir/$template";
725 sub template_params (@) { #{{{
726 my $filename=template_file(shift);
728 if (! defined $filename) {
733 require HTML::Template;
736 my $text_ref = shift;
737 $$text_ref=&Encode::decode_utf8($$text_ref);
739 filename => $filename,
740 loop_context_vars => 1,
741 die_on_bad_params => 0,
744 return wantarray ? @ret : {@ret};
747 sub template ($;@) { #{{{
748 HTML::Template->new(template_params(@_));
751 sub misctemplate ($$;@) { #{{{
755 my $template=template("misc.tmpl");
758 indexlink => indexlink(),
759 wikiname => $config{wikiname},
760 pagebody => $pagebody,
761 baseurl => baseurl(),
764 run_hooks(pagetemplate => sub {
765 shift->(page => "", destpage => "", template => $template);
767 return $template->output;
773 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
774 error "hook requires type, call, and id parameters";
777 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
779 $hooks{$param{type}}{$param{id}}=\%param;
782 sub run_hooks ($$) { # {{{
783 # Calls the given sub for each hook of the given type,
784 # passing it the hook function to call.
788 if (exists $hooks{$type}) {
790 foreach my $id (keys %{$hooks{$type}}) {
791 if ($hooks{$type}{$id}{last}) {
795 $sub->($hooks{$type}{$id}{call});
797 foreach my $id (@deferred) {
798 $sub->($hooks{$type}{$id}{call});
803 sub globlist_to_pagespec ($) { #{{{
804 my @globlist=split(' ', shift);
807 foreach my $glob (@globlist) {
808 if ($glob=~/^!(.*)/) {
816 my $spec=join(" or ", @spec);
818 my $skip=join(" and ", @skip);
820 $spec="$skip and ($spec)";
829 sub is_globlist ($) { #{{{
831 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
834 sub safequote ($) { #{{{
840 sub add_depends ($$) { #{{{
844 if (! exists $depends{$page}) {
845 $depends{$page}=$pagespec;
848 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
852 sub file_pruned ($$) { #{{{
854 my $file=File::Spec->canonpath(shift);
855 my $base=File::Spec->canonpath(shift);
856 $file=~s#^\Q$base\E/*##;
858 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
863 # Only use gettext in the rare cases it's needed.
864 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
865 if (! $gettext_obj) {
867 use Locale::gettext q{textdomain};
868 Locale::gettext->domain('ikiwiki')
876 return $gettext_obj->get(shift);
883 sub pagespec_merge ($$) { #{{{
887 return $a if $a eq $b;
889 # Support for old-style GlobLists.
890 if (is_globlist($a)) {
891 $a=globlist_to_pagespec($a);
893 if (is_globlist($b)) {
894 $b=globlist_to_pagespec($b);
897 return "($a) or ($b)";
900 sub pagespec_translate ($) { #{{{
901 # This assumes that $page is in scope in the function
902 # that evalulates the translated pagespec code.
905 # Support for old-style GlobLists.
906 if (is_globlist($spec)) {
907 $spec=globlist_to_pagespec($spec);
910 # Convert spec to perl code.
912 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
914 if (lc $word eq "and") {
917 elsif (lc $word eq "or") {
920 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
923 elsif ($word =~ /^(\w+)\((.*)\)$/) {
924 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
925 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
932 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
939 sub pagespec_match ($$;$) { #{{{
944 return eval pagespec_translate($spec);
947 package IkiWiki::PageSpec;
949 sub match_glob ($$$) { #{{{
953 if (! defined $from){
958 if ($glob =~ m!^\./!) {
961 $glob="$from/$glob" if length $from;
964 # turn glob into safe regexp
965 $glob=quotemeta($glob);
969 return $page=~/^$glob$/i;
972 sub match_link ($$$) { #{{{
976 if (! defined $from){
981 if ($link =~ m!^\.! && defined $from) {
984 $link="$from/$link" if length $from;
987 my $links = $IkiWiki::links{$page} or return undef;
988 return 0 unless @$links;
989 my $bestlink = IkiWiki::bestlink($from, $link);
990 foreach my $p (@$links) {
991 return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
996 sub match_backlink ($$$) { #{{{
997 match_link($_[1], $_[0], $_[3]);
1000 sub match_created_before ($$$) { #{{{
1004 if (exists $IkiWiki::pagectime{$testpage}) {
1005 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
1012 sub match_created_after ($$$) { #{{{
1016 if (exists $IkiWiki::pagectime{$testpage}) {
1017 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1024 sub match_creation_day ($$$) { #{{{
1025 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1028 sub match_creation_month ($$$) { #{{{
1029 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1032 sub match_creation_year ($$$) { #{{{
1033 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);