8 use open qw{:utf8 :std};
10 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
11 %renderedfiles %oldrenderedfiles %pagesources %depends %hooks
12 %forcerebuild $gettext_obj};
14 use Exporter q{import};
15 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
16 bestlink htmllink readfile writefile pagetype srcfile pagename
17 displaytime will_render gettext
18 %config %links %renderedfiles %pagesources);
19 our $VERSION = 1.02; # plugin interface version, next is ikiwiki version
20 our $version="1.45";my $installdir="/usr";
24 memoize("pagespec_translate");
25 memoize("file_pruned");
27 sub defaultconfig () { #{{{
28 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
29 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
30 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
31 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
32 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
33 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
37 default_pageext => "mdwn",
57 gitorigin_branch => "origin",
58 gitmaster_branch => "master",
62 templatedir => "$installdir/share/ikiwiki/templates",
63 underlaydir => "$installdir/share/ikiwiki/basewiki",
67 plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
68 lockedit conditional}],
76 sub checkconfig () { #{{{
77 # locale stuff; avoid LC_ALL since it overrides everything
78 if (defined $ENV{LC_ALL}) {
79 $ENV{LANG} = $ENV{LC_ALL};
82 if (defined $config{locale}) {
85 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
86 $ENV{LANG}=$config{locale};
91 if ($config{w3mmode}) {
92 eval q{use Cwd q{abs_path}};
94 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
95 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
96 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
97 unless $config{cgiurl} =~ m!file:///!;
98 $config{url}="file://".$config{destdir};
101 if ($config{cgi} && ! length $config{url}) {
102 error(gettext("Must specify url to wiki with --url when using --cgi"));
105 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
106 unless exists $config{wikistatedir};
109 eval qq{require IkiWiki::Rcs::$config{rcs}};
111 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
115 require IkiWiki::Rcs::Stub;
118 run_hooks(checkconfig => sub { shift->() });
121 sub loadplugins () { #{{{
122 loadplugin($_) foreach @{$config{plugin}};
124 run_hooks(getopt => sub { shift->() });
125 if (grep /^-/, @ARGV) {
126 print STDERR "Unknown option: $_\n"
127 foreach grep /^-/, @ARGV;
132 sub loadplugin ($) { #{{{
135 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
137 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
140 error("Failed to load plugin $mod: $@");
144 sub error ($;$) { #{{{
148 print "Content-type: text/html\n\n";
149 print misctemplate(gettext("Error"),
150 "<p>".gettext("Error").": $message</p>");
152 log_message(debug => $message) if $config{syslog};
153 if (defined $cleaner) {
160 return unless $config{verbose};
161 log_message(debug => @_);
165 sub log_message ($$) { #{{{
168 if ($config{syslog}) {
171 Sys::Syslog::setlogsock('unix');
172 Sys::Syslog::openlog('ikiwiki', '', 'user');
176 Sys::Syslog::syslog($type, "%s", join(" ", @_));
179 elsif (! $config{cgi}) {
187 sub possibly_foolish_untaint ($) { #{{{
189 my ($untainted)=$tainted=~/(.*)/;
193 sub basename ($) { #{{{
200 sub dirname ($) { #{{{
207 sub pagetype ($) { #{{{
210 if ($page =~ /\.([^.]+)$/) {
211 return $1 if exists $hooks{htmlize}{$1};
216 sub pagename ($) { #{{{
219 my $type=pagetype($file);
221 $page=~s/\Q.$type\E*$// if defined $type;
225 sub htmlpage ($) { #{{{
228 return $page.".html";
231 sub srcfile ($) { #{{{
234 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
235 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
236 error("internal error: $file cannot be found");
239 sub readfile ($;$$) { #{{{
245 error("cannot read a symlink ($file)");
249 open (IN, $file) || error("failed to read $file: $!");
250 binmode(IN) if ($binary);
251 return \*IN if $wantfd;
253 close IN || error("failed to read $file: $!");
257 sub writefile ($$$;$$) { #{{{
258 my $file=shift; # can include subdirs
259 my $destdir=shift; # directory to put file in
265 while (length $test) {
266 if (-l "$destdir/$test") {
267 error("cannot write to a symlink ($test)");
269 $test=dirname($test);
271 my $newfile="$destdir/$file.ikiwiki-new";
273 error("cannot write to a symlink ($newfile)");
276 my $dir=dirname($newfile);
279 foreach my $s (split(m!/+!, $dir)) {
282 mkdir($d) || error("failed to create directory $d: $!");
287 my $cleanup = sub { unlink($newfile) };
288 open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
289 binmode(OUT) if ($binary);
291 $writer->(\*OUT, $cleanup);
294 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
296 close OUT || error("failed saving $newfile: $!", $cleanup);
297 rename($newfile, "$destdir/$file") ||
298 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
302 sub will_render ($$;$) { #{{{
307 # Important security check.
308 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
309 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
310 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
313 if (! $clear || $cleared{$page}) {
314 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
317 $renderedfiles{$page}=[$dest];
322 sub bestlink ($$) { #{{{
327 if ($link=~s/^\/+//) {
334 $l.="/" if length $l;
337 if (exists $links{$l}) {
340 elsif (exists $pagecase{lc $l}) {
341 return $pagecase{lc $l};
343 } while $cwd=~s!/?[^/]+$!!;
345 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
346 return "$config{userdir}/".lc($link);
349 #print STDERR "warning: page $page, broken link: $link\n";
353 sub isinlinableimage ($) { #{{{
356 $file=~/\.(png|gif|jpg|jpeg)$/i;
359 sub pagetitle ($;$) { #{{{
364 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
367 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
373 sub titlepage ($) { #{{{
375 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
379 sub linkpage ($) { #{{{
381 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
385 sub cgiurl (@) { #{{{
388 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
391 sub baseurl (;$) { #{{{
394 return "$config{url}/" if ! defined $page;
397 $page=~s/[^\/]+\//..\//g;
401 sub abs2rel ($$) { #{{{
402 # Work around very innefficient behavior in File::Spec if abs2rel
403 # is passed two relative paths. It's much faster if paths are
404 # absolute! (Debian bug #376658; fixed in debian unstable now)
409 my $ret=File::Spec->abs2rel($path, $base);
410 $ret=~s/^// if defined $ret;
414 sub displaytime ($) { #{{{
419 # strftime doesn't know about encodings, so make sure
420 # its output is properly treated as utf8
421 return decode_utf8(POSIX::strftime(
422 $config{timeformat}, localtime($time)));
425 sub htmllink ($$$;@) { #{{{
426 my $lpage=shift; # the page doing the linking
427 my $page=shift; # the page that will contain the link (different for inline)
431 print STDERR "bestlink $lpage $link\n" if $lpage eq "roadmap" && $link =~/rcs/;
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=\"".
458 cgiurl(do => "create", page => lc($link), from => $page).
459 "\">?</a>$linktext</span>"
462 $bestlink=abs2rel($bestlink, dirname($page));
464 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
465 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
468 if (defined $opts{anchor}) {
469 $bestlink.="#".$opts{anchor};
472 return "<a href=\"$bestlink\">$linktext</a>";
475 sub htmlize ($$$) { #{{{
480 if (exists $hooks{htmlize}{$type}) {
481 $content=$hooks{htmlize}{$type}{call}->(
487 error("htmlization of $type not supported");
490 run_hooks(sanitize => sub {
500 sub linkify ($$$) { #{{{
501 my $lpage=shift; # the page containing the links
502 my $page=shift; # the page the link will end up on (different for inline)
505 $content =~ s{(\\?)$config{wiki_link_regexp}}{
507 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4, linktext => pagetitle($2)))
508 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4))
515 our $preprocess_preview=0;
516 sub preprocess ($$$;$$) { #{{{
517 my $page=shift; # the page the data comes from
518 my $destpage=shift; # the page the data will appear in (different for inline)
523 # Using local because it needs to be set within any nested calls
525 local $preprocess_preview=$preview if defined $preview;
531 if (length $escape) {
532 return "[[$command $params]]";
534 elsif (exists $hooks{preprocess}{$command}) {
535 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
536 # Note: preserve order of params, some plugins may
537 # consider it significant.
539 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
556 push @params, $key, $val;
559 push @params, $val, '';
562 if ($preprocessing{$page}++ > 3) {
563 # Avoid loops of preprocessed pages preprocessing
564 # other pages that preprocess them, etc.
565 #translators: The first parameter is a
566 #translators: preprocessor directive name,
567 #translators: the second a page name, the
568 #translators: third a number.
569 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
570 $command, $page, $preprocessing{$page}).
573 my $ret=$hooks{preprocess}{$command}{call}->(
576 destpage => $destpage,
577 preview => $preprocess_preview,
579 $preprocessing{$page}--;
583 return "[[$command $params]]";
587 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
591 sub filter ($$) { #{{{
595 run_hooks(filter => sub {
596 $content=shift->(page => $page, content => $content);
602 sub indexlink () { #{{{
603 return "<a href=\"$config{url}\">$config{wikiname}</a>";
606 sub lockwiki () { #{{{
607 # Take an exclusive lock on the wiki to prevent multiple concurrent
608 # run issues. The lock will be dropped on program exit.
609 if (! -d $config{wikistatedir}) {
610 mkdir($config{wikistatedir});
612 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
613 error ("cannot write to $config{wikistatedir}/lockfile: $!");
614 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
615 debug("wiki seems to be locked, waiting for lock");
616 my $wait=600; # arbitrary, but don't hang forever to
617 # prevent process pileup
619 return if flock(WIKILOCK, 2 | 4);
622 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
626 sub unlockwiki () { #{{{
630 sub commit_hook_enabled () { #{{{
631 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
632 error ("cannot write to $config{wikistatedir}/commitlock: $!");
633 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
641 sub disable_commit_hook () { #{{{
642 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
643 error ("cannot write to $config{wikistatedir}/commitlock: $!");
644 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
645 error("failed to get commit lock");
649 sub enable_commit_hook () { #{{{
653 sub loadindex () { #{{{
654 open (IN, "$config{wikistatedir}/index") || return;
656 $_=possibly_foolish_untaint($_);
661 foreach my $i (split(/ /, $_)) {
662 my ($item, $val)=split(/=/, $i, 2);
663 push @{$items{$item}}, decode_entities($val);
666 next unless exists $items{src}; # skip bad lines for now
668 my $page=pagename($items{src}[0]);
669 if (! $config{rebuild}) {
670 $pagesources{$page}=$items{src}[0];
671 $oldpagemtime{$page}=$items{mtime}[0];
672 $oldlinks{$page}=[@{$items{link}}];
673 $links{$page}=[@{$items{link}}];
674 $depends{$page}=$items{depends}[0] if exists $items{depends};
675 $renderedfiles{$page}=[@{$items{dest}}];
676 $oldrenderedfiles{$page}=[@{$items{dest}}];
677 $pagecase{lc $page}=$page;
679 $pagectime{$page}=$items{ctime}[0];
684 sub saveindex () { #{{{
685 run_hooks(savestate => sub { shift->() });
687 if (! -d $config{wikistatedir}) {
688 mkdir($config{wikistatedir});
690 my $newfile="$config{wikistatedir}/index.new";
691 my $cleanup = sub { unlink($newfile) };
692 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
693 foreach my $page (keys %oldpagemtime) {
694 next unless $oldpagemtime{$page};
695 my $line="mtime=$oldpagemtime{$page} ".
696 "ctime=$pagectime{$page} ".
697 "src=$pagesources{$page}";
698 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
700 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
701 if (exists $depends{$page}) {
702 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
704 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
706 close OUT || error("failed saving to $newfile: $!", $cleanup);
707 rename($newfile, "$config{wikistatedir}/index") ||
708 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
711 sub template_file ($) { #{{{
714 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
715 return "$dir/$template" if -e "$dir/$template";
720 sub template_params (@) { #{{{
721 my $filename=template_file(shift);
723 if (! defined $filename) {
728 require HTML::Template;
731 my $text_ref = shift;
732 $$text_ref=&Encode::decode_utf8($$text_ref);
734 filename => $filename,
735 loop_context_vars => 1,
736 die_on_bad_params => 0,
739 return wantarray ? @ret : {@ret};
742 sub template ($;@) { #{{{
743 HTML::Template->new(template_params(@_));
746 sub misctemplate ($$;@) { #{{{
750 my $template=template("misc.tmpl");
753 indexlink => indexlink(),
754 wikiname => $config{wikiname},
755 pagebody => $pagebody,
756 baseurl => baseurl(),
759 run_hooks(pagetemplate => sub {
760 shift->(page => "", destpage => "", template => $template);
762 return $template->output;
768 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
769 error "hook requires type, call, and id parameters";
772 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
774 $hooks{$param{type}}{$param{id}}=\%param;
777 sub run_hooks ($$) { # {{{
778 # Calls the given sub for each hook of the given type,
779 # passing it the hook function to call.
783 if (exists $hooks{$type}) {
785 foreach my $id (keys %{$hooks{$type}}) {
786 if ($hooks{$type}{$id}{last}) {
790 $sub->($hooks{$type}{$id}{call});
792 foreach my $id (@deferred) {
793 $sub->($hooks{$type}{$id}{call});
798 sub globlist_to_pagespec ($) { #{{{
799 my @globlist=split(' ', shift);
802 foreach my $glob (@globlist) {
803 if ($glob=~/^!(.*)/) {
811 my $spec=join(" or ", @spec);
813 my $skip=join(" and ", @skip);
815 $spec="$skip and ($spec)";
824 sub is_globlist ($) { #{{{
826 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
829 sub safequote ($) { #{{{
835 sub add_depends ($$) { #{{{
839 if (! exists $depends{$page}) {
840 $depends{$page}=$pagespec;
843 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
847 sub file_pruned ($$) { #{{{
849 my $file=File::Spec->canonpath(shift);
850 my $base=File::Spec->canonpath(shift);
851 $file=~s#^\Q$base\E/*##;
853 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
858 # Only use gettext in the rare cases it's needed.
859 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
860 if (! $gettext_obj) {
862 use Locale::gettext q{textdomain};
863 Locale::gettext->domain('ikiwiki')
871 return $gettext_obj->get(shift);
878 sub pagespec_merge ($$) { #{{{
882 return $a if $a eq $b;
884 # Support for old-style GlobLists.
885 if (is_globlist($a)) {
886 $a=globlist_to_pagespec($a);
888 if (is_globlist($b)) {
889 $b=globlist_to_pagespec($b);
892 return "($a) or ($b)";
895 sub pagespec_translate ($) { #{{{
896 # This assumes that $page is in scope in the function
897 # that evalulates the translated pagespec code.
900 # Support for old-style GlobLists.
901 if (is_globlist($spec)) {
902 $spec=globlist_to_pagespec($spec);
905 # Convert spec to perl code.
907 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
909 if (lc $word eq "and") {
912 elsif (lc $word eq "or") {
915 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
918 elsif ($word =~ /^(\w+)\((.*)\)$/) {
919 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
920 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
927 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
934 sub pagespec_match ($$;$) { #{{{
939 return eval pagespec_translate($spec);
942 package IkiWiki::PageSpec;
944 sub match_glob ($$$) { #{{{
948 if (! defined $from){
953 if ($glob =~ m!^\./!) {
956 $glob="$from/$glob" if length $from;
959 # turn glob into safe regexp
960 $glob=quotemeta($glob);
964 return $page=~/^$glob$/i;
967 sub match_link ($$) { #{{{
971 my $links = $IkiWiki::links{$page} or return undef;
972 foreach my $p (@$links) {
973 return 1 if lc $p eq $link;
978 sub match_backlink ($$) { #{{{
979 match_link(pop, pop);
982 sub match_created_before ($$) { #{{{
986 if (exists $IkiWiki::pagectime{$testpage}) {
987 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
994 sub match_created_after ($$) { #{{{
998 if (exists $IkiWiki::pagectime{$testpage}) {
999 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1006 sub match_creation_day ($$) { #{{{
1007 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1010 sub match_creation_month ($$) { #{{{
1011 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1014 sub match_creation_year ($$) { #{{{
1015 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);