8 use URI::Escape q{uri_escape_utf8};
10 use open qw{:utf8 :std};
12 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
13 %renderedfiles %oldrenderedfiles %pagesources %destsources
14 %depends %hooks %forcerebuild $gettext_obj};
16 use Exporter q{import};
17 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
18 bestlink htmllink readfile writefile pagetype srcfile pagename
19 displaytime will_render gettext urlto targetpage
20 %config %links %renderedfiles %pagesources %destsources);
21 our $VERSION = 1.02; # plugin interface version, next is ikiwiki version
22 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
23 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
28 memoize("pagespec_translate");
29 memoize("file_pruned");
31 sub defaultconfig () { #{{{
32 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
33 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
34 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
35 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
36 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
37 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
41 default_pageext => "mdwn",
61 gitorigin_branch => "origin",
62 gitmaster_branch => "master",
66 templatedir => "$installdir/share/ikiwiki/templates",
67 underlaydir => "$installdir/share/ikiwiki/basewiki",
71 plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
72 lockedit conditional}],
82 sub checkconfig () { #{{{
83 # locale stuff; avoid LC_ALL since it overrides everything
84 if (defined $ENV{LC_ALL}) {
85 $ENV{LANG} = $ENV{LC_ALL};
88 if (defined $config{locale}) {
89 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
90 $ENV{LANG}=$config{locale};
95 if ($config{w3mmode}) {
96 eval q{use Cwd q{abs_path}};
98 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
99 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
100 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
101 unless $config{cgiurl} =~ m!file:///!;
102 $config{url}="file://".$config{destdir};
105 if ($config{cgi} && ! length $config{url}) {
106 error(gettext("Must specify url to wiki with --url when using --cgi"));
109 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
110 unless exists $config{wikistatedir};
113 eval qq{require IkiWiki::Rcs::$config{rcs}};
115 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
119 require IkiWiki::Rcs::Stub;
122 run_hooks(checkconfig => sub { shift->() });
125 sub loadplugins () { #{{{
126 loadplugin($_) foreach @{$config{plugin}};
128 run_hooks(getopt => sub { shift->() });
129 if (grep /^-/, @ARGV) {
130 print STDERR "Unknown option: $_\n"
131 foreach grep /^-/, @ARGV;
136 sub loadplugin ($) { #{{{
139 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
141 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
144 error("Failed to load plugin $mod: $@");
148 sub error ($;$) { #{{{
152 print "Content-type: text/html\n\n";
153 print misctemplate(gettext("Error"),
154 "<p>".gettext("Error").": $message</p>");
156 log_message('err' => $message) if $config{syslog};
157 if (defined $cleaner) {
164 return unless $config{verbose};
165 log_message(debug => @_);
169 sub log_message ($$) { #{{{
172 if ($config{syslog}) {
175 Sys::Syslog::setlogsock('unix');
176 Sys::Syslog::openlog('ikiwiki', '', 'user');
180 Sys::Syslog::syslog($type, "%s", join(" ", @_));
183 elsif (! $config{cgi}) {
191 sub possibly_foolish_untaint ($) { #{{{
193 my ($untainted)=$tainted=~/(.*)/;
197 sub basename ($) { #{{{
204 sub dirname ($) { #{{{
211 sub pagetype ($) { #{{{
214 if ($page =~ /\.([^.]+)$/) {
215 return $1 if exists $hooks{htmlize}{$1};
220 sub pagename ($) { #{{{
223 my $type=pagetype($file);
225 $page=~s/\Q.$type\E*$// if defined $type;
229 sub targetpage ($$) { #{{{
233 if (! $config{usedirs} || $page =~ /^index$/ ) {
234 return $page.".".$ext;
236 return $page."/index.".$ext;
240 sub htmlpage ($) { #{{{
243 return targetpage($page, "html");
246 sub srcfile ($) { #{{{
249 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
250 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
251 error("internal error: $file cannot be found in $config{srcdir} or $config{underlaydir}");
254 sub readfile ($;$$) { #{{{
260 error("cannot read a symlink ($file)");
264 open (IN, $file) || error("failed to read $file: $!");
265 binmode(IN) if ($binary);
266 return \*IN if $wantfd;
268 close IN || error("failed to read $file: $!");
272 sub writefile ($$$;$$) { #{{{
273 my $file=shift; # can include subdirs
274 my $destdir=shift; # directory to put file in
280 while (length $test) {
281 if (-l "$destdir/$test") {
282 error("cannot write to a symlink ($test)");
284 $test=dirname($test);
286 my $newfile="$destdir/$file.ikiwiki-new";
288 error("cannot write to a symlink ($newfile)");
291 my $dir=dirname($newfile);
294 foreach my $s (split(m!/+!, $dir)) {
297 mkdir($d) || error("failed to create directory $d: $!");
302 my $cleanup = sub { unlink($newfile) };
303 open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
304 binmode(OUT) if ($binary);
306 $writer->(\*OUT, $cleanup);
309 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
311 close OUT || error("failed saving $newfile: $!", $cleanup);
312 rename($newfile, "$destdir/$file") ||
313 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
317 sub will_render ($$;$) { #{{{
322 # Important security check.
323 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
324 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
325 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
328 if (! $clear || $cleared{$page}) {
329 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
332 foreach my $old (@{$renderedfiles{$page}}) {
333 delete $destsources{$old};
335 $renderedfiles{$page}=[$dest];
338 $destsources{$dest}=$page;
341 sub bestlink ($$) { #{{{
346 if ($link=~s/^\/+//) {
353 $l.="/" if length $l;
356 if (exists $links{$l}) {
359 elsif (exists $pagecase{lc $l}) {
360 return $pagecase{lc $l};
362 } while $cwd=~s!/?[^/]+$!!;
364 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
365 return "$config{userdir}/".lc($link);
368 #print STDERR "warning: page $page, broken link: $link\n";
372 sub isinlinableimage ($) { #{{{
375 $file=~/\.(png|gif|jpg|jpeg)$/i;
378 sub pagetitle ($;$) { #{{{
383 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
386 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
392 sub titlepage ($) { #{{{
394 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
398 sub linkpage ($) { #{{{
400 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
404 sub cgiurl (@) { #{{{
407 return $config{cgiurl}."?".
408 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
411 sub baseurl (;$) { #{{{
414 return "$config{url}/" if ! defined $page;
416 $page=htmlpage($page);
418 $page=~s/[^\/]+\//..\//g;
422 sub abs2rel ($$) { #{{{
423 # Work around very innefficient behavior in File::Spec if abs2rel
424 # is passed two relative paths. It's much faster if paths are
425 # absolute! (Debian bug #376658; fixed in debian unstable now)
430 my $ret=File::Spec->abs2rel($path, $base);
431 $ret=~s/^// if defined $ret;
435 sub displaytime ($) { #{{{
438 # strftime doesn't know about encodings, so make sure
439 # its output is properly treated as utf8
440 return decode_utf8(POSIX::strftime(
441 $config{timeformat}, localtime($time)));
444 sub beautify_url ($) { #{{{
447 $url =~ s!/index.html$!/!;
448 $url =~ s!^$!./!; # Browsers don't like empty links...
453 sub urlto ($$) { #{{{
458 return beautify_url(baseurl($from));
461 if (! $destsources{$to}) {
465 my $link = abs2rel($to, dirname(htmlpage($from)));
467 return beautify_url($link);
470 sub htmllink ($$$;@) { #{{{
471 my $lpage=shift; # the page doing the linking
472 my $page=shift; # the page that will contain the link (different for inline)
477 if (! $opts{forcesubpage}) {
478 $bestlink=bestlink($lpage, $link);
481 $bestlink="$lpage/".lc($link);
485 if (defined $opts{linktext}) {
486 $linktext=$opts{linktext};
489 $linktext=pagetitle(basename($link));
492 return "<span class=\"selflink\">$linktext</span>"
493 if length $bestlink && $page eq $bestlink;
495 if (! $destsources{$bestlink}) {
496 $bestlink=htmlpage($bestlink);
498 if (! $destsources{$bestlink}) {
499 return $linktext unless length $config{cgiurl};
500 return "<span><a href=\"".
503 page => pagetitle(lc($link), 1),
506 "\">?</a>$linktext</span>"
510 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
511 $bestlink=beautify_url($bestlink);
513 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
514 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
517 if (defined $opts{anchor}) {
518 $bestlink.="#".$opts{anchor};
521 return "<a href=\"$bestlink\">$linktext</a>";
524 sub htmlize ($$$) { #{{{
529 if (exists $hooks{htmlize}{$type}) {
530 $content=$hooks{htmlize}{$type}{call}->(
536 error("htmlization of $type not supported");
539 run_hooks(sanitize => sub {
549 sub linkify ($$$) { #{{{
550 my $lpage=shift; # the page containing the links
551 my $page=shift; # the page the link will end up on (different for inline)
554 $content =~ s{(\\?)$config{wiki_link_regexp}}{
557 ? "[[$2|$3".($4 ? "#$4" : "")."]]"
558 : htmllink($lpage, $page, linkpage($3),
559 anchor => $4, linktext => pagetitle($2)))
561 ? "[[$3".($4 ? "#$4" : "")."]]"
562 : htmllink($lpage, $page, linkpage($3),
570 our $preprocess_preview=0;
571 sub preprocess ($$$;$$) { #{{{
572 my $page=shift; # the page the data comes from
573 my $destpage=shift; # the page the data will appear in (different for inline)
578 # Using local because it needs to be set within any nested calls
580 local $preprocess_preview=$preview if defined $preview;
586 if (length $escape) {
587 return "[[$command $params]]";
589 elsif (exists $hooks{preprocess}{$command}) {
590 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
591 # Note: preserve order of params, some plugins may
592 # consider it significant.
594 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
611 push @params, $key, $val;
614 push @params, $val, '';
617 if ($preprocessing{$page}++ > 3) {
618 # Avoid loops of preprocessed pages preprocessing
619 # other pages that preprocess them, etc.
620 #translators: The first parameter is a
621 #translators: preprocessor directive name,
622 #translators: the second a page name, the
623 #translators: third a number.
624 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
625 $command, $page, $preprocessing{$page}).
628 my $ret=$hooks{preprocess}{$command}{call}->(
631 destpage => $destpage,
632 preview => $preprocess_preview,
634 $preprocessing{$page}--;
638 return "[[$command $params]]";
642 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
646 sub filter ($$) { #{{{
650 run_hooks(filter => sub {
651 $content=shift->(page => $page, content => $content);
657 sub indexlink () { #{{{
658 return "<a href=\"$config{url}\">$config{wikiname}</a>";
661 sub lockwiki () { #{{{
662 # Take an exclusive lock on the wiki to prevent multiple concurrent
663 # run issues. The lock will be dropped on program exit.
664 if (! -d $config{wikistatedir}) {
665 mkdir($config{wikistatedir});
667 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
668 error ("cannot write to $config{wikistatedir}/lockfile: $!");
669 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
670 debug("wiki seems to be locked, waiting for lock");
671 my $wait=600; # arbitrary, but don't hang forever to
672 # prevent process pileup
674 return if flock(WIKILOCK, 2 | 4);
677 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
681 sub unlockwiki () { #{{{
685 sub commit_hook_enabled () { #{{{
686 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
687 error ("cannot write to $config{wikistatedir}/commitlock: $!");
688 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
696 sub disable_commit_hook () { #{{{
697 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
698 error ("cannot write to $config{wikistatedir}/commitlock: $!");
699 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
700 error("failed to get commit lock");
704 sub enable_commit_hook () { #{{{
708 sub loadindex () { #{{{
709 open (IN, "$config{wikistatedir}/index") || return;
711 $_=possibly_foolish_untaint($_);
716 foreach my $i (split(/ /, $_)) {
717 my ($item, $val)=split(/=/, $i, 2);
718 push @{$items{$item}}, decode_entities($val);
721 next unless exists $items{src}; # skip bad lines for now
723 my $page=pagename($items{src}[0]);
724 if (! $config{rebuild}) {
725 $pagesources{$page}=$items{src}[0];
726 $pagemtime{$page}=$items{mtime}[0];
727 $oldlinks{$page}=[@{$items{link}}];
728 $links{$page}=[@{$items{link}}];
729 $depends{$page}=$items{depends}[0] if exists $items{depends};
730 $destsources{$_}=$page foreach @{$items{dest}};
731 $renderedfiles{$page}=[@{$items{dest}}];
732 $oldrenderedfiles{$page}=[@{$items{dest}}];
733 $pagecase{lc $page}=$page;
735 $pagectime{$page}=$items{ctime}[0];
740 sub saveindex () { #{{{
741 run_hooks(savestate => sub { shift->() });
743 if (! -d $config{wikistatedir}) {
744 mkdir($config{wikistatedir});
746 my $newfile="$config{wikistatedir}/index.new";
747 my $cleanup = sub { unlink($newfile) };
748 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
749 foreach my $page (keys %pagemtime) {
750 next unless $pagemtime{$page};
751 my $line="mtime=$pagemtime{$page} ".
752 "ctime=$pagectime{$page} ".
753 "src=$pagesources{$page}";
754 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
756 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
757 if (exists $depends{$page}) {
758 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
760 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
762 close OUT || error("failed saving to $newfile: $!", $cleanup);
763 rename($newfile, "$config{wikistatedir}/index") ||
764 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
767 sub template_file ($) { #{{{
770 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
771 return "$dir/$template" if -e "$dir/$template";
776 sub template_params (@) { #{{{
777 my $filename=template_file(shift);
779 if (! defined $filename) {
784 require HTML::Template;
787 my $text_ref = shift;
788 $$text_ref=&Encode::decode_utf8($$text_ref);
790 filename => $filename,
791 loop_context_vars => 1,
792 die_on_bad_params => 0,
795 return wantarray ? @ret : {@ret};
798 sub template ($;@) { #{{{
799 HTML::Template->new(template_params(@_));
802 sub misctemplate ($$;@) { #{{{
806 my $template=template("misc.tmpl");
809 indexlink => indexlink(),
810 wikiname => $config{wikiname},
811 pagebody => $pagebody,
812 baseurl => baseurl(),
815 run_hooks(pagetemplate => sub {
816 shift->(page => "", destpage => "", template => $template);
818 return $template->output;
824 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
825 error "hook requires type, call, and id parameters";
828 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
830 $hooks{$param{type}}{$param{id}}=\%param;
833 sub run_hooks ($$) { # {{{
834 # Calls the given sub for each hook of the given type,
835 # passing it the hook function to call.
839 if (exists $hooks{$type}) {
841 foreach my $id (keys %{$hooks{$type}}) {
842 if ($hooks{$type}{$id}{last}) {
846 $sub->($hooks{$type}{$id}{call});
848 foreach my $id (@deferred) {
849 $sub->($hooks{$type}{$id}{call});
854 sub globlist_to_pagespec ($) { #{{{
855 my @globlist=split(' ', shift);
858 foreach my $glob (@globlist) {
859 if ($glob=~/^!(.*)/) {
867 my $spec=join(" or ", @spec);
869 my $skip=join(" and ", @skip);
871 $spec="$skip and ($spec)";
880 sub is_globlist ($) { #{{{
882 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
885 sub safequote ($) { #{{{
891 sub add_depends ($$) { #{{{
895 if (! exists $depends{$page}) {
896 $depends{$page}=$pagespec;
899 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
903 sub file_pruned ($$) { #{{{
905 my $file=File::Spec->canonpath(shift);
906 my $base=File::Spec->canonpath(shift);
907 $file=~s#^\Q$base\E/*##;
909 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
914 # Only use gettext in the rare cases it's needed.
915 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
916 if (! $gettext_obj) {
918 use Locale::gettext q{textdomain};
919 Locale::gettext->domain('ikiwiki')
927 return $gettext_obj->get(shift);
934 sub pagespec_merge ($$) { #{{{
938 return $a if $a eq $b;
940 # Support for old-style GlobLists.
941 if (is_globlist($a)) {
942 $a=globlist_to_pagespec($a);
944 if (is_globlist($b)) {
945 $b=globlist_to_pagespec($b);
948 return "($a) or ($b)";
951 sub pagespec_translate ($) { #{{{
952 # This assumes that $page is in scope in the function
953 # that evalulates the translated pagespec code.
956 # Support for old-style GlobLists.
957 if (is_globlist($spec)) {
958 $spec=globlist_to_pagespec($spec);
961 # Convert spec to perl code.
963 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
965 if (lc $word eq "and") {
968 elsif (lc $word eq "or") {
971 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
974 elsif ($word =~ /^(\w+)\((.*)\)$/) {
975 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
976 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
983 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
990 sub pagespec_match ($$;$) { #{{{
995 return eval pagespec_translate($spec);
998 package IkiWiki::PageSpec;
1000 sub match_glob ($$$) { #{{{
1004 if (! defined $from){
1009 if ($glob =~ m!^\./!) {
1010 $from=~s!/?[^/]+$!!;
1012 $glob="$from/$glob" if length $from;
1015 # turn glob into safe regexp
1016 $glob=quotemeta($glob);
1020 return $page=~/^$glob$/i;
1023 sub match_link ($$$) { #{{{
1027 if (! defined $from){
1032 if ($link =~ m!^\.! && defined $from) {
1033 $from=~s!/?[^/]+$!!;
1035 $link="$from/$link" if length $from;
1038 my $links = $IkiWiki::links{$page} or return undef;
1039 return 0 unless @$links;
1040 my $bestlink = IkiWiki::bestlink($from, $link);
1041 return 0 unless length $bestlink;
1042 foreach my $p (@$links) {
1043 return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
1048 sub match_backlink ($$$) { #{{{
1049 match_link($_[1], $_[0], $_[3]);
1052 sub match_created_before ($$$) { #{{{
1056 if (exists $IkiWiki::pagectime{$testpage}) {
1057 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
1064 sub match_created_after ($$$) { #{{{
1068 if (exists $IkiWiki::pagectime{$testpage}) {
1069 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1076 sub match_creation_day ($$$) { #{{{
1077 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1080 sub match_creation_month ($$$) { #{{{
1081 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1084 sub match_creation_year ($$$) { #{{{
1085 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);