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 if (length $content) {
297 print OUT $content || error("failed writing to $newfile: $!", $cleanup);
300 close OUT || error("failed saving $newfile: $!", $cleanup);
301 rename($newfile, "$destdir/$file") ||
302 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
306 sub will_render ($$;$) { #{{{
311 # Important security check.
312 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
313 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
314 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
317 if (! $clear || $cleared{$page}) {
318 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
321 $renderedfiles{$page}=[$dest];
326 sub bestlink ($$) { #{{{
331 if ($link=~s/^\/+//) {
338 $l.="/" if length $l;
341 if (exists $links{$l}) {
344 elsif (exists $pagecase{lc $l}) {
345 return $pagecase{lc $l};
347 } while $cwd=~s!/?[^/]+$!!;
349 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
350 return "$config{userdir}/".lc($link);
353 #print STDERR "warning: page $page, broken link: $link\n";
357 sub isinlinableimage ($) { #{{{
360 $file=~/\.(png|gif|jpg|jpeg)$/i;
363 sub pagetitle ($;$) { #{{{
368 $page=~s/__(\d+)__/chr($1)/eg;
371 $page=~s/__(\d+)__/&#$1;/g;
378 sub titlepage ($) { #{{{
381 $title=~s/([^-[:alnum:]_:+\/.])/"__".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)
432 if (! $opts{forcesubpage}) {
433 $bestlink=bestlink($lpage, $link);
436 $bestlink="$lpage/".lc($link);
440 if (defined $opts{linktext}) {
441 $linktext=$opts{linktext};
444 $linktext=pagetitle(basename($link));
447 return "<span class=\"selflink\">$linktext</span>"
448 if length $bestlink && $page eq $bestlink;
450 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
451 $bestlink=htmlpage($bestlink);
453 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
454 return $linktext unless length $config{cgiurl};
455 return "<span><a href=\"".
456 cgiurl(do => "create", page => lc($link), from => $page).
457 "\">?</a>$linktext</span>"
460 $bestlink=abs2rel($bestlink, dirname($page));
462 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
463 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
466 if (defined $opts{anchor}) {
467 $bestlink.="#".$opts{anchor};
470 return "<a href=\"$bestlink\">$linktext</a>";
473 sub htmlize ($$$) { #{{{
478 if (exists $hooks{htmlize}{$type}) {
479 $content=$hooks{htmlize}{$type}{call}->(
485 error("htmlization of $type not supported");
488 run_hooks(sanitize => sub {
498 sub linkify ($$$) { #{{{
499 my $lpage=shift; # the page containing the links
500 my $page=shift; # the page the link will end up on (different for inline)
503 $content =~ s{(\\?)$config{wiki_link_regexp}}{
505 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), anchor => $4, linktext => pagetitle($2)))
506 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3), anchor => $4))
513 sub preprocess ($$$;$) { #{{{
514 my $page=shift; # the page the data comes from
515 my $destpage=shift; # the page the data will appear in (different for inline)
523 if (length $escape) {
524 return "[[$command $params]]";
526 elsif (exists $hooks{preprocess}{$command}) {
527 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
528 # Note: preserve order of params, some plugins may
529 # consider it significant.
531 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
548 push @params, $key, $val;
551 push @params, $val, '';
554 if ($preprocessing{$page}++ > 3) {
555 # Avoid loops of preprocessed pages preprocessing
556 # other pages that preprocess them, etc.
557 #translators: The first parameter is a
558 #translators: preprocessor directive name,
559 #translators: the second a page name, the
560 #translators: third a number.
561 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
562 $command, $page, $preprocessing{$page}).
565 my $ret=$hooks{preprocess}{$command}{call}->(
568 destpage => $destpage,
570 $preprocessing{$page}--;
574 return "[[$command $params]]";
578 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
582 sub filter ($$) { #{{{
586 run_hooks(filter => sub {
587 $content=shift->(page => $page, content => $content);
593 sub indexlink () { #{{{
594 return "<a href=\"$config{url}\">$config{wikiname}</a>";
597 sub lockwiki () { #{{{
598 # Take an exclusive lock on the wiki to prevent multiple concurrent
599 # run issues. The lock will be dropped on program exit.
600 if (! -d $config{wikistatedir}) {
601 mkdir($config{wikistatedir});
603 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
604 error ("cannot write to $config{wikistatedir}/lockfile: $!");
605 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
606 debug("wiki seems to be locked, waiting for lock");
607 my $wait=600; # arbitrary, but don't hang forever to
608 # prevent process pileup
610 return if flock(WIKILOCK, 2 | 4);
613 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
617 sub unlockwiki () { #{{{
621 sub commit_hook_enabled () { #{{{
622 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
623 error ("cannot write to $config{wikistatedir}/commitlock: $!");
624 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
632 sub disable_commit_hook () { #{{{
633 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
634 error ("cannot write to $config{wikistatedir}/commitlock: $!");
635 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
636 error("failed to get commit lock");
640 sub enable_commit_hook () { #{{{
644 sub loadindex () { #{{{
645 open (IN, "$config{wikistatedir}/index") || return;
647 $_=possibly_foolish_untaint($_);
652 foreach my $i (split(/ /, $_)) {
653 my ($item, $val)=split(/=/, $i, 2);
654 push @{$items{$item}}, decode_entities($val);
657 next unless exists $items{src}; # skip bad lines for now
659 my $page=pagename($items{src}[0]);
660 if (! $config{rebuild}) {
661 $pagesources{$page}=$items{src}[0];
662 $oldpagemtime{$page}=$items{mtime}[0];
663 $oldlinks{$page}=[@{$items{link}}];
664 $links{$page}=[@{$items{link}}];
665 $depends{$page}=$items{depends}[0] if exists $items{depends};
666 $renderedfiles{$page}=[@{$items{dest}}];
667 $oldrenderedfiles{$page}=[@{$items{dest}}];
668 $pagecase{lc $page}=$page;
670 $pagectime{$page}=$items{ctime}[0];
675 sub saveindex () { #{{{
676 run_hooks(savestate => sub { shift->() });
678 if (! -d $config{wikistatedir}) {
679 mkdir($config{wikistatedir});
681 my $newfile="$config{wikistatedir}/index.new";
682 my $cleanup = sub { unlink($newfile) };
683 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
684 foreach my $page (keys %oldpagemtime) {
685 next unless $oldpagemtime{$page};
686 my $line="mtime=$oldpagemtime{$page} ".
687 "ctime=$pagectime{$page} ".
688 "src=$pagesources{$page}";
689 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
691 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
692 if (exists $depends{$page}) {
693 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
695 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
697 close OUT || error("failed saving to $newfile: $!", $cleanup);
698 rename($newfile, "$config{wikistatedir}/index") ||
699 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
702 sub template_file ($) { #{{{
705 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
706 return "$dir/$template" if -e "$dir/$template";
711 sub template_params (@) { #{{{
712 my $filename=template_file(shift);
714 if (! defined $filename) {
719 require HTML::Template;
722 my $text_ref = shift;
723 $$text_ref=&Encode::decode_utf8($$text_ref);
725 filename => $filename,
726 loop_context_vars => 1,
727 die_on_bad_params => 0,
730 return wantarray ? @ret : {@ret};
733 sub template ($;@) { #{{{
734 HTML::Template->new(template_params(@_));
737 sub misctemplate ($$;@) { #{{{
741 my $template=template("misc.tmpl");
744 indexlink => indexlink(),
745 wikiname => $config{wikiname},
746 pagebody => $pagebody,
747 baseurl => baseurl(),
750 run_hooks(pagetemplate => sub {
751 shift->(page => "", destpage => "", template => $template);
753 return $template->output;
759 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
760 error "hook requires type, call, and id parameters";
763 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
765 $hooks{$param{type}}{$param{id}}=\%param;
768 sub run_hooks ($$) { # {{{
769 # Calls the given sub for each hook of the given type,
770 # passing it the hook function to call.
774 if (exists $hooks{$type}) {
776 foreach my $id (keys %{$hooks{$type}}) {
777 if ($hooks{$type}{$id}{last}) {
781 $sub->($hooks{$type}{$id}{call});
783 foreach my $id (@deferred) {
784 $sub->($hooks{$type}{$id}{call});
789 sub globlist_to_pagespec ($) { #{{{
790 my @globlist=split(' ', shift);
793 foreach my $glob (@globlist) {
794 if ($glob=~/^!(.*)/) {
802 my $spec=join(" or ", @spec);
804 my $skip=join(" and ", @skip);
806 $spec="$skip and ($spec)";
815 sub is_globlist ($) { #{{{
817 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
820 sub safequote ($) { #{{{
826 sub add_depends ($$) { #{{{
830 if (! exists $depends{$page}) {
831 $depends{$page}=$pagespec;
834 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
838 sub file_pruned ($$) { #{{{
840 my $file=File::Spec->canonpath(shift);
841 my $base=File::Spec->canonpath(shift);
842 $file=~s#^\Q$base\E/*##;
844 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
849 # Only use gettext in the rare cases it's needed.
850 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
851 if (! $gettext_obj) {
853 use Locale::gettext q{textdomain};
854 Locale::gettext->domain('ikiwiki')
862 return $gettext_obj->get(shift);
869 sub pagespec_merge ($$) { #{{{
873 return $a if $a eq $b;
875 # Support for old-style GlobLists.
876 if (is_globlist($a)) {
877 $a=globlist_to_pagespec($a);
879 if (is_globlist($b)) {
880 $b=globlist_to_pagespec($b);
883 return "($a) or ($b)";
886 sub pagespec_translate ($) { #{{{
887 # This assumes that $page is in scope in the function
888 # that evalulates the translated pagespec code.
891 # Support for old-style GlobLists.
892 if (is_globlist($spec)) {
893 $spec=globlist_to_pagespec($spec);
896 # Convert spec to perl code.
898 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
900 if (lc $word eq "and") {
903 elsif (lc $word eq "or") {
906 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
909 elsif ($word =~ /^(\w+)\((.*)\)$/) {
910 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
911 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
918 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
925 sub pagespec_match ($$;$) { #{{{
930 return eval pagespec_translate($spec);
933 package IkiWiki::PageSpec;
935 sub match_glob ($$$) { #{{{
939 if (! defined $from){
944 if ($glob =~ m!^\./!) {
947 $glob="$from/$glob" if length $from;
950 # turn glob into safe regexp
951 $glob=quotemeta($glob);
955 return $page=~/^$glob$/i;
958 sub match_link ($$) { #{{{
962 my $links = $IkiWiki::links{$page} or return undef;
963 foreach my $p (@$links) {
964 return 1 if lc $p eq $link;
969 sub match_backlink ($$) { #{{{
970 match_link(pop, pop);
973 sub match_created_before ($$) { #{{{
977 if (exists $IkiWiki::pagectime{$testpage}) {
978 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
985 sub match_created_after ($$) { #{{{
989 if (exists $IkiWiki::pagectime{$testpage}) {
990 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
997 sub match_creation_day ($$) { #{{{
998 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1001 sub match_creation_month ($$) { #{{{
1002 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1005 sub match_creation_year ($$) { #{{{
1006 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);