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='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
21 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
26 memoize("pagespec_translate");
27 memoize("file_pruned");
29 sub defaultconfig () { #{{{
30 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
31 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
32 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
33 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
34 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
35 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
39 default_pageext => "mdwn",
59 gitorigin_branch => "origin",
60 gitmaster_branch => "master",
64 templatedir => "$installdir/share/ikiwiki/templates",
65 underlaydir => "$installdir/share/ikiwiki/basewiki",
69 plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
70 lockedit conditional}],
78 sub checkconfig () { #{{{
79 # locale stuff; avoid LC_ALL since it overrides everything
80 if (defined $ENV{LC_ALL}) {
81 $ENV{LANG} = $ENV{LC_ALL};
84 if (defined $config{locale}) {
87 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
88 $ENV{LANG}=$config{locale};
93 if ($config{w3mmode}) {
94 eval q{use Cwd q{abs_path}};
96 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
97 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
98 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
99 unless $config{cgiurl} =~ m!file:///!;
100 $config{url}="file://".$config{destdir};
103 if ($config{cgi} && ! length $config{url}) {
104 error(gettext("Must specify url to wiki with --url when using --cgi"));
107 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
108 unless exists $config{wikistatedir};
111 eval qq{require IkiWiki::Rcs::$config{rcs}};
113 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
117 require IkiWiki::Rcs::Stub;
120 run_hooks(checkconfig => sub { shift->() });
123 sub loadplugins () { #{{{
124 loadplugin($_) foreach @{$config{plugin}};
126 run_hooks(getopt => sub { shift->() });
127 if (grep /^-/, @ARGV) {
128 print STDERR "Unknown option: $_\n"
129 foreach grep /^-/, @ARGV;
134 sub loadplugin ($) { #{{{
137 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
139 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
142 error("Failed to load plugin $mod: $@");
146 sub error ($;$) { #{{{
150 print "Content-type: text/html\n\n";
151 print misctemplate(gettext("Error"),
152 "<p>".gettext("Error").": $message</p>");
154 log_message(debug => $message) if $config{syslog};
155 if (defined $cleaner) {
162 return unless $config{verbose};
163 log_message(debug => @_);
167 sub log_message ($$) { #{{{
170 if ($config{syslog}) {
173 Sys::Syslog::setlogsock('unix');
174 Sys::Syslog::openlog('ikiwiki', '', 'user');
178 Sys::Syslog::syslog($type, "%s", join(" ", @_));
181 elsif (! $config{cgi}) {
189 sub possibly_foolish_untaint ($) { #{{{
191 my ($untainted)=$tainted=~/(.*)/;
195 sub basename ($) { #{{{
202 sub dirname ($) { #{{{
209 sub pagetype ($) { #{{{
212 if ($page =~ /\.([^.]+)$/) {
213 return $1 if exists $hooks{htmlize}{$1};
218 sub pagename ($) { #{{{
221 my $type=pagetype($file);
223 $page=~s/\Q.$type\E*$// if defined $type;
227 sub htmlpage ($) { #{{{
230 return $page.".html";
233 sub srcfile ($) { #{{{
236 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
237 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
238 error("internal error: $file cannot be found");
241 sub readfile ($;$$) { #{{{
247 error("cannot read a symlink ($file)");
251 open (IN, $file) || error("failed to read $file: $!");
252 binmode(IN) if ($binary);
253 return \*IN if $wantfd;
255 close IN || error("failed to read $file: $!");
259 sub writefile ($$$;$$) { #{{{
260 my $file=shift; # can include subdirs
261 my $destdir=shift; # directory to put file in
267 while (length $test) {
268 if (-l "$destdir/$test") {
269 error("cannot write to a symlink ($test)");
271 $test=dirname($test);
273 my $newfile="$destdir/$file.ikiwiki-new";
275 error("cannot write to a symlink ($newfile)");
278 my $dir=dirname($newfile);
281 foreach my $s (split(m!/+!, $dir)) {
284 mkdir($d) || error("failed to create directory $d: $!");
289 my $cleanup = sub { unlink($newfile) };
290 open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
291 binmode(OUT) if ($binary);
293 $writer->(\*OUT, $cleanup);
296 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
298 close OUT || error("failed saving $newfile: $!", $cleanup);
299 rename($newfile, "$destdir/$file") ||
300 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
304 sub will_render ($$;$) { #{{{
309 # Important security check.
310 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
311 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
312 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
315 if (! $clear || $cleared{$page}) {
316 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
319 $renderedfiles{$page}=[$dest];
324 sub bestlink ($$) { #{{{
329 if ($link=~s/^\/+//) {
336 $l.="/" if length $l;
339 if (exists $links{$l}) {
342 elsif (exists $pagecase{lc $l}) {
343 return $pagecase{lc $l};
345 } while $cwd=~s!/?[^/]+$!!;
347 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
348 return "$config{userdir}/".lc($link);
351 #print STDERR "warning: page $page, broken link: $link\n";
355 sub isinlinableimage ($) { #{{{
358 $file=~/\.(png|gif|jpg|jpeg)$/i;
361 sub pagetitle ($;$) { #{{{
366 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
369 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
375 sub titlepage ($) { #{{{
377 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
381 sub cgiurl (@) { #{{{
384 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
387 sub baseurl (;$) { #{{{
390 return "$config{url}/" if ! defined $page;
393 $page=~s/[^\/]+\//..\//g;
397 sub abs2rel ($$) { #{{{
398 # Work around very innefficient behavior in File::Spec if abs2rel
399 # is passed two relative paths. It's much faster if paths are
400 # absolute! (Debian bug #376658; fixed in debian unstable now)
405 my $ret=File::Spec->abs2rel($path, $base);
406 $ret=~s/^// if defined $ret;
410 sub displaytime ($) { #{{{
415 # strftime doesn't know about encodings, so make sure
416 # its output is properly treated as utf8
417 return decode_utf8(POSIX::strftime(
418 $config{timeformat}, localtime($time)));
421 sub htmllink ($$$;@) { #{{{
422 my $lpage=shift; # the page doing the linking
423 my $page=shift; # the page that will contain the link (different for inline)
428 if (! $opts{forcesubpage}) {
429 $bestlink=bestlink($lpage, $link);
432 $bestlink="$lpage/".lc($link);
436 if (defined $opts{linktext}) {
437 $linktext=$opts{linktext};
440 $linktext=pagetitle(basename($link));
443 return "<span class=\"selflink\">$linktext</span>"
444 if length $bestlink && $page eq $bestlink;
446 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
447 $bestlink=htmlpage($bestlink);
449 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
450 return $linktext unless length $config{cgiurl};
451 return "<span><a href=\"".
452 cgiurl(do => "create", page => lc($link), from => $page).
453 "\">?</a>$linktext</span>"
456 $bestlink=abs2rel($bestlink, dirname($page));
458 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
459 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
462 if (defined $opts{anchor}) {
463 $bestlink.="#".$opts{anchor};
466 return "<a href=\"$bestlink\">$linktext</a>";
469 sub htmlize ($$$) { #{{{
474 if (exists $hooks{htmlize}{$type}) {
475 $content=$hooks{htmlize}{$type}{call}->(
481 error("htmlization of $type not supported");
484 run_hooks(sanitize => sub {
494 sub linkify ($$$) { #{{{
495 my $lpage=shift; # the page containing the links
496 my $page=shift; # the page the link will end up on (different for inline)
499 $content =~ s{(\\?)$config{wiki_link_regexp}}{
501 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), anchor => $4, linktext => pagetitle($2)))
502 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3), anchor => $4))
509 sub preprocess ($$$;$) { #{{{
510 my $page=shift; # the page the data comes from
511 my $destpage=shift; # the page the data will appear in (different for inline)
519 if (length $escape) {
520 return "[[$command $params]]";
522 elsif (exists $hooks{preprocess}{$command}) {
523 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
524 # Note: preserve order of params, some plugins may
525 # consider it significant.
527 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
544 push @params, $key, $val;
547 push @params, $val, '';
550 if ($preprocessing{$page}++ > 3) {
551 # Avoid loops of preprocessed pages preprocessing
552 # other pages that preprocess them, etc.
553 #translators: The first parameter is a
554 #translators: preprocessor directive name,
555 #translators: the second a page name, the
556 #translators: third a number.
557 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
558 $command, $page, $preprocessing{$page}).
561 my $ret=$hooks{preprocess}{$command}{call}->(
564 destpage => $destpage,
566 $preprocessing{$page}--;
570 return "[[$command $params]]";
574 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
578 sub filter ($$) { #{{{
582 run_hooks(filter => sub {
583 $content=shift->(page => $page, content => $content);
589 sub indexlink () { #{{{
590 return "<a href=\"$config{url}\">$config{wikiname}</a>";
593 sub lockwiki () { #{{{
594 # Take an exclusive lock on the wiki to prevent multiple concurrent
595 # run issues. The lock will be dropped on program exit.
596 if (! -d $config{wikistatedir}) {
597 mkdir($config{wikistatedir});
599 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
600 error ("cannot write to $config{wikistatedir}/lockfile: $!");
601 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
602 debug("wiki seems to be locked, waiting for lock");
603 my $wait=600; # arbitrary, but don't hang forever to
604 # prevent process pileup
606 return if flock(WIKILOCK, 2 | 4);
609 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
613 sub unlockwiki () { #{{{
617 sub commit_hook_enabled () { #{{{
618 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
619 error ("cannot write to $config{wikistatedir}/commitlock: $!");
620 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
628 sub disable_commit_hook () { #{{{
629 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
630 error ("cannot write to $config{wikistatedir}/commitlock: $!");
631 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
632 error("failed to get commit lock");
636 sub enable_commit_hook () { #{{{
640 sub loadindex () { #{{{
641 open (IN, "$config{wikistatedir}/index") || return;
643 $_=possibly_foolish_untaint($_);
648 foreach my $i (split(/ /, $_)) {
649 my ($item, $val)=split(/=/, $i, 2);
650 push @{$items{$item}}, decode_entities($val);
653 next unless exists $items{src}; # skip bad lines for now
655 my $page=pagename($items{src}[0]);
656 if (! $config{rebuild}) {
657 $pagesources{$page}=$items{src}[0];
658 $oldpagemtime{$page}=$items{mtime}[0];
659 $oldlinks{$page}=[@{$items{link}}];
660 $links{$page}=[@{$items{link}}];
661 $depends{$page}=$items{depends}[0] if exists $items{depends};
662 $renderedfiles{$page}=[@{$items{dest}}];
663 $oldrenderedfiles{$page}=[@{$items{dest}}];
664 $pagecase{lc $page}=$page;
666 $pagectime{$page}=$items{ctime}[0];
671 sub saveindex () { #{{{
672 run_hooks(savestate => sub { shift->() });
674 if (! -d $config{wikistatedir}) {
675 mkdir($config{wikistatedir});
677 my $newfile="$config{wikistatedir}/index.new";
678 my $cleanup = sub { unlink($newfile) };
679 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
680 foreach my $page (keys %oldpagemtime) {
681 next unless $oldpagemtime{$page};
682 my $line="mtime=$oldpagemtime{$page} ".
683 "ctime=$pagectime{$page} ".
684 "src=$pagesources{$page}";
685 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
687 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
688 if (exists $depends{$page}) {
689 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
691 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
693 close OUT || error("failed saving to $newfile: $!", $cleanup);
694 rename($newfile, "$config{wikistatedir}/index") ||
695 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
698 sub template_file ($) { #{{{
701 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
702 return "$dir/$template" if -e "$dir/$template";
707 sub template_params (@) { #{{{
708 my $filename=template_file(shift);
710 if (! defined $filename) {
715 require HTML::Template;
718 my $text_ref = shift;
719 $$text_ref=&Encode::decode_utf8($$text_ref);
721 filename => $filename,
722 loop_context_vars => 1,
723 die_on_bad_params => 0,
726 return wantarray ? @ret : {@ret};
729 sub template ($;@) { #{{{
730 HTML::Template->new(template_params(@_));
733 sub misctemplate ($$;@) { #{{{
737 my $template=template("misc.tmpl");
740 indexlink => indexlink(),
741 wikiname => $config{wikiname},
742 pagebody => $pagebody,
743 baseurl => baseurl(),
746 run_hooks(pagetemplate => sub {
747 shift->(page => "", destpage => "", template => $template);
749 return $template->output;
755 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
756 error "hook requires type, call, and id parameters";
759 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
761 $hooks{$param{type}}{$param{id}}=\%param;
764 sub run_hooks ($$) { # {{{
765 # Calls the given sub for each hook of the given type,
766 # passing it the hook function to call.
770 if (exists $hooks{$type}) {
772 foreach my $id (keys %{$hooks{$type}}) {
773 if ($hooks{$type}{$id}{last}) {
777 $sub->($hooks{$type}{$id}{call});
779 foreach my $id (@deferred) {
780 $sub->($hooks{$type}{$id}{call});
785 sub globlist_to_pagespec ($) { #{{{
786 my @globlist=split(' ', shift);
789 foreach my $glob (@globlist) {
790 if ($glob=~/^!(.*)/) {
798 my $spec=join(" or ", @spec);
800 my $skip=join(" and ", @skip);
802 $spec="$skip and ($spec)";
811 sub is_globlist ($) { #{{{
813 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
816 sub safequote ($) { #{{{
822 sub add_depends ($$) { #{{{
826 if (! exists $depends{$page}) {
827 $depends{$page}=$pagespec;
830 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
834 sub file_pruned ($$) { #{{{
836 my $file=File::Spec->canonpath(shift);
837 my $base=File::Spec->canonpath(shift);
838 $file=~s#^\Q$base\E/*##;
840 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
845 # Only use gettext in the rare cases it's needed.
846 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
847 if (! $gettext_obj) {
849 use Locale::gettext q{textdomain};
850 Locale::gettext->domain('ikiwiki')
858 return $gettext_obj->get(shift);
865 sub pagespec_merge ($$) { #{{{
869 return $a if $a eq $b;
871 # Support for old-style GlobLists.
872 if (is_globlist($a)) {
873 $a=globlist_to_pagespec($a);
875 if (is_globlist($b)) {
876 $b=globlist_to_pagespec($b);
879 return "($a) or ($b)";
882 sub pagespec_translate ($) { #{{{
883 # This assumes that $page is in scope in the function
884 # that evalulates the translated pagespec code.
887 # Support for old-style GlobLists.
888 if (is_globlist($spec)) {
889 $spec=globlist_to_pagespec($spec);
892 # Convert spec to perl code.
894 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
896 if (lc $word eq "and") {
899 elsif (lc $word eq "or") {
902 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
905 elsif ($word =~ /^(\w+)\((.*)\)$/) {
906 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
907 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
914 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
921 sub pagespec_match ($$;$) { #{{{
926 return eval pagespec_translate($spec);
929 package IkiWiki::PageSpec;
931 sub match_glob ($$$) { #{{{
935 if (! defined $from){
940 if ($glob =~ m!^\./!) {
943 $glob="$from/$glob" if length $from;
946 # turn glob into safe regexp
947 $glob=quotemeta($glob);
951 return $page=~/^$glob$/i;
954 sub match_link ($$) { #{{{
958 my $links = $IkiWiki::links{$page} or return undef;
959 foreach my $p (@$links) {
960 return 1 if lc $p eq $link;
965 sub match_backlink ($$) { #{{{
966 match_link(pop, pop);
969 sub match_created_before ($$) { #{{{
973 if (exists $IkiWiki::pagectime{$testpage}) {
974 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
981 sub match_created_after ($$) { #{{{
985 if (exists $IkiWiki::pagectime{$testpage}) {
986 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
993 sub match_creation_day ($$) { #{{{
994 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
997 sub match_creation_month ($$) { #{{{
998 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1001 sub match_creation_year ($$) { #{{{
1002 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);