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}}{
553 ? "[[$2|$3".(length $4 ? "#$4" : "")."]]"
554 : htmllink($lpage, $page, linkpage($3),
555 anchor => $4, linktext => pagetitle($2)))
557 ? "[[$3".(length $4 ? "#$4" : "")."]]"
558 : htmllink($lpage, $page, linkpage($3),
566 our $preprocess_preview=0;
567 sub preprocess ($$$;$$) { #{{{
568 my $page=shift; # the page the data comes from
569 my $destpage=shift; # the page the data will appear in (different for inline)
574 # Using local because it needs to be set within any nested calls
576 local $preprocess_preview=$preview if defined $preview;
582 if (length $escape) {
583 return "[[$command $params]]";
585 elsif (exists $hooks{preprocess}{$command}) {
586 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
587 # Note: preserve order of params, some plugins may
588 # consider it significant.
590 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
607 push @params, $key, $val;
610 push @params, $val, '';
613 if ($preprocessing{$page}++ > 3) {
614 # Avoid loops of preprocessed pages preprocessing
615 # other pages that preprocess them, etc.
616 #translators: The first parameter is a
617 #translators: preprocessor directive name,
618 #translators: the second a page name, the
619 #translators: third a number.
620 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
621 $command, $page, $preprocessing{$page}).
624 my $ret=$hooks{preprocess}{$command}{call}->(
627 destpage => $destpage,
628 preview => $preprocess_preview,
630 $preprocessing{$page}--;
634 return "[[$command $params]]";
638 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
642 sub filter ($$) { #{{{
646 run_hooks(filter => sub {
647 $content=shift->(page => $page, content => $content);
653 sub indexlink () { #{{{
654 return "<a href=\"$config{url}\">$config{wikiname}</a>";
657 sub lockwiki () { #{{{
658 # Take an exclusive lock on the wiki to prevent multiple concurrent
659 # run issues. The lock will be dropped on program exit.
660 if (! -d $config{wikistatedir}) {
661 mkdir($config{wikistatedir});
663 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
664 error ("cannot write to $config{wikistatedir}/lockfile: $!");
665 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
666 debug("wiki seems to be locked, waiting for lock");
667 my $wait=600; # arbitrary, but don't hang forever to
668 # prevent process pileup
670 return if flock(WIKILOCK, 2 | 4);
673 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
677 sub unlockwiki () { #{{{
681 sub commit_hook_enabled () { #{{{
682 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
683 error ("cannot write to $config{wikistatedir}/commitlock: $!");
684 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
692 sub disable_commit_hook () { #{{{
693 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
694 error ("cannot write to $config{wikistatedir}/commitlock: $!");
695 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
696 error("failed to get commit lock");
700 sub enable_commit_hook () { #{{{
704 sub loadindex () { #{{{
705 open (IN, "$config{wikistatedir}/index") || return;
707 $_=possibly_foolish_untaint($_);
712 foreach my $i (split(/ /, $_)) {
713 my ($item, $val)=split(/=/, $i, 2);
714 push @{$items{$item}}, decode_entities($val);
717 next unless exists $items{src}; # skip bad lines for now
719 my $page=pagename($items{src}[0]);
720 if (! $config{rebuild}) {
721 $pagesources{$page}=$items{src}[0];
722 $pagemtime{$page}=$items{mtime}[0];
723 $oldlinks{$page}=[@{$items{link}}];
724 $links{$page}=[@{$items{link}}];
725 $depends{$page}=$items{depends}[0] if exists $items{depends};
726 $renderedfiles{$page}=[@{$items{dest}}];
727 $oldrenderedfiles{$page}=[@{$items{dest}}];
728 $pagecase{lc $page}=$page;
730 $pagectime{$page}=$items{ctime}[0];
735 sub saveindex () { #{{{
736 run_hooks(savestate => sub { shift->() });
738 if (! -d $config{wikistatedir}) {
739 mkdir($config{wikistatedir});
741 my $newfile="$config{wikistatedir}/index.new";
742 my $cleanup = sub { unlink($newfile) };
743 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
744 foreach my $page (keys %pagemtime) {
745 next unless $pagemtime{$page};
746 my $line="mtime=$pagemtime{$page} ".
747 "ctime=$pagectime{$page} ".
748 "src=$pagesources{$page}";
749 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
751 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
752 if (exists $depends{$page}) {
753 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
755 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
757 close OUT || error("failed saving to $newfile: $!", $cleanup);
758 rename($newfile, "$config{wikistatedir}/index") ||
759 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
762 sub template_file ($) { #{{{
765 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
766 return "$dir/$template" if -e "$dir/$template";
771 sub template_params (@) { #{{{
772 my $filename=template_file(shift);
774 if (! defined $filename) {
779 require HTML::Template;
782 my $text_ref = shift;
783 $$text_ref=&Encode::decode_utf8($$text_ref);
785 filename => $filename,
786 loop_context_vars => 1,
787 die_on_bad_params => 0,
790 return wantarray ? @ret : {@ret};
793 sub template ($;@) { #{{{
794 HTML::Template->new(template_params(@_));
797 sub misctemplate ($$;@) { #{{{
801 my $template=template("misc.tmpl");
804 indexlink => indexlink(),
805 wikiname => $config{wikiname},
806 pagebody => $pagebody,
807 baseurl => baseurl(),
810 run_hooks(pagetemplate => sub {
811 shift->(page => "", destpage => "", template => $template);
813 return $template->output;
819 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
820 error "hook requires type, call, and id parameters";
823 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
825 $hooks{$param{type}}{$param{id}}=\%param;
828 sub run_hooks ($$) { # {{{
829 # Calls the given sub for each hook of the given type,
830 # passing it the hook function to call.
834 if (exists $hooks{$type}) {
836 foreach my $id (keys %{$hooks{$type}}) {
837 if ($hooks{$type}{$id}{last}) {
841 $sub->($hooks{$type}{$id}{call});
843 foreach my $id (@deferred) {
844 $sub->($hooks{$type}{$id}{call});
849 sub globlist_to_pagespec ($) { #{{{
850 my @globlist=split(' ', shift);
853 foreach my $glob (@globlist) {
854 if ($glob=~/^!(.*)/) {
862 my $spec=join(" or ", @spec);
864 my $skip=join(" and ", @skip);
866 $spec="$skip and ($spec)";
875 sub is_globlist ($) { #{{{
877 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
880 sub safequote ($) { #{{{
886 sub add_depends ($$) { #{{{
890 if (! exists $depends{$page}) {
891 $depends{$page}=$pagespec;
894 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
898 sub file_pruned ($$) { #{{{
900 my $file=File::Spec->canonpath(shift);
901 my $base=File::Spec->canonpath(shift);
902 $file=~s#^\Q$base\E/*##;
904 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
909 # Only use gettext in the rare cases it's needed.
910 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
911 if (! $gettext_obj) {
913 use Locale::gettext q{textdomain};
914 Locale::gettext->domain('ikiwiki')
922 return $gettext_obj->get(shift);
929 sub pagespec_merge ($$) { #{{{
933 return $a if $a eq $b;
935 # Support for old-style GlobLists.
936 if (is_globlist($a)) {
937 $a=globlist_to_pagespec($a);
939 if (is_globlist($b)) {
940 $b=globlist_to_pagespec($b);
943 return "($a) or ($b)";
946 sub pagespec_translate ($) { #{{{
947 # This assumes that $page is in scope in the function
948 # that evalulates the translated pagespec code.
951 # Support for old-style GlobLists.
952 if (is_globlist($spec)) {
953 $spec=globlist_to_pagespec($spec);
956 # Convert spec to perl code.
958 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
960 if (lc $word eq "and") {
963 elsif (lc $word eq "or") {
966 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
969 elsif ($word =~ /^(\w+)\((.*)\)$/) {
970 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
971 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
978 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
985 sub pagespec_match ($$;$) { #{{{
990 return eval pagespec_translate($spec);
993 package IkiWiki::PageSpec;
995 sub match_glob ($$$) { #{{{
999 if (! defined $from){
1004 if ($glob =~ m!^\./!) {
1005 $from=~s!/?[^/]+$!!;
1007 $glob="$from/$glob" if length $from;
1010 # turn glob into safe regexp
1011 $glob=quotemeta($glob);
1015 return $page=~/^$glob$/i;
1018 sub match_link ($$$) { #{{{
1022 if (! defined $from){
1027 if ($link =~ m!^\.! && defined $from) {
1028 $from=~s!/?[^/]+$!!;
1030 $link="$from/$link" if length $from;
1033 my $links = $IkiWiki::links{$page} or return undef;
1034 return 0 unless @$links;
1035 my $bestlink = IkiWiki::bestlink($from, $link);
1036 return 0 unless length $bestlink;
1037 foreach my $p (@$links) {
1038 return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
1043 sub match_backlink ($$$) { #{{{
1044 match_link($_[1], $_[0], $_[3]);
1047 sub match_created_before ($$$) { #{{{
1051 if (exists $IkiWiki::pagectime{$testpage}) {
1052 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
1059 sub match_created_after ($$$) { #{{{
1063 if (exists $IkiWiki::pagectime{$testpage}) {
1064 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1071 sub match_creation_day ($$$) { #{{{
1072 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1075 sub match_creation_month ($$$) { #{{{
1076 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1079 sub match_creation_year ($$$) { #{{{
1080 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);