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 urlto targetpage
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}],
79 sub checkconfig () { #{{{
80 # locale stuff; avoid LC_ALL since it overrides everything
81 if (defined $ENV{LC_ALL}) {
82 $ENV{LANG} = $ENV{LC_ALL};
85 if (defined $config{locale}) {
88 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
89 $ENV{LANG}=$config{locale};
94 if ($config{w3mmode}) {
95 eval q{use Cwd q{abs_path}};
97 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
98 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
99 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
100 unless $config{cgiurl} =~ m!file:///!;
101 $config{url}="file://".$config{destdir};
104 if ($config{cgi} && ! length $config{url}) {
105 error(gettext("Must specify url to wiki with --url when using --cgi"));
108 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
109 unless exists $config{wikistatedir};
112 eval qq{require IkiWiki::Rcs::$config{rcs}};
114 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
118 require IkiWiki::Rcs::Stub;
121 run_hooks(checkconfig => sub { shift->() });
124 sub loadplugins () { #{{{
125 loadplugin($_) foreach @{$config{plugin}};
127 run_hooks(getopt => sub { shift->() });
128 if (grep /^-/, @ARGV) {
129 print STDERR "Unknown option: $_\n"
130 foreach grep /^-/, @ARGV;
135 sub loadplugin ($) { #{{{
138 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
140 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
143 error("Failed to load plugin $mod: $@");
147 sub error ($;$) { #{{{
151 print "Content-type: text/html\n\n";
152 print misctemplate(gettext("Error"),
153 "<p>".gettext("Error").": $message</p>");
155 log_message(debug => $message) if $config{syslog};
156 if (defined $cleaner) {
163 return unless $config{verbose};
164 log_message(debug => @_);
168 sub log_message ($$) { #{{{
171 if ($config{syslog}) {
174 Sys::Syslog::setlogsock('unix');
175 Sys::Syslog::openlog('ikiwiki', '', 'user');
179 Sys::Syslog::syslog($type, "%s", join(" ", @_));
182 elsif (! $config{cgi}) {
190 sub possibly_foolish_untaint ($) { #{{{
192 my ($untainted)=$tainted=~/(.*)/;
196 sub basename ($) { #{{{
203 sub dirname ($) { #{{{
210 sub pagetype ($) { #{{{
213 if ($page =~ /\.([^.]+)$/) {
214 return $1 if exists $hooks{htmlize}{$1};
219 sub pagename ($) { #{{{
222 my $type=pagetype($file);
224 $page=~s/\Q.$type\E*$// if defined $type;
228 sub targetpage ($$) { #{{{
232 if (! $config{usedirs} || $page =~ /^index$/ ) {
233 return $page.".".$ext;
235 return $page."/index.".$ext;
239 sub htmlpage ($) { #{{{
242 return targetpage($page, "html");
245 sub srcfile ($) { #{{{
248 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
249 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
250 error("internal error: $file cannot be found");
253 sub readfile ($;$$) { #{{{
259 error("cannot read a symlink ($file)");
263 open (IN, $file) || error("failed to read $file: $!");
264 binmode(IN) if ($binary);
265 return \*IN if $wantfd;
267 close IN || error("failed to read $file: $!");
271 sub writefile ($$$;$$) { #{{{
272 my $file=shift; # can include subdirs
273 my $destdir=shift; # directory to put file in
279 while (length $test) {
280 if (-l "$destdir/$test") {
281 error("cannot write to a symlink ($test)");
283 $test=dirname($test);
285 my $newfile="$destdir/$file.ikiwiki-new";
287 error("cannot write to a symlink ($newfile)");
290 my $dir=dirname($newfile);
293 foreach my $s (split(m!/+!, $dir)) {
296 mkdir($d) || error("failed to create directory $d: $!");
301 my $cleanup = sub { unlink($newfile) };
302 open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
303 binmode(OUT) if ($binary);
305 $writer->(\*OUT, $cleanup);
308 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
310 close OUT || error("failed saving $newfile: $!", $cleanup);
311 rename($newfile, "$destdir/$file") ||
312 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
316 sub will_render ($$;$) { #{{{
321 # Important security check.
322 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
323 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
324 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
327 if (! $clear || $cleared{$page}) {
328 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
331 $renderedfiles{$page}=[$dest];
336 sub bestlink ($$) { #{{{
341 if ($link=~s/^\/+//) {
348 $l.="/" if length $l;
351 if (exists $links{$l}) {
354 elsif (exists $pagecase{lc $l}) {
355 return $pagecase{lc $l};
357 } while $cwd=~s!/?[^/]+$!!;
359 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
360 return "$config{userdir}/".lc($link);
363 #print STDERR "warning: page $page, broken link: $link\n";
367 sub isinlinableimage ($) { #{{{
370 $file=~/\.(png|gif|jpg|jpeg)$/i;
373 sub pagetitle ($;$) { #{{{
378 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
381 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
387 sub titlepage ($) { #{{{
389 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
393 sub linkpage ($) { #{{{
395 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
399 sub cgiurl (@) { #{{{
402 return $config{cgiurl}."?".
403 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
406 sub baseurl (;$) { #{{{
409 return "$config{url}/" if ! defined $page;
411 $page=htmlpage($page);
413 $page=~s/[^\/]+\//..\//g;
417 sub abs2rel ($$) { #{{{
418 # Work around very innefficient behavior in File::Spec if abs2rel
419 # is passed two relative paths. It's much faster if paths are
420 # absolute! (Debian bug #376658; fixed in debian unstable now)
425 my $ret=File::Spec->abs2rel($path, $base);
426 $ret=~s/^// if defined $ret;
430 sub displaytime ($) { #{{{
435 # strftime doesn't know about encodings, so make sure
436 # its output is properly treated as utf8
437 return decode_utf8(POSIX::strftime(
438 $config{timeformat}, localtime($time)));
441 sub beautify_url ($) { #{{{
444 $url =~ s!/index.html$!/!;
445 $url =~ s!^$!./!; # Browsers don't like empty links...
450 sub urlto ($$) { #{{{
455 return beautify_url(baseurl($from));
458 if (! grep { $_ eq $to } map { @{$_} } values %renderedfiles) {
462 my $link = abs2rel($to, dirname(htmlpage($from)));
464 return beautify_url($link);
467 sub htmllink ($$$;@) { #{{{
468 my $lpage=shift; # the page doing the linking
469 my $page=shift; # the page that will contain the link (different for inline)
474 if (! $opts{forcesubpage}) {
475 $bestlink=bestlink($lpage, $link);
478 $bestlink="$lpage/".lc($link);
482 if (defined $opts{linktext}) {
483 $linktext=$opts{linktext};
486 $linktext=pagetitle(basename($link));
489 return "<span class=\"selflink\">$linktext</span>"
490 if length $bestlink && $page eq $bestlink;
492 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
493 $bestlink=htmlpage($bestlink);
495 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
496 return $linktext unless length $config{cgiurl};
497 return "<span><a href=\"".
500 page => pagetitle(lc($link), 1),
503 "\">?</a>$linktext</span>"
506 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
507 $bestlink=beautify_url($bestlink);
509 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
510 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
513 if (defined $opts{anchor}) {
514 $bestlink.="#".$opts{anchor};
517 return "<a href=\"$bestlink\">$linktext</a>";
520 sub htmlize ($$$) { #{{{
525 if (exists $hooks{htmlize}{$type}) {
526 $content=$hooks{htmlize}{$type}{call}->(
532 error("htmlization of $type not supported");
535 run_hooks(sanitize => sub {
545 sub linkify ($$$) { #{{{
546 my $lpage=shift; # the page containing the links
547 my $page=shift; # the page the link will end up on (different for inline)
550 $content =~ s{(\\?)$config{wiki_link_regexp}}{
552 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4, linktext => pagetitle($2)))
553 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4))
560 our $preprocess_preview=0;
561 sub preprocess ($$$;$$) { #{{{
562 my $page=shift; # the page the data comes from
563 my $destpage=shift; # the page the data will appear in (different for inline)
568 # Using local because it needs to be set within any nested calls
570 local $preprocess_preview=$preview if defined $preview;
576 if (length $escape) {
577 return "[[$command $params]]";
579 elsif (exists $hooks{preprocess}{$command}) {
580 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
581 # Note: preserve order of params, some plugins may
582 # consider it significant.
584 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
601 push @params, $key, $val;
604 push @params, $val, '';
607 if ($preprocessing{$page}++ > 3) {
608 # Avoid loops of preprocessed pages preprocessing
609 # other pages that preprocess them, etc.
610 #translators: The first parameter is a
611 #translators: preprocessor directive name,
612 #translators: the second a page name, the
613 #translators: third a number.
614 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
615 $command, $page, $preprocessing{$page}).
618 my $ret=$hooks{preprocess}{$command}{call}->(
621 destpage => $destpage,
622 preview => $preprocess_preview,
624 $preprocessing{$page}--;
628 return "[[$command $params]]";
632 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
636 sub filter ($$) { #{{{
640 run_hooks(filter => sub {
641 $content=shift->(page => $page, content => $content);
647 sub indexlink () { #{{{
648 return "<a href=\"$config{url}\">$config{wikiname}</a>";
651 sub lockwiki () { #{{{
652 # Take an exclusive lock on the wiki to prevent multiple concurrent
653 # run issues. The lock will be dropped on program exit.
654 if (! -d $config{wikistatedir}) {
655 mkdir($config{wikistatedir});
657 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
658 error ("cannot write to $config{wikistatedir}/lockfile: $!");
659 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
660 debug("wiki seems to be locked, waiting for lock");
661 my $wait=600; # arbitrary, but don't hang forever to
662 # prevent process pileup
664 return if flock(WIKILOCK, 2 | 4);
667 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
671 sub unlockwiki () { #{{{
675 sub commit_hook_enabled () { #{{{
676 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
677 error ("cannot write to $config{wikistatedir}/commitlock: $!");
678 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
686 sub disable_commit_hook () { #{{{
687 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
688 error ("cannot write to $config{wikistatedir}/commitlock: $!");
689 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
690 error("failed to get commit lock");
694 sub enable_commit_hook () { #{{{
698 sub loadindex () { #{{{
699 open (IN, "$config{wikistatedir}/index") || return;
701 $_=possibly_foolish_untaint($_);
706 foreach my $i (split(/ /, $_)) {
707 my ($item, $val)=split(/=/, $i, 2);
708 push @{$items{$item}}, decode_entities($val);
711 next unless exists $items{src}; # skip bad lines for now
713 my $page=pagename($items{src}[0]);
714 if (! $config{rebuild}) {
715 $pagesources{$page}=$items{src}[0];
716 $pagemtime{$page}=$items{mtime}[0];
717 $oldlinks{$page}=[@{$items{link}}];
718 $links{$page}=[@{$items{link}}];
719 $depends{$page}=$items{depends}[0] if exists $items{depends};
720 $renderedfiles{$page}=[@{$items{dest}}];
721 $oldrenderedfiles{$page}=[@{$items{dest}}];
722 $pagecase{lc $page}=$page;
724 $pagectime{$page}=$items{ctime}[0];
729 sub saveindex () { #{{{
730 run_hooks(savestate => sub { shift->() });
732 if (! -d $config{wikistatedir}) {
733 mkdir($config{wikistatedir});
735 my $newfile="$config{wikistatedir}/index.new";
736 my $cleanup = sub { unlink($newfile) };
737 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
738 foreach my $page (keys %pagemtime) {
739 next unless $pagemtime{$page};
740 my $line="mtime=$pagemtime{$page} ".
741 "ctime=$pagectime{$page} ".
742 "src=$pagesources{$page}";
743 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
745 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
746 if (exists $depends{$page}) {
747 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
749 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
751 close OUT || error("failed saving to $newfile: $!", $cleanup);
752 rename($newfile, "$config{wikistatedir}/index") ||
753 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
756 sub template_file ($) { #{{{
759 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
760 return "$dir/$template" if -e "$dir/$template";
765 sub template_params (@) { #{{{
766 my $filename=template_file(shift);
768 if (! defined $filename) {
773 require HTML::Template;
776 my $text_ref = shift;
777 $$text_ref=&Encode::decode_utf8($$text_ref);
779 filename => $filename,
780 loop_context_vars => 1,
781 die_on_bad_params => 0,
784 return wantarray ? @ret : {@ret};
787 sub template ($;@) { #{{{
788 HTML::Template->new(template_params(@_));
791 sub misctemplate ($$;@) { #{{{
795 my $template=template("misc.tmpl");
798 indexlink => indexlink(),
799 wikiname => $config{wikiname},
800 pagebody => $pagebody,
801 baseurl => baseurl(),
804 run_hooks(pagetemplate => sub {
805 shift->(page => "", destpage => "", template => $template);
807 return $template->output;
813 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
814 error "hook requires type, call, and id parameters";
817 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
819 $hooks{$param{type}}{$param{id}}=\%param;
822 sub run_hooks ($$) { # {{{
823 # Calls the given sub for each hook of the given type,
824 # passing it the hook function to call.
828 if (exists $hooks{$type}) {
830 foreach my $id (keys %{$hooks{$type}}) {
831 if ($hooks{$type}{$id}{last}) {
835 $sub->($hooks{$type}{$id}{call});
837 foreach my $id (@deferred) {
838 $sub->($hooks{$type}{$id}{call});
843 sub globlist_to_pagespec ($) { #{{{
844 my @globlist=split(' ', shift);
847 foreach my $glob (@globlist) {
848 if ($glob=~/^!(.*)/) {
856 my $spec=join(" or ", @spec);
858 my $skip=join(" and ", @skip);
860 $spec="$skip and ($spec)";
869 sub is_globlist ($) { #{{{
871 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
874 sub safequote ($) { #{{{
880 sub add_depends ($$) { #{{{
884 if (! exists $depends{$page}) {
885 $depends{$page}=$pagespec;
888 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
892 sub file_pruned ($$) { #{{{
894 my $file=File::Spec->canonpath(shift);
895 my $base=File::Spec->canonpath(shift);
896 $file=~s#^\Q$base\E/*##;
898 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
903 # Only use gettext in the rare cases it's needed.
904 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
905 if (! $gettext_obj) {
907 use Locale::gettext q{textdomain};
908 Locale::gettext->domain('ikiwiki')
916 return $gettext_obj->get(shift);
923 sub pagespec_merge ($$) { #{{{
927 return $a if $a eq $b;
929 # Support for old-style GlobLists.
930 if (is_globlist($a)) {
931 $a=globlist_to_pagespec($a);
933 if (is_globlist($b)) {
934 $b=globlist_to_pagespec($b);
937 return "($a) or ($b)";
940 sub pagespec_translate ($) { #{{{
941 # This assumes that $page is in scope in the function
942 # that evalulates the translated pagespec code.
945 # Support for old-style GlobLists.
946 if (is_globlist($spec)) {
947 $spec=globlist_to_pagespec($spec);
950 # Convert spec to perl code.
952 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
954 if (lc $word eq "and") {
957 elsif (lc $word eq "or") {
960 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
963 elsif ($word =~ /^(\w+)\((.*)\)$/) {
964 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
965 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
972 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
979 sub pagespec_match ($$;$) { #{{{
984 return eval pagespec_translate($spec);
987 package IkiWiki::PageSpec;
989 sub match_glob ($$$) { #{{{
993 if (! defined $from){
998 if ($glob =~ m!^\./!) {
1001 $glob="$from/$glob" if length $from;
1004 # turn glob into safe regexp
1005 $glob=quotemeta($glob);
1009 return $page=~/^$glob$/i;
1012 sub match_link ($$$) { #{{{
1016 if (! defined $from){
1021 if ($link =~ m!^\.! && defined $from) {
1022 $from=~s!/?[^/]+$!!;
1024 $link="$from/$link" if length $from;
1027 my $links = $IkiWiki::links{$page} or return undef;
1028 return 0 unless @$links;
1029 my $bestlink = IkiWiki::bestlink($from, $link);
1030 foreach my $p (@$links) {
1031 return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
1036 sub match_backlink ($$$) { #{{{
1037 match_link($_[1], $_[0], $_[3]);
1040 sub match_created_before ($$$) { #{{{
1044 if (exists $IkiWiki::pagectime{$testpage}) {
1045 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
1052 sub match_created_after ($$$) { #{{{
1056 if (exists $IkiWiki::pagectime{$testpage}) {
1057 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1064 sub match_creation_day ($$$) { #{{{
1065 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1068 sub match_creation_month ($$$) { #{{{
1069 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1072 sub match_creation_year ($$$) { #{{{
1073 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);