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.01; # plugin interface version
24 memoize("pagespec_translate");
25 memoize("file_pruned");
27 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 sub defaultconfig () { #{{{
31 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./, qr/\.x?html?$/,
32 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
33 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
34 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
35 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
39 default_pageext => "mdwn",
58 gitorigin_branch => "origin",
59 gitmaster_branch => "master",
63 templatedir => "$installdir/share/ikiwiki/templates",
64 underlaydir => "$installdir/share/ikiwiki/basewiki",
68 plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
69 lockedit conditional}],
77 sub checkconfig () { #{{{
78 # locale stuff; avoid LC_ALL since it overrides everything
79 if (defined $ENV{LC_ALL}) {
80 $ENV{LANG} = $ENV{LC_ALL};
83 if (defined $config{locale}) {
86 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
87 $ENV{LANG}=$config{locale};
92 if ($config{w3mmode}) {
93 eval q{use Cwd q{abs_path}};
95 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
96 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
97 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
98 unless $config{cgiurl} =~ m!file:///!;
99 $config{url}="file://".$config{destdir};
102 if ($config{cgi} && ! length $config{url}) {
103 error(gettext("Must specify url to wiki with --url when using --cgi"));
106 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
107 unless exists $config{wikistatedir};
110 eval qq{require IkiWiki::Rcs::$config{rcs}};
112 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
116 require IkiWiki::Rcs::Stub;
119 run_hooks(checkconfig => sub { shift->() });
122 sub loadplugins () { #{{{
123 loadplugin($_) foreach @{$config{plugin}};
125 run_hooks(getopt => sub { shift->() });
126 if (grep /^-/, @ARGV) {
127 print STDERR "Unknown option: $_\n"
128 foreach grep /^-/, @ARGV;
133 sub loadplugin ($) { #{{{
136 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
138 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
141 error("Failed to load plugin $mod: $@");
147 print "Content-type: text/html\n\n";
148 print misctemplate(gettext("Error"),
149 "<p>".gettext("Error").": @_</p>");
151 log_message(error => @_);
156 return unless $config{verbose};
157 log_message(debug => @_);
161 sub log_message ($$) { #{{{
164 if ($config{syslog}) {
167 Sys::Syslog::setlogsock('unix');
168 Sys::Syslog::openlog('ikiwiki', '', 'user');
172 Sys::Syslog::syslog($type, join(" ", @_));
175 elsif (! $config{cgi}) {
183 sub possibly_foolish_untaint ($) { #{{{
185 my ($untainted)=$tainted=~/(.*)/;
189 sub basename ($) { #{{{
196 sub dirname ($) { #{{{
203 sub pagetype ($) { #{{{
206 if ($page =~ /\.([^.]+)$/) {
207 return $1 if exists $hooks{htmlize}{$1};
212 sub pagename ($) { #{{{
215 my $type=pagetype($file);
217 $page=~s/\Q.$type\E*$// if defined $type;
221 sub htmlpage ($) { #{{{
224 return $page.".html";
227 sub srcfile ($) { #{{{
230 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
231 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
232 error("internal error: $file cannot be found");
235 sub readfile ($;$$) { #{{{
241 error("cannot read a symlink ($file)");
245 open (IN, $file) || error("failed to read $file: $!");
246 binmode(IN) if ($binary);
247 return \*IN if $wantfd;
253 sub writefile ($$$;$$) { #{{{
254 my $file=shift; # can include subdirs
255 my $destdir=shift; # directory to put file in
261 while (length $test) {
262 if (-l "$destdir/$test") {
263 error("cannot write to a symlink ($test)");
265 $test=dirname($test);
268 my $dir=dirname("$destdir/$file");
271 foreach my $s (split(m!/+!, $dir)) {
274 mkdir($d) || error("failed to create directory $d: $!");
279 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
280 binmode(OUT) if ($binary);
281 return \*OUT if $wantfd;
287 sub will_render ($$;$) { #{{{
292 # Important security check.
293 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
294 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
295 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
298 if (! $clear || $cleared{$page}) {
299 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
302 $renderedfiles{$page}=[$dest];
307 sub bestlink ($$) { #{{{
312 if ($link=~s/^\/+//) {
319 $l.="/" if length $l;
322 if (exists $links{$l}) {
325 elsif (exists $pagecase{lc $l}) {
326 return $pagecase{lc $l};
328 } while $cwd=~s!/?[^/]+$!!;
330 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
331 return "$config{userdir}/".lc($link);
334 #print STDERR "warning: page $page, broken link: $link\n";
338 sub isinlinableimage ($) { #{{{
341 $file=~/\.(png|gif|jpg|jpeg)$/i;
344 sub pagetitle ($;$) { #{{{
349 $page=~s/__(\d+)__/chr($1)/eg;
352 $page=~s/__(\d+)__/&#$1;/g;
359 sub titlepage ($) { #{{{
362 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
366 sub cgiurl (@) { #{{{
369 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
372 sub baseurl (;$) { #{{{
375 return "$config{url}/" if ! defined $page;
378 $page=~s/[^\/]+\//..\//g;
382 sub abs2rel ($$) { #{{{
383 # Work around very innefficient behavior in File::Spec if abs2rel
384 # is passed two relative paths. It's much faster if paths are
385 # absolute! (Debian bug #376658; fixed in debian unstable now)
390 my $ret=File::Spec->abs2rel($path, $base);
391 $ret=~s/^// if defined $ret;
395 sub displaytime ($) { #{{{
400 # strftime doesn't know about encodings, so make sure
401 # its output is properly treated as utf8
402 return decode_utf8(POSIX::strftime(
403 $config{timeformat}, localtime($time)));
406 sub htmllink ($$$;$$$) { #{{{
407 my $lpage=shift; # the page doing the linking
408 my $page=shift; # the page that will contain the link (different for inline)
410 my $noimageinline=shift; # don't turn links into inline html images
411 my $forcesubpage=shift; # force a link to a subpage
412 my $linktext=shift; # set to force the link text to something
415 if (! $forcesubpage) {
416 $bestlink=bestlink($lpage, $link);
419 $bestlink="$lpage/".lc($link);
422 $linktext=pagetitle(basename($link)) unless defined $linktext;
424 return "<span class=\"selflink\">$linktext</span>"
425 if length $bestlink && $page eq $bestlink;
427 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
428 $bestlink=htmlpage($bestlink);
430 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
431 return $linktext unless length $config{cgiurl};
432 return "<span><a href=\"".
433 cgiurl(do => "create", page => lc($link), from => $page).
434 "\">?</a>$linktext</span>"
437 $bestlink=abs2rel($bestlink, dirname($page));
439 if (! $noimageinline && isinlinableimage($bestlink)) {
440 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
442 return "<a href=\"$bestlink\">$linktext</a>";
445 sub htmlize ($$$) { #{{{
450 if (exists $hooks{htmlize}{$type}) {
451 $content=$hooks{htmlize}{$type}{call}->(
457 error("htmlization of $type not supported");
460 run_hooks(sanitize => sub {
470 sub linkify ($$$) { #{{{
471 my $lpage=shift; # the page containing the links
472 my $page=shift; # the page the link will end up on (different for inline)
475 $content =~ s{(\\?)$config{wiki_link_regexp}}{
476 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
477 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
484 sub preprocess ($$$;$) { #{{{
485 my $page=shift; # the page the data comes from
486 my $destpage=shift; # the page the data will appear in (different for inline)
494 if (length $escape) {
495 return "[[$command $params]]";
497 elsif (exists $hooks{preprocess}{$command}) {
498 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
499 # Note: preserve order of params, some plugins may
500 # consider it significant.
502 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
519 push @params, $key, $val;
522 push @params, $val, '';
525 if ($preprocessing{$page}++ > 3) {
526 # Avoid loops of preprocessed pages preprocessing
527 # other pages that preprocess them, etc.
528 #translators: The first parameter is a
529 #translators: preprocessor directive name,
530 #translators: the second a page name, the
531 #translators: third a number.
532 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
533 $command, $page, $preprocessing{$page}).
536 my $ret=$hooks{preprocess}{$command}{call}->(
539 destpage => $destpage,
541 $preprocessing{$page}--;
545 return "[[$command $params]]";
549 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
553 sub filter ($$) { #{{{
557 run_hooks(filter => sub {
558 $content=shift->(page => $page, content => $content);
564 sub indexlink () { #{{{
565 return "<a href=\"$config{url}\">$config{wikiname}</a>";
568 sub lockwiki () { #{{{
569 # Take an exclusive lock on the wiki to prevent multiple concurrent
570 # run issues. The lock will be dropped on program exit.
571 if (! -d $config{wikistatedir}) {
572 mkdir($config{wikistatedir});
574 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
575 error ("cannot write to $config{wikistatedir}/lockfile: $!");
576 if (! flock(WIKILOCK, 2 | 4)) {
577 debug("wiki seems to be locked, waiting for lock");
578 my $wait=600; # arbitrary, but don't hang forever to
579 # prevent process pileup
581 return if flock(WIKILOCK, 2 | 4);
584 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
588 sub unlockwiki () { #{{{
592 sub loadindex () { #{{{
593 open (IN, "$config{wikistatedir}/index") || return;
595 $_=possibly_foolish_untaint($_);
600 foreach my $i (split(/ /, $_)) {
601 my ($item, $val)=split(/=/, $i, 2);
602 push @{$items{$item}}, decode_entities($val);
605 next unless exists $items{src}; # skip bad lines for now
607 my $page=pagename($items{src}[0]);
608 if (! $config{rebuild}) {
609 $pagesources{$page}=$items{src}[0];
610 $oldpagemtime{$page}=$items{mtime}[0];
611 $oldlinks{$page}=[@{$items{link}}];
612 $links{$page}=[@{$items{link}}];
613 $depends{$page}=$items{depends}[0] if exists $items{depends};
614 $renderedfiles{$page}=[@{$items{dest}}];
615 $oldrenderedfiles{$page}=[@{$items{dest}}];
616 $pagecase{lc $page}=$page;
618 $pagectime{$page}=$items{ctime}[0];
623 sub saveindex () { #{{{
624 run_hooks(savestate => sub { shift->() });
626 if (! -d $config{wikistatedir}) {
627 mkdir($config{wikistatedir});
629 open (OUT, ">$config{wikistatedir}/index") ||
630 error("cannot write to $config{wikistatedir}/index: $!");
631 foreach my $page (keys %oldpagemtime) {
632 next unless $oldpagemtime{$page};
633 my $line="mtime=$oldpagemtime{$page} ".
634 "ctime=$pagectime{$page} ".
635 "src=$pagesources{$page}";
636 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
638 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
639 if (exists $depends{$page}) {
640 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
642 print OUT $line."\n";
647 sub template_file ($) { #{{{
650 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
651 return "$dir/$template" if -e "$dir/$template";
656 sub template_params (@) { #{{{
657 my $filename=template_file(shift);
659 if (! defined $filename) {
664 require HTML::Template;
667 my $text_ref = shift;
668 $$text_ref=&Encode::decode_utf8($$text_ref);
670 filename => $filename,
671 loop_context_vars => 1,
672 die_on_bad_params => 0,
675 return wantarray ? @ret : {@ret};
678 sub template ($;@) { #{{{
679 HTML::Template->new(template_params(@_));
682 sub misctemplate ($$;@) { #{{{
686 my $template=template("misc.tmpl");
689 indexlink => indexlink(),
690 wikiname => $config{wikiname},
691 pagebody => $pagebody,
692 baseurl => baseurl(),
695 run_hooks(pagetemplate => sub {
696 shift->(page => "", destpage => "", template => $template);
698 return $template->output;
704 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
705 error "hook requires type, call, and id parameters";
708 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
710 $hooks{$param{type}}{$param{id}}=\%param;
713 sub run_hooks ($$) { # {{{
714 # Calls the given sub for each hook of the given type,
715 # passing it the hook function to call.
719 if (exists $hooks{$type}) {
721 foreach my $id (keys %{$hooks{$type}}) {
722 if ($hooks{$type}{$id}{last}) {
726 $sub->($hooks{$type}{$id}{call});
728 foreach my $id (@deferred) {
729 $sub->($hooks{$type}{$id}{call});
734 sub globlist_to_pagespec ($) { #{{{
735 my @globlist=split(' ', shift);
738 foreach my $glob (@globlist) {
739 if ($glob=~/^!(.*)/) {
747 my $spec=join(" or ", @spec);
749 my $skip=join(" and ", @skip);
751 $spec="$skip and ($spec)";
760 sub is_globlist ($) { #{{{
762 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
765 sub safequote ($) { #{{{
771 sub add_depends ($$) { #{{{
775 if (! exists $depends{$page}) {
776 $depends{$page}=$pagespec;
779 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
783 sub file_pruned ($$) { #{{{
785 my $file=File::Spec->canonpath(shift);
786 my $base=File::Spec->canonpath(shift);
787 $file=~s#^\Q$base\E/*##;
789 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
794 # Only use gettext in the rare cases it's needed.
795 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
796 if (! $gettext_obj) {
798 use Locale::gettext q{textdomain};
799 Locale::gettext->domain('ikiwiki')
807 return $gettext_obj->get(shift);
814 sub pagespec_merge ($$) { #{{{
818 return $a if $a eq $b;
820 # Support for old-style GlobLists.
821 if (is_globlist($a)) {
822 $a=globlist_to_pagespec($a);
824 if (is_globlist($b)) {
825 $b=globlist_to_pagespec($b);
828 return "($a) or ($b)";
831 sub pagespec_translate ($) { #{{{
832 # This assumes that $page is in scope in the function
833 # that evalulates the translated pagespec code.
836 # Support for old-style GlobLists.
837 if (is_globlist($spec)) {
838 $spec=globlist_to_pagespec($spec);
841 # Convert spec to perl code.
843 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
845 if (lc $word eq "and") {
848 elsif (lc $word eq "or") {
851 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
854 elsif ($word =~ /^(\w+)\((.*)\)$/) {
855 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
856 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
863 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
870 sub pagespec_match ($$;$) { #{{{
875 return eval pagespec_translate($spec);
878 package IkiWiki::PageSpec;
880 sub match_glob ($$$) { #{{{
884 if (! defined $from){
889 if ($glob =~ m!^\./!) {
892 $glob="$from/$glob" if length $from;
895 # turn glob into safe regexp
896 $glob=quotemeta($glob);
900 return $page=~/^$glob$/i;
903 sub match_link ($$) { #{{{
907 my $links = $IkiWiki::links{$page} or return undef;
908 foreach my $p (@$links) {
909 return 1 if lc $p eq $link;
914 sub match_backlink ($$) { #{{{
915 match_link(pop, pop);
918 sub match_created_before ($$) { #{{{
922 if (exists $IkiWiki::pagectime{$testpage}) {
923 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
930 sub match_created_after ($$) { #{{{
934 if (exists $IkiWiki::pagectime{$testpage}) {
935 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
942 sub match_creation_day ($$) { #{{{
943 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
946 sub match_creation_month ($$) { #{{{
947 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
950 sub match_creation_year ($$) { #{{{
951 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);