8 use URI::Escape q{uri_escape_utf8};
9 use open qw{:utf8 :std};
11 use vars qw{%config %links %oldlinks %oldpagemtime %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}],
77 sub checkconfig () { #{{{
78 # locale stuff; avoid LC_ALL since it overrides everything
79 if (defined $ENV{LC_ALL}) {
80 $ENV{LANG} = $ENV{LC_ALL};
83 if (defined $config{locale}) {
86 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
87 $ENV{LANG}=$config{locale};
92 if ($config{w3mmode}) {
93 eval q{use Cwd q{abs_path}};
95 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
96 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
97 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
98 unless $config{cgiurl} =~ m!file:///!;
99 $config{url}="file://".$config{destdir};
102 if ($config{cgi} && ! length $config{url}) {
103 error(gettext("Must specify url to wiki with --url when using --cgi"));
106 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
107 unless exists $config{wikistatedir};
110 eval qq{require IkiWiki::Rcs::$config{rcs}};
112 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
116 require IkiWiki::Rcs::Stub;
119 run_hooks(checkconfig => sub { shift->() });
122 sub loadplugins () { #{{{
123 loadplugin($_) foreach @{$config{plugin}};
125 run_hooks(getopt => sub { shift->() });
126 if (grep /^-/, @ARGV) {
127 print STDERR "Unknown option: $_\n"
128 foreach grep /^-/, @ARGV;
133 sub loadplugin ($) { #{{{
136 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
138 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
141 error("Failed to load plugin $mod: $@");
145 sub error ($;$) { #{{{
149 print "Content-type: text/html\n\n";
150 print misctemplate(gettext("Error"),
151 "<p>".gettext("Error").": $message</p>");
153 log_message(debug => $message) if $config{syslog};
154 if (defined $cleaner) {
161 return unless $config{verbose};
162 log_message(debug => @_);
166 sub log_message ($$) { #{{{
169 if ($config{syslog}) {
172 Sys::Syslog::setlogsock('unix');
173 Sys::Syslog::openlog('ikiwiki', '', 'user');
177 Sys::Syslog::syslog($type, "%s", join(" ", @_));
180 elsif (! $config{cgi}) {
188 sub possibly_foolish_untaint ($) { #{{{
190 my ($untainted)=$tainted=~/(.*)/;
194 sub basename ($) { #{{{
201 sub dirname ($) { #{{{
208 sub pagetype ($) { #{{{
211 if ($page =~ /\.([^.]+)$/) {
212 return $1 if exists $hooks{htmlize}{$1};
217 sub pagename ($) { #{{{
220 my $type=pagetype($file);
222 $page=~s/\Q.$type\E*$// if defined $type;
226 sub htmlpage ($) { #{{{
229 return $page.".html";
232 sub srcfile ($) { #{{{
235 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
236 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
237 error("internal error: $file cannot be found");
240 sub readfile ($;$$) { #{{{
246 error("cannot read a symlink ($file)");
250 open (IN, $file) || error("failed to read $file: $!");
251 binmode(IN) if ($binary);
252 return \*IN if $wantfd;
254 close IN || error("failed to read $file: $!");
258 sub writefile ($$$;$$) { #{{{
259 my $file=shift; # can include subdirs
260 my $destdir=shift; # directory to put file in
266 while (length $test) {
267 if (-l "$destdir/$test") {
268 error("cannot write to a symlink ($test)");
270 $test=dirname($test);
272 my $newfile="$destdir/$file.ikiwiki-new";
274 error("cannot write to a symlink ($newfile)");
277 my $dir=dirname($newfile);
280 foreach my $s (split(m!/+!, $dir)) {
283 mkdir($d) || error("failed to create directory $d: $!");
288 my $cleanup = sub { unlink($newfile) };
289 open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
290 binmode(OUT) if ($binary);
292 $writer->(\*OUT, $cleanup);
295 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
297 close OUT || error("failed saving $newfile: $!", $cleanup);
298 rename($newfile, "$destdir/$file") ||
299 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
303 sub will_render ($$;$) { #{{{
308 # Important security check.
309 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
310 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
311 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
314 if (! $clear || $cleared{$page}) {
315 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
318 $renderedfiles{$page}=[$dest];
323 sub bestlink ($$) { #{{{
328 if ($link=~s/^\/+//) {
335 $l.="/" if length $l;
338 if (exists $links{$l}) {
341 elsif (exists $pagecase{lc $l}) {
342 return $pagecase{lc $l};
344 } while $cwd=~s!/?[^/]+$!!;
346 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
347 return "$config{userdir}/".lc($link);
350 #print STDERR "warning: page $page, broken link: $link\n";
354 sub isinlinableimage ($) { #{{{
357 $file=~/\.(png|gif|jpg|jpeg)$/i;
360 sub pagetitle ($;$) { #{{{
365 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
368 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
374 sub titlepage ($) { #{{{
376 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
380 sub linkpage ($) { #{{{
382 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
386 sub cgiurl (@) { #{{{
389 return $config{cgiurl}."?".
390 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
393 sub baseurl (;$) { #{{{
396 return "$config{url}/" if ! defined $page;
399 $page=~s/[^\/]+\//..\//g;
403 sub abs2rel ($$) { #{{{
404 # Work around very innefficient behavior in File::Spec if abs2rel
405 # is passed two relative paths. It's much faster if paths are
406 # absolute! (Debian bug #376658; fixed in debian unstable now)
411 my $ret=File::Spec->abs2rel($path, $base);
412 $ret=~s/^// if defined $ret;
416 sub displaytime ($) { #{{{
421 # strftime doesn't know about encodings, so make sure
422 # its output is properly treated as utf8
423 return decode_utf8(POSIX::strftime(
424 $config{timeformat}, localtime($time)));
427 sub htmllink ($$$;@) { #{{{
428 my $lpage=shift; # the page doing the linking
429 my $page=shift; # the page that will contain the link (different for inline)
434 if (! $opts{forcesubpage}) {
435 $bestlink=bestlink($lpage, $link);
438 $bestlink="$lpage/".lc($link);
442 if (defined $opts{linktext}) {
443 $linktext=$opts{linktext};
446 $linktext=pagetitle(basename($link));
449 return "<span class=\"selflink\">$linktext</span>"
450 if length $bestlink && $page eq $bestlink;
452 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
453 $bestlink=htmlpage($bestlink);
455 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
456 return $linktext unless length $config{cgiurl};
457 return "<span><a href=\"".
460 page => pagetitle(lc($link), 1),
463 "\">?</a>$linktext</span>"
466 $bestlink=abs2rel($bestlink, dirname($page));
468 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
469 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
472 if (defined $opts{anchor}) {
473 $bestlink.="#".$opts{anchor};
476 return "<a href=\"$bestlink\">$linktext</a>";
479 sub htmlize ($$$) { #{{{
484 if (exists $hooks{htmlize}{$type}) {
485 $content=$hooks{htmlize}{$type}{call}->(
491 error("htmlization of $type not supported");
494 run_hooks(sanitize => sub {
504 sub linkify ($$$) { #{{{
505 my $lpage=shift; # the page containing the links
506 my $page=shift; # the page the link will end up on (different for inline)
509 $content =~ s{(\\?)$config{wiki_link_regexp}}{
511 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4, linktext => pagetitle($2)))
512 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4))
519 our $preprocess_preview=0;
520 sub preprocess ($$$;$$) { #{{{
521 my $page=shift; # the page the data comes from
522 my $destpage=shift; # the page the data will appear in (different for inline)
527 # Using local because it needs to be set within any nested calls
529 local $preprocess_preview=$preview if defined $preview;
535 if (length $escape) {
536 return "[[$command $params]]";
538 elsif (exists $hooks{preprocess}{$command}) {
539 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
540 # Note: preserve order of params, some plugins may
541 # consider it significant.
543 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
560 push @params, $key, $val;
563 push @params, $val, '';
566 if ($preprocessing{$page}++ > 3) {
567 # Avoid loops of preprocessed pages preprocessing
568 # other pages that preprocess them, etc.
569 #translators: The first parameter is a
570 #translators: preprocessor directive name,
571 #translators: the second a page name, the
572 #translators: third a number.
573 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
574 $command, $page, $preprocessing{$page}).
577 my $ret=$hooks{preprocess}{$command}{call}->(
580 destpage => $destpage,
581 preview => $preprocess_preview,
583 $preprocessing{$page}--;
587 return "[[$command $params]]";
591 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
595 sub filter ($$) { #{{{
599 run_hooks(filter => sub {
600 $content=shift->(page => $page, content => $content);
606 sub indexlink () { #{{{
607 return "<a href=\"$config{url}\">$config{wikiname}</a>";
610 sub lockwiki () { #{{{
611 # Take an exclusive lock on the wiki to prevent multiple concurrent
612 # run issues. The lock will be dropped on program exit.
613 if (! -d $config{wikistatedir}) {
614 mkdir($config{wikistatedir});
616 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
617 error ("cannot write to $config{wikistatedir}/lockfile: $!");
618 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
619 debug("wiki seems to be locked, waiting for lock");
620 my $wait=600; # arbitrary, but don't hang forever to
621 # prevent process pileup
623 return if flock(WIKILOCK, 2 | 4);
626 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
630 sub unlockwiki () { #{{{
634 sub commit_hook_enabled () { #{{{
635 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
636 error ("cannot write to $config{wikistatedir}/commitlock: $!");
637 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
645 sub disable_commit_hook () { #{{{
646 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
647 error ("cannot write to $config{wikistatedir}/commitlock: $!");
648 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
649 error("failed to get commit lock");
653 sub enable_commit_hook () { #{{{
657 sub loadindex () { #{{{
658 open (IN, "$config{wikistatedir}/index") || return;
660 $_=possibly_foolish_untaint($_);
665 foreach my $i (split(/ /, $_)) {
666 my ($item, $val)=split(/=/, $i, 2);
667 push @{$items{$item}}, decode_entities($val);
670 next unless exists $items{src}; # skip bad lines for now
672 my $page=pagename($items{src}[0]);
673 if (! $config{rebuild}) {
674 $pagesources{$page}=$items{src}[0];
675 $oldpagemtime{$page}=$items{mtime}[0];
676 $oldlinks{$page}=[@{$items{link}}];
677 $links{$page}=[@{$items{link}}];
678 $depends{$page}=$items{depends}[0] if exists $items{depends};
679 $renderedfiles{$page}=[@{$items{dest}}];
680 $oldrenderedfiles{$page}=[@{$items{dest}}];
681 $pagecase{lc $page}=$page;
683 $pagectime{$page}=$items{ctime}[0];
688 sub saveindex () { #{{{
689 run_hooks(savestate => sub { shift->() });
691 if (! -d $config{wikistatedir}) {
692 mkdir($config{wikistatedir});
694 my $newfile="$config{wikistatedir}/index.new";
695 my $cleanup = sub { unlink($newfile) };
696 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
697 foreach my $page (keys %oldpagemtime) {
698 next unless $oldpagemtime{$page};
699 my $line="mtime=$oldpagemtime{$page} ".
700 "ctime=$pagectime{$page} ".
701 "src=$pagesources{$page}";
702 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
704 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
705 if (exists $depends{$page}) {
706 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
708 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
710 close OUT || error("failed saving to $newfile: $!", $cleanup);
711 rename($newfile, "$config{wikistatedir}/index") ||
712 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
715 sub template_file ($) { #{{{
718 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
719 return "$dir/$template" if -e "$dir/$template";
724 sub template_params (@) { #{{{
725 my $filename=template_file(shift);
727 if (! defined $filename) {
732 require HTML::Template;
735 my $text_ref = shift;
736 $$text_ref=&Encode::decode_utf8($$text_ref);
738 filename => $filename,
739 loop_context_vars => 1,
740 die_on_bad_params => 0,
743 return wantarray ? @ret : {@ret};
746 sub template ($;@) { #{{{
747 HTML::Template->new(template_params(@_));
750 sub misctemplate ($$;@) { #{{{
754 my $template=template("misc.tmpl");
757 indexlink => indexlink(),
758 wikiname => $config{wikiname},
759 pagebody => $pagebody,
760 baseurl => baseurl(),
763 run_hooks(pagetemplate => sub {
764 shift->(page => "", destpage => "", template => $template);
766 return $template->output;
772 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
773 error "hook requires type, call, and id parameters";
776 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
778 $hooks{$param{type}}{$param{id}}=\%param;
781 sub run_hooks ($$) { # {{{
782 # Calls the given sub for each hook of the given type,
783 # passing it the hook function to call.
787 if (exists $hooks{$type}) {
789 foreach my $id (keys %{$hooks{$type}}) {
790 if ($hooks{$type}{$id}{last}) {
794 $sub->($hooks{$type}{$id}{call});
796 foreach my $id (@deferred) {
797 $sub->($hooks{$type}{$id}{call});
802 sub globlist_to_pagespec ($) { #{{{
803 my @globlist=split(' ', shift);
806 foreach my $glob (@globlist) {
807 if ($glob=~/^!(.*)/) {
815 my $spec=join(" or ", @spec);
817 my $skip=join(" and ", @skip);
819 $spec="$skip and ($spec)";
828 sub is_globlist ($) { #{{{
830 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
833 sub safequote ($) { #{{{
839 sub add_depends ($$) { #{{{
843 if (! exists $depends{$page}) {
844 $depends{$page}=$pagespec;
847 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
851 sub file_pruned ($$) { #{{{
853 my $file=File::Spec->canonpath(shift);
854 my $base=File::Spec->canonpath(shift);
855 $file=~s#^\Q$base\E/*##;
857 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
862 # Only use gettext in the rare cases it's needed.
863 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
864 if (! $gettext_obj) {
866 use Locale::gettext q{textdomain};
867 Locale::gettext->domain('ikiwiki')
875 return $gettext_obj->get(shift);
882 sub pagespec_merge ($$) { #{{{
886 return $a if $a eq $b;
888 # Support for old-style GlobLists.
889 if (is_globlist($a)) {
890 $a=globlist_to_pagespec($a);
892 if (is_globlist($b)) {
893 $b=globlist_to_pagespec($b);
896 return "($a) or ($b)";
899 sub pagespec_translate ($) { #{{{
900 # This assumes that $page is in scope in the function
901 # that evalulates the translated pagespec code.
904 # Support for old-style GlobLists.
905 if (is_globlist($spec)) {
906 $spec=globlist_to_pagespec($spec);
909 # Convert spec to perl code.
911 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
913 if (lc $word eq "and") {
916 elsif (lc $word eq "or") {
919 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
922 elsif ($word =~ /^(\w+)\((.*)\)$/) {
923 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
924 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
931 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
938 sub pagespec_match ($$;$) { #{{{
943 return eval pagespec_translate($spec);
946 package IkiWiki::PageSpec;
948 sub match_glob ($$$) { #{{{
952 if (! defined $from){
957 if ($glob =~ m!^\./!) {
960 $glob="$from/$glob" if length $from;
963 # turn glob into safe regexp
964 $glob=quotemeta($glob);
968 return $page=~/^$glob$/i;
971 sub match_link ($$) { #{{{
975 my $links = $IkiWiki::links{$page} or return undef;
976 foreach my $p (@$links) {
977 return 1 if lc $p eq $link;
982 sub match_backlink ($$) { #{{{
983 match_link(pop, pop);
986 sub match_created_before ($$) { #{{{
990 if (exists $IkiWiki::pagectime{$testpage}) {
991 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
998 sub match_created_after ($$) { #{{{
1002 if (exists $IkiWiki::pagectime{$testpage}) {
1003 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1010 sub match_creation_day ($$) { #{{{
1011 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1014 sub match_creation_month ($$) { #{{{
1015 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1018 sub match_creation_year ($$) { #{{{
1019 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);