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 %destsources
13 %depends %hooks %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('err' => $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 foreach my $old (@{$renderedfiles{$page}}) {
332 delete $destsources{$old};
334 $renderedfiles{$page}=[$dest];
337 $destsources{$dest}=$page;
340 sub bestlink ($$) { #{{{
345 if ($link=~s/^\/+//) {
352 $l.="/" if length $l;
355 if (exists $links{$l}) {
358 elsif (exists $pagecase{lc $l}) {
359 return $pagecase{lc $l};
361 } while $cwd=~s!/?[^/]+$!!;
363 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
364 return "$config{userdir}/".lc($link);
367 #print STDERR "warning: page $page, broken link: $link\n";
371 sub isinlinableimage ($) { #{{{
374 $file=~/\.(png|gif|jpg|jpeg)$/i;
377 sub pagetitle ($;$) { #{{{
382 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
385 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
391 sub titlepage ($) { #{{{
393 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
397 sub linkpage ($) { #{{{
399 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
403 sub cgiurl (@) { #{{{
406 return $config{cgiurl}."?".
407 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
410 sub baseurl (;$) { #{{{
413 return "$config{url}/" if ! defined $page;
415 $page=htmlpage($page);
417 $page=~s/[^\/]+\//..\//g;
421 sub abs2rel ($$) { #{{{
422 # Work around very innefficient behavior in File::Spec if abs2rel
423 # is passed two relative paths. It's much faster if paths are
424 # absolute! (Debian bug #376658; fixed in debian unstable now)
429 my $ret=File::Spec->abs2rel($path, $base);
430 $ret=~s/^// if defined $ret;
434 sub displaytime ($) { #{{{
439 # strftime doesn't know about encodings, so make sure
440 # its output is properly treated as utf8
441 return decode_utf8(POSIX::strftime(
442 $config{timeformat}, localtime($time)));
445 sub beautify_url ($) { #{{{
448 $url =~ s!/index.html$!/!;
449 $url =~ s!^$!./!; # Browsers don't like empty links...
454 sub urlto ($$) { #{{{
459 return beautify_url(baseurl($from));
462 if (! $destsources{$to}) {
466 my $link = abs2rel($to, dirname(htmlpage($from)));
468 return beautify_url($link);
471 sub htmllink ($$$;@) { #{{{
472 my $lpage=shift; # the page doing the linking
473 my $page=shift; # the page that will contain the link (different for inline)
478 if (! $opts{forcesubpage}) {
479 $bestlink=bestlink($lpage, $link);
482 $bestlink="$lpage/".lc($link);
486 if (defined $opts{linktext}) {
487 $linktext=$opts{linktext};
490 $linktext=pagetitle(basename($link));
493 return "<span class=\"selflink\">$linktext</span>"
494 if length $bestlink && $page eq $bestlink;
496 if (! $destsources{$bestlink}) {
497 $bestlink=htmlpage($bestlink);
499 if (! $destsources{$bestlink}) {
500 return $linktext unless length $config{cgiurl};
501 return "<span><a href=\"".
504 page => pagetitle(lc($link), 1),
507 "\">?</a>$linktext</span>"
511 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
512 $bestlink=beautify_url($bestlink);
514 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
515 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
518 if (defined $opts{anchor}) {
519 $bestlink.="#".$opts{anchor};
522 return "<a href=\"$bestlink\">$linktext</a>";
525 sub htmlize ($$$) { #{{{
530 if (exists $hooks{htmlize}{$type}) {
531 $content=$hooks{htmlize}{$type}{call}->(
537 error("htmlization of $type not supported");
540 run_hooks(sanitize => sub {
550 sub linkify ($$$) { #{{{
551 my $lpage=shift; # the page containing the links
552 my $page=shift; # the page the link will end up on (different for inline)
555 $content =~ s{(\\?)$config{wiki_link_regexp}}{
558 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
559 : htmllink($lpage, $page, linkpage($3),
560 anchor => $4, linktext => pagetitle($2)))
562 ? "[[$3".($4 ? "#$4" : "")."]]"
563 : htmllink($lpage, $page, linkpage($3),
571 our $preprocess_preview=0;
572 sub preprocess ($$$;$$) { #{{{
573 my $page=shift; # the page the data comes from
574 my $destpage=shift; # the page the data will appear in (different for inline)
579 # Using local because it needs to be set within any nested calls
581 local $preprocess_preview=$preview if defined $preview;
587 if (length $escape) {
588 return "[[$command $params]]";
590 elsif (exists $hooks{preprocess}{$command}) {
591 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
592 # Note: preserve order of params, some plugins may
593 # consider it significant.
595 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
612 push @params, $key, $val;
615 push @params, $val, '';
618 if ($preprocessing{$page}++ > 3) {
619 # Avoid loops of preprocessed pages preprocessing
620 # other pages that preprocess them, etc.
621 #translators: The first parameter is a
622 #translators: preprocessor directive name,
623 #translators: the second a page name, the
624 #translators: third a number.
625 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
626 $command, $page, $preprocessing{$page}).
629 my $ret=$hooks{preprocess}{$command}{call}->(
632 destpage => $destpage,
633 preview => $preprocess_preview,
635 $preprocessing{$page}--;
639 return "[[$command $params]]";
643 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
647 sub filter ($$) { #{{{
651 run_hooks(filter => sub {
652 $content=shift->(page => $page, content => $content);
658 sub indexlink () { #{{{
659 return "<a href=\"$config{url}\">$config{wikiname}</a>";
662 sub lockwiki () { #{{{
663 # Take an exclusive lock on the wiki to prevent multiple concurrent
664 # run issues. The lock will be dropped on program exit.
665 if (! -d $config{wikistatedir}) {
666 mkdir($config{wikistatedir});
668 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
669 error ("cannot write to $config{wikistatedir}/lockfile: $!");
670 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
671 debug("wiki seems to be locked, waiting for lock");
672 my $wait=600; # arbitrary, but don't hang forever to
673 # prevent process pileup
675 return if flock(WIKILOCK, 2 | 4);
678 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
682 sub unlockwiki () { #{{{
686 sub commit_hook_enabled () { #{{{
687 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
688 error ("cannot write to $config{wikistatedir}/commitlock: $!");
689 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
697 sub disable_commit_hook () { #{{{
698 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
699 error ("cannot write to $config{wikistatedir}/commitlock: $!");
700 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
701 error("failed to get commit lock");
705 sub enable_commit_hook () { #{{{
709 sub loadindex () { #{{{
710 open (IN, "$config{wikistatedir}/index") || return;
712 $_=possibly_foolish_untaint($_);
717 foreach my $i (split(/ /, $_)) {
718 my ($item, $val)=split(/=/, $i, 2);
719 push @{$items{$item}}, decode_entities($val);
722 next unless exists $items{src}; # skip bad lines for now
724 my $page=pagename($items{src}[0]);
725 if (! $config{rebuild}) {
726 $pagesources{$page}=$items{src}[0];
727 $pagemtime{$page}=$items{mtime}[0];
728 $oldlinks{$page}=[@{$items{link}}];
729 $links{$page}=[@{$items{link}}];
730 $depends{$page}=$items{depends}[0] if exists $items{depends};
731 $destsources{$_}=$page foreach @{$items{dest}};
732 $renderedfiles{$page}=[@{$items{dest}}];
733 $oldrenderedfiles{$page}=[@{$items{dest}}];
734 $pagecase{lc $page}=$page;
736 $pagectime{$page}=$items{ctime}[0];
741 sub saveindex () { #{{{
742 run_hooks(savestate => sub { shift->() });
744 if (! -d $config{wikistatedir}) {
745 mkdir($config{wikistatedir});
747 my $newfile="$config{wikistatedir}/index.new";
748 my $cleanup = sub { unlink($newfile) };
749 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
750 foreach my $page (keys %pagemtime) {
751 next unless $pagemtime{$page};
752 my $line="mtime=$pagemtime{$page} ".
753 "ctime=$pagectime{$page} ".
754 "src=$pagesources{$page}";
755 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
757 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
758 if (exists $depends{$page}) {
759 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
761 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
763 close OUT || error("failed saving to $newfile: $!", $cleanup);
764 rename($newfile, "$config{wikistatedir}/index") ||
765 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
768 sub template_file ($) { #{{{
771 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
772 return "$dir/$template" if -e "$dir/$template";
777 sub template_params (@) { #{{{
778 my $filename=template_file(shift);
780 if (! defined $filename) {
785 require HTML::Template;
788 my $text_ref = shift;
789 $$text_ref=&Encode::decode_utf8($$text_ref);
791 filename => $filename,
792 loop_context_vars => 1,
793 die_on_bad_params => 0,
796 return wantarray ? @ret : {@ret};
799 sub template ($;@) { #{{{
800 HTML::Template->new(template_params(@_));
803 sub misctemplate ($$;@) { #{{{
807 my $template=template("misc.tmpl");
810 indexlink => indexlink(),
811 wikiname => $config{wikiname},
812 pagebody => $pagebody,
813 baseurl => baseurl(),
816 run_hooks(pagetemplate => sub {
817 shift->(page => "", destpage => "", template => $template);
819 return $template->output;
825 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
826 error "hook requires type, call, and id parameters";
829 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
831 $hooks{$param{type}}{$param{id}}=\%param;
834 sub run_hooks ($$) { # {{{
835 # Calls the given sub for each hook of the given type,
836 # passing it the hook function to call.
840 if (exists $hooks{$type}) {
842 foreach my $id (keys %{$hooks{$type}}) {
843 if ($hooks{$type}{$id}{last}) {
847 $sub->($hooks{$type}{$id}{call});
849 foreach my $id (@deferred) {
850 $sub->($hooks{$type}{$id}{call});
855 sub globlist_to_pagespec ($) { #{{{
856 my @globlist=split(' ', shift);
859 foreach my $glob (@globlist) {
860 if ($glob=~/^!(.*)/) {
868 my $spec=join(" or ", @spec);
870 my $skip=join(" and ", @skip);
872 $spec="$skip and ($spec)";
881 sub is_globlist ($) { #{{{
883 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
886 sub safequote ($) { #{{{
892 sub add_depends ($$) { #{{{
896 if (! exists $depends{$page}) {
897 $depends{$page}=$pagespec;
900 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
904 sub file_pruned ($$) { #{{{
906 my $file=File::Spec->canonpath(shift);
907 my $base=File::Spec->canonpath(shift);
908 $file=~s#^\Q$base\E/*##;
910 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
915 # Only use gettext in the rare cases it's needed.
916 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
917 if (! $gettext_obj) {
919 use Locale::gettext q{textdomain};
920 Locale::gettext->domain('ikiwiki')
928 return $gettext_obj->get(shift);
935 sub pagespec_merge ($$) { #{{{
939 return $a if $a eq $b;
941 # Support for old-style GlobLists.
942 if (is_globlist($a)) {
943 $a=globlist_to_pagespec($a);
945 if (is_globlist($b)) {
946 $b=globlist_to_pagespec($b);
949 return "($a) or ($b)";
952 sub pagespec_translate ($) { #{{{
953 # This assumes that $page is in scope in the function
954 # that evalulates the translated pagespec code.
957 # Support for old-style GlobLists.
958 if (is_globlist($spec)) {
959 $spec=globlist_to_pagespec($spec);
962 # Convert spec to perl code.
964 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
966 if (lc $word eq "and") {
969 elsif (lc $word eq "or") {
972 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
975 elsif ($word =~ /^(\w+)\((.*)\)$/) {
976 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
977 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
984 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
991 sub pagespec_match ($$;$) { #{{{
996 return eval pagespec_translate($spec);
999 package IkiWiki::PageSpec;
1001 sub match_glob ($$$) { #{{{
1005 if (! defined $from){
1010 if ($glob =~ m!^\./!) {
1011 $from=~s!/?[^/]+$!!;
1013 $glob="$from/$glob" if length $from;
1016 # turn glob into safe regexp
1017 $glob=quotemeta($glob);
1021 return $page=~/^$glob$/i;
1024 sub match_link ($$$) { #{{{
1028 if (! defined $from){
1033 if ($link =~ m!^\.! && defined $from) {
1034 $from=~s!/?[^/]+$!!;
1036 $link="$from/$link" if length $from;
1039 my $links = $IkiWiki::links{$page} or return undef;
1040 return 0 unless @$links;
1041 my $bestlink = IkiWiki::bestlink($from, $link);
1042 return 0 unless length $bestlink;
1043 foreach my $p (@$links) {
1044 return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
1049 sub match_backlink ($$$) { #{{{
1050 match_link($_[1], $_[0], $_[3]);
1053 sub match_created_before ($$$) { #{{{
1057 if (exists $IkiWiki::pagectime{$testpage}) {
1058 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
1065 sub match_created_after ($$$) { #{{{
1069 if (exists $IkiWiki::pagectime{$testpage}) {
1070 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1077 sub match_creation_day ($$$) { #{{{
1078 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1081 sub match_creation_month ($$$) { #{{{
1082 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1085 sub match_creation_year ($$$) { #{{{
1086 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);