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 cgiurl (@) { #{{{
382 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
385 sub baseurl (;$) { #{{{
388 return "$config{url}/" if ! defined $page;
391 $page=~s/[^\/]+\//..\//g;
395 sub abs2rel ($$) { #{{{
396 # Work around very innefficient behavior in File::Spec if abs2rel
397 # is passed two relative paths. It's much faster if paths are
398 # absolute! (Debian bug #376658; fixed in debian unstable now)
403 my $ret=File::Spec->abs2rel($path, $base);
404 $ret=~s/^// if defined $ret;
408 sub displaytime ($) { #{{{
413 # strftime doesn't know about encodings, so make sure
414 # its output is properly treated as utf8
415 return decode_utf8(POSIX::strftime(
416 $config{timeformat}, localtime($time)));
419 sub htmllink ($$$;@) { #{{{
420 my $lpage=shift; # the page doing the linking
421 my $page=shift; # the page that will contain the link (different for inline)
426 if (! $opts{forcesubpage}) {
427 $bestlink=bestlink($lpage, $link);
430 $bestlink="$lpage/".lc($link);
434 if (defined $opts{linktext}) {
435 $linktext=$opts{linktext};
438 $linktext=pagetitle(basename($link));
441 return "<span class=\"selflink\">$linktext</span>"
442 if length $bestlink && $page eq $bestlink;
444 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
445 $bestlink=htmlpage($bestlink);
447 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
448 return $linktext unless length $config{cgiurl};
449 return "<span><a href=\"".
450 cgiurl(do => "create", page => lc($link), from => $page).
451 "\">?</a>$linktext</span>"
454 $bestlink=abs2rel($bestlink, dirname($page));
456 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
457 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
460 if (defined $opts{anchor}) {
461 $bestlink.="#".$opts{anchor};
464 return "<a href=\"$bestlink\">$linktext</a>";
467 sub htmlize ($$$) { #{{{
472 if (exists $hooks{htmlize}{$type}) {
473 $content=$hooks{htmlize}{$type}{call}->(
479 error("htmlization of $type not supported");
482 run_hooks(sanitize => sub {
492 sub linkify ($$$) { #{{{
493 my $lpage=shift; # the page containing the links
494 my $page=shift; # the page the link will end up on (different for inline)
497 $content =~ s{(\\?)$config{wiki_link_regexp}}{
499 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), anchor => $4, linktext => pagetitle($2)))
500 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3), anchor => $4))
507 our $preprocess_preview=0;
508 sub preprocess ($$$;$$) { #{{{
509 my $page=shift; # the page the data comes from
510 my $destpage=shift; # the page the data will appear in (different for inline)
515 # Using local because it needs to be set within any nested calls
517 local $preprocess_preview=$preview if defined $preview;
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,
569 preview => $preprocess_preview,
571 $preprocessing{$page}--;
575 return "[[$command $params]]";
579 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
583 sub filter ($$) { #{{{
587 run_hooks(filter => sub {
588 $content=shift->(page => $page, content => $content);
594 sub indexlink () { #{{{
595 return "<a href=\"$config{url}\">$config{wikiname}</a>";
598 sub lockwiki () { #{{{
599 # Take an exclusive lock on the wiki to prevent multiple concurrent
600 # run issues. The lock will be dropped on program exit.
601 if (! -d $config{wikistatedir}) {
602 mkdir($config{wikistatedir});
604 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
605 error ("cannot write to $config{wikistatedir}/lockfile: $!");
606 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
607 debug("wiki seems to be locked, waiting for lock");
608 my $wait=600; # arbitrary, but don't hang forever to
609 # prevent process pileup
611 return if flock(WIKILOCK, 2 | 4);
614 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
618 sub unlockwiki () { #{{{
622 sub commit_hook_enabled () { #{{{
623 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
624 error ("cannot write to $config{wikistatedir}/commitlock: $!");
625 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
633 sub disable_commit_hook () { #{{{
634 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
635 error ("cannot write to $config{wikistatedir}/commitlock: $!");
636 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
637 error("failed to get commit lock");
641 sub enable_commit_hook () { #{{{
645 sub loadindex () { #{{{
646 open (IN, "$config{wikistatedir}/index") || return;
648 $_=possibly_foolish_untaint($_);
653 foreach my $i (split(/ /, $_)) {
654 my ($item, $val)=split(/=/, $i, 2);
655 push @{$items{$item}}, decode_entities($val);
658 next unless exists $items{src}; # skip bad lines for now
660 my $page=pagename($items{src}[0]);
661 if (! $config{rebuild}) {
662 $pagesources{$page}=$items{src}[0];
663 $oldpagemtime{$page}=$items{mtime}[0];
664 $oldlinks{$page}=[@{$items{link}}];
665 $links{$page}=[@{$items{link}}];
666 $depends{$page}=$items{depends}[0] if exists $items{depends};
667 $renderedfiles{$page}=[@{$items{dest}}];
668 $oldrenderedfiles{$page}=[@{$items{dest}}];
669 $pagecase{lc $page}=$page;
671 $pagectime{$page}=$items{ctime}[0];
676 sub saveindex () { #{{{
677 run_hooks(savestate => sub { shift->() });
679 if (! -d $config{wikistatedir}) {
680 mkdir($config{wikistatedir});
682 my $newfile="$config{wikistatedir}/index.new";
683 my $cleanup = sub { unlink($newfile) };
684 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
685 foreach my $page (keys %oldpagemtime) {
686 next unless $oldpagemtime{$page};
687 my $line="mtime=$oldpagemtime{$page} ".
688 "ctime=$pagectime{$page} ".
689 "src=$pagesources{$page}";
690 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
692 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
693 if (exists $depends{$page}) {
694 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
696 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
698 close OUT || error("failed saving to $newfile: $!", $cleanup);
699 rename($newfile, "$config{wikistatedir}/index") ||
700 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
703 sub template_file ($) { #{{{
706 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
707 return "$dir/$template" if -e "$dir/$template";
712 sub template_params (@) { #{{{
713 my $filename=template_file(shift);
715 if (! defined $filename) {
720 require HTML::Template;
723 my $text_ref = shift;
724 $$text_ref=&Encode::decode_utf8($$text_ref);
726 filename => $filename,
727 loop_context_vars => 1,
728 die_on_bad_params => 0,
731 return wantarray ? @ret : {@ret};
734 sub template ($;@) { #{{{
735 HTML::Template->new(template_params(@_));
738 sub misctemplate ($$;@) { #{{{
742 my $template=template("misc.tmpl");
745 indexlink => indexlink(),
746 wikiname => $config{wikiname},
747 pagebody => $pagebody,
748 baseurl => baseurl(),
751 run_hooks(pagetemplate => sub {
752 shift->(page => "", destpage => "", template => $template);
754 return $template->output;
760 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
761 error "hook requires type, call, and id parameters";
764 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
766 $hooks{$param{type}}{$param{id}}=\%param;
769 sub run_hooks ($$) { # {{{
770 # Calls the given sub for each hook of the given type,
771 # passing it the hook function to call.
775 if (exists $hooks{$type}) {
777 foreach my $id (keys %{$hooks{$type}}) {
778 if ($hooks{$type}{$id}{last}) {
782 $sub->($hooks{$type}{$id}{call});
784 foreach my $id (@deferred) {
785 $sub->($hooks{$type}{$id}{call});
790 sub globlist_to_pagespec ($) { #{{{
791 my @globlist=split(' ', shift);
794 foreach my $glob (@globlist) {
795 if ($glob=~/^!(.*)/) {
803 my $spec=join(" or ", @spec);
805 my $skip=join(" and ", @skip);
807 $spec="$skip and ($spec)";
816 sub is_globlist ($) { #{{{
818 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
821 sub safequote ($) { #{{{
827 sub add_depends ($$) { #{{{
831 if (! exists $depends{$page}) {
832 $depends{$page}=$pagespec;
835 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
839 sub file_pruned ($$) { #{{{
841 my $file=File::Spec->canonpath(shift);
842 my $base=File::Spec->canonpath(shift);
843 $file=~s#^\Q$base\E/*##;
845 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
850 # Only use gettext in the rare cases it's needed.
851 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
852 if (! $gettext_obj) {
854 use Locale::gettext q{textdomain};
855 Locale::gettext->domain('ikiwiki')
863 return $gettext_obj->get(shift);
870 sub pagespec_merge ($$) { #{{{
874 return $a if $a eq $b;
876 # Support for old-style GlobLists.
877 if (is_globlist($a)) {
878 $a=globlist_to_pagespec($a);
880 if (is_globlist($b)) {
881 $b=globlist_to_pagespec($b);
884 return "($a) or ($b)";
887 sub pagespec_translate ($) { #{{{
888 # This assumes that $page is in scope in the function
889 # that evalulates the translated pagespec code.
892 # Support for old-style GlobLists.
893 if (is_globlist($spec)) {
894 $spec=globlist_to_pagespec($spec);
897 # Convert spec to perl code.
899 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
901 if (lc $word eq "and") {
904 elsif (lc $word eq "or") {
907 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
910 elsif ($word =~ /^(\w+)\((.*)\)$/) {
911 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
912 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
919 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
926 sub pagespec_match ($$;$) { #{{{
931 return eval pagespec_translate($spec);
934 package IkiWiki::PageSpec;
936 sub match_glob ($$$) { #{{{
940 if (! defined $from){
945 if ($glob =~ m!^\./!) {
948 $glob="$from/$glob" if length $from;
951 # turn glob into safe regexp
952 $glob=quotemeta($glob);
956 return $page=~/^$glob$/i;
959 sub match_link ($$) { #{{{
963 my $links = $IkiWiki::links{$page} or return undef;
964 foreach my $p (@$links) {
965 return 1 if lc $p eq $link;
970 sub match_backlink ($$) { #{{{
971 match_link(pop, pop);
974 sub match_created_before ($$) { #{{{
978 if (exists $IkiWiki::pagectime{$testpage}) {
979 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
986 sub match_created_after ($$) { #{{{
990 if (exists $IkiWiki::pagectime{$testpage}) {
991 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
998 sub match_creation_day ($$) { #{{{
999 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1002 sub match_creation_month ($$) { #{{{
1003 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1006 sub match_creation_year ($$) { #{{{
1007 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);