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/\/\./,
32 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
33 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
34 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
35 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
36 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
40 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, 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 || 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+)__/chr($1)/eg;
369 $page=~s/__(\d+)__/&#$1;/g;
376 sub titlepage ($) { #{{{
379 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
383 sub cgiurl (@) { #{{{
386 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
389 sub baseurl (;$) { #{{{
392 return "$config{url}/" if ! defined $page;
395 $page=~s/[^\/]+\//..\//g;
399 sub abs2rel ($$) { #{{{
400 # Work around very innefficient behavior in File::Spec if abs2rel
401 # is passed two relative paths. It's much faster if paths are
402 # absolute! (Debian bug #376658; fixed in debian unstable now)
407 my $ret=File::Spec->abs2rel($path, $base);
408 $ret=~s/^// if defined $ret;
412 sub displaytime ($) { #{{{
417 # strftime doesn't know about encodings, so make sure
418 # its output is properly treated as utf8
419 return decode_utf8(POSIX::strftime(
420 $config{timeformat}, localtime($time)));
423 sub htmllink ($$$;$$$) { #{{{
424 my $lpage=shift; # the page doing the linking
425 my $page=shift; # the page that will contain the link (different for inline)
427 my $noimageinline=shift; # don't turn links into inline html images
428 my $forcesubpage=shift; # force a link to a subpage
429 my $linktext=shift; # set to force the link text to something
432 if (! $forcesubpage) {
433 $bestlink=bestlink($lpage, $link);
436 $bestlink="$lpage/".lc($link);
439 $linktext=pagetitle(basename($link)) unless defined $linktext;
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 (! $noimageinline && isinlinableimage($bestlink)) {
457 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
459 return "<a href=\"$bestlink\">$linktext</a>";
462 sub htmlize ($$$) { #{{{
467 if (exists $hooks{htmlize}{$type}) {
468 $content=$hooks{htmlize}{$type}{call}->(
474 error("htmlization of $type not supported");
477 run_hooks(sanitize => sub {
487 sub linkify ($$$) { #{{{
488 my $lpage=shift; # the page containing the links
489 my $page=shift; # the page the link will end up on (different for inline)
492 $content =~ s{(\\?)$config{wiki_link_regexp}}{
493 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
494 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
501 sub preprocess ($$$;$) { #{{{
502 my $page=shift; # the page the data comes from
503 my $destpage=shift; # the page the data will appear in (different for inline)
511 if (length $escape) {
512 return "[[$command $params]]";
514 elsif (exists $hooks{preprocess}{$command}) {
515 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
516 # Note: preserve order of params, some plugins may
517 # consider it significant.
519 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
536 push @params, $key, $val;
539 push @params, $val, '';
542 if ($preprocessing{$page}++ > 3) {
543 # Avoid loops of preprocessed pages preprocessing
544 # other pages that preprocess them, etc.
545 #translators: The first parameter is a
546 #translators: preprocessor directive name,
547 #translators: the second a page name, the
548 #translators: third a number.
549 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
550 $command, $page, $preprocessing{$page}).
553 my $ret=$hooks{preprocess}{$command}{call}->(
556 destpage => $destpage,
558 $preprocessing{$page}--;
562 return "[[$command $params]]";
566 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
570 sub filter ($$) { #{{{
574 run_hooks(filter => sub {
575 $content=shift->(page => $page, content => $content);
581 sub indexlink () { #{{{
582 return "<a href=\"$config{url}\">$config{wikiname}</a>";
585 sub lockwiki () { #{{{
586 # Take an exclusive lock on the wiki to prevent multiple concurrent
587 # run issues. The lock will be dropped on program exit.
588 if (! -d $config{wikistatedir}) {
589 mkdir($config{wikistatedir});
591 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
592 error ("cannot write to $config{wikistatedir}/lockfile: $!");
593 if (! flock(WIKILOCK, 2 | 4)) {
594 debug("wiki seems to be locked, waiting for lock");
595 my $wait=600; # arbitrary, but don't hang forever to
596 # prevent process pileup
598 return if flock(WIKILOCK, 2 | 4);
601 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
605 sub unlockwiki () { #{{{
609 sub loadindex () { #{{{
610 open (IN, "$config{wikistatedir}/index") || return;
612 $_=possibly_foolish_untaint($_);
617 foreach my $i (split(/ /, $_)) {
618 my ($item, $val)=split(/=/, $i, 2);
619 push @{$items{$item}}, decode_entities($val);
622 next unless exists $items{src}; # skip bad lines for now
624 my $page=pagename($items{src}[0]);
625 if (! $config{rebuild}) {
626 $pagesources{$page}=$items{src}[0];
627 $oldpagemtime{$page}=$items{mtime}[0];
628 $oldlinks{$page}=[@{$items{link}}];
629 $links{$page}=[@{$items{link}}];
630 $depends{$page}=$items{depends}[0] if exists $items{depends};
631 $renderedfiles{$page}=[@{$items{dest}}];
632 $oldrenderedfiles{$page}=[@{$items{dest}}];
633 $pagecase{lc $page}=$page;
635 $pagectime{$page}=$items{ctime}[0];
640 sub saveindex () { #{{{
641 run_hooks(savestate => sub { shift->() });
643 if (! -d $config{wikistatedir}) {
644 mkdir($config{wikistatedir});
646 my $newfile="$config{wikistatedir}/index.new";
647 my $cleanup = sub { unlink($newfile) };
648 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
649 foreach my $page (keys %oldpagemtime) {
650 next unless $oldpagemtime{$page};
651 my $line="mtime=$oldpagemtime{$page} ".
652 "ctime=$pagectime{$page} ".
653 "src=$pagesources{$page}";
654 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
656 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
657 if (exists $depends{$page}) {
658 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
660 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
662 close OUT || error("failed saving to $newfile: $!", $cleanup);
663 rename($newfile, "$config{wikistatedir}/index") ||
664 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
667 sub template_file ($) { #{{{
670 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
671 return "$dir/$template" if -e "$dir/$template";
676 sub template_params (@) { #{{{
677 my $filename=template_file(shift);
679 if (! defined $filename) {
684 require HTML::Template;
687 my $text_ref = shift;
688 $$text_ref=&Encode::decode_utf8($$text_ref);
690 filename => $filename,
691 loop_context_vars => 1,
692 die_on_bad_params => 0,
695 return wantarray ? @ret : {@ret};
698 sub template ($;@) { #{{{
699 HTML::Template->new(template_params(@_));
702 sub misctemplate ($$;@) { #{{{
706 my $template=template("misc.tmpl");
709 indexlink => indexlink(),
710 wikiname => $config{wikiname},
711 pagebody => $pagebody,
712 baseurl => baseurl(),
715 run_hooks(pagetemplate => sub {
716 shift->(page => "", destpage => "", template => $template);
718 return $template->output;
724 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
725 error "hook requires type, call, and id parameters";
728 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
730 $hooks{$param{type}}{$param{id}}=\%param;
733 sub run_hooks ($$) { # {{{
734 # Calls the given sub for each hook of the given type,
735 # passing it the hook function to call.
739 if (exists $hooks{$type}) {
741 foreach my $id (keys %{$hooks{$type}}) {
742 if ($hooks{$type}{$id}{last}) {
746 $sub->($hooks{$type}{$id}{call});
748 foreach my $id (@deferred) {
749 $sub->($hooks{$type}{$id}{call});
754 sub globlist_to_pagespec ($) { #{{{
755 my @globlist=split(' ', shift);
758 foreach my $glob (@globlist) {
759 if ($glob=~/^!(.*)/) {
767 my $spec=join(" or ", @spec);
769 my $skip=join(" and ", @skip);
771 $spec="$skip and ($spec)";
780 sub is_globlist ($) { #{{{
782 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
785 sub safequote ($) { #{{{
791 sub add_depends ($$) { #{{{
795 if (! exists $depends{$page}) {
796 $depends{$page}=$pagespec;
799 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
803 sub file_pruned ($$) { #{{{
805 my $file=File::Spec->canonpath(shift);
806 my $base=File::Spec->canonpath(shift);
807 $file=~s#^\Q$base\E/*##;
809 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
814 # Only use gettext in the rare cases it's needed.
815 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
816 if (! $gettext_obj) {
818 use Locale::gettext q{textdomain};
819 Locale::gettext->domain('ikiwiki')
827 return $gettext_obj->get(shift);
834 sub pagespec_merge ($$) { #{{{
838 return $a if $a eq $b;
840 # Support for old-style GlobLists.
841 if (is_globlist($a)) {
842 $a=globlist_to_pagespec($a);
844 if (is_globlist($b)) {
845 $b=globlist_to_pagespec($b);
848 return "($a) or ($b)";
851 sub pagespec_translate ($) { #{{{
852 # This assumes that $page is in scope in the function
853 # that evalulates the translated pagespec code.
856 # Support for old-style GlobLists.
857 if (is_globlist($spec)) {
858 $spec=globlist_to_pagespec($spec);
861 # Convert spec to perl code.
863 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
865 if (lc $word eq "and") {
868 elsif (lc $word eq "or") {
871 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
874 elsif ($word =~ /^(\w+)\((.*)\)$/) {
875 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
876 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
883 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
890 sub pagespec_match ($$;$) { #{{{
895 return eval pagespec_translate($spec);
898 package IkiWiki::PageSpec;
900 sub match_glob ($$$) { #{{{
904 if (! defined $from){
909 if ($glob =~ m!^\./!) {
912 $glob="$from/$glob" if length $from;
915 # turn glob into safe regexp
916 $glob=quotemeta($glob);
920 return $page=~/^$glob$/i;
923 sub match_link ($$) { #{{{
927 my $links = $IkiWiki::links{$page} or return undef;
928 foreach my $p (@$links) {
929 return 1 if lc $p eq $link;
934 sub match_backlink ($$) { #{{{
935 match_link(pop, pop);
938 sub match_created_before ($$) { #{{{
942 if (exists $IkiWiki::pagectime{$testpage}) {
943 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
950 sub match_created_after ($$) { #{{{
954 if (exists $IkiWiki::pagectime{$testpage}) {
955 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
962 sub match_creation_day ($$) { #{{{
963 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
966 sub match_creation_month ($$) { #{{{
967 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
970 sub match_creation_year ($$) { #{{{
971 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);