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 lockedit}],
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: $@");
146 print "Content-type: text/html\n\n";
147 print misctemplate(gettext("Error"),
148 "<p>".gettext("Error").": @_</p>");
150 log_message(error => @_);
155 return unless $config{verbose};
156 log_message(debug => @_);
160 sub log_message ($$) { #{{{
163 if ($config{syslog}) {
166 Sys::Syslog::setlogsock('unix');
167 Sys::Syslog::openlog('ikiwiki', '', 'user');
171 Sys::Syslog::syslog($type, join(" ", @_));
174 elsif (! $config{cgi}) {
182 sub possibly_foolish_untaint ($) { #{{{
184 my ($untainted)=$tainted=~/(.*)/;
188 sub basename ($) { #{{{
195 sub dirname ($) { #{{{
202 sub pagetype ($) { #{{{
205 if ($page =~ /\.([^.]+)$/) {
206 return $1 if exists $hooks{htmlize}{$1};
211 sub pagename ($) { #{{{
214 my $type=pagetype($file);
216 $page=~s/\Q.$type\E*$// if defined $type;
220 sub htmlpage ($) { #{{{
223 return $page.".html";
226 sub srcfile ($) { #{{{
229 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
230 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
231 error("internal error: $file cannot be found");
234 sub readfile ($;$$) { #{{{
240 error("cannot read a symlink ($file)");
244 open (IN, $file) || error("failed to read $file: $!");
245 binmode(IN) if ($binary);
246 return \*IN if $wantfd;
252 sub writefile ($$$;$$) { #{{{
253 my $file=shift; # can include subdirs
254 my $destdir=shift; # directory to put file in
260 while (length $test) {
261 if (-l "$destdir/$test") {
262 error("cannot write to a symlink ($test)");
264 $test=dirname($test);
267 my $dir=dirname("$destdir/$file");
270 foreach my $s (split(m!/+!, $dir)) {
273 mkdir($d) || error("failed to create directory $d: $!");
278 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
279 binmode(OUT) if ($binary);
280 return \*OUT if $wantfd;
286 sub will_render ($$;$) { #{{{
291 # Important security check.
292 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
293 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
294 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
297 if (! $clear || $cleared{$page}) {
298 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
301 $renderedfiles{$page}=[$dest];
306 sub bestlink ($$) { #{{{
311 if ($link=~s/^\/+//) {
318 $l.="/" if length $l;
321 if (exists $links{$l}) {
324 elsif (exists $pagecase{lc $l}) {
325 return $pagecase{lc $l};
327 } while $cwd=~s!/?[^/]+$!!;
329 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
330 return "$config{userdir}/".lc($link);
333 #print STDERR "warning: page $page, broken link: $link\n";
337 sub isinlinableimage ($) { #{{{
340 $file=~/\.(png|gif|jpg|jpeg)$/i;
343 sub pagetitle ($;$) { #{{{
348 $page=~s/__(\d+)__/chr($1)/eg;
351 $page=~s/__(\d+)__/&#$1;/g;
358 sub titlepage ($) { #{{{
361 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
365 sub cgiurl (@) { #{{{
368 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
371 sub baseurl (;$) { #{{{
374 return "$config{url}/" if ! defined $page;
377 $page=~s/[^\/]+\//..\//g;
381 sub abs2rel ($$) { #{{{
382 # Work around very innefficient behavior in File::Spec if abs2rel
383 # is passed two relative paths. It's much faster if paths are
384 # absolute! (Debian bug #376658; fixed in debian unstable now)
389 my $ret=File::Spec->abs2rel($path, $base);
390 $ret=~s/^// if defined $ret;
394 sub displaytime ($) { #{{{
399 # strftime doesn't know about encodings, so make sure
400 # its output is properly treated as utf8
401 return decode_utf8(POSIX::strftime(
402 $config{timeformat}, localtime($time)));
405 sub htmllink ($$$;$$$) { #{{{
406 my $lpage=shift; # the page doing the linking
407 my $page=shift; # the page that will contain the link (different for inline)
409 my $noimageinline=shift; # don't turn links into inline html images
410 my $forcesubpage=shift; # force a link to a subpage
411 my $linktext=shift; # set to force the link text to something
414 if (! $forcesubpage) {
415 $bestlink=bestlink($lpage, $link);
418 $bestlink="$lpage/".lc($link);
421 $linktext=pagetitle(basename($link)) unless defined $linktext;
423 return "<span class=\"selflink\">$linktext</span>"
424 if length $bestlink && $page eq $bestlink;
426 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
427 $bestlink=htmlpage($bestlink);
429 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
430 return $linktext unless length $config{cgiurl};
431 return "<span><a href=\"".
432 cgiurl(do => "create", page => lc($link), from => $page).
433 "\">?</a>$linktext</span>"
436 $bestlink=abs2rel($bestlink, dirname($page));
438 if (! $noimageinline && isinlinableimage($bestlink)) {
439 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
441 return "<a href=\"$bestlink\">$linktext</a>";
444 sub htmlize ($$$) { #{{{
449 if (exists $hooks{htmlize}{$type}) {
450 $content=$hooks{htmlize}{$type}{call}->(
456 error("htmlization of $type not supported");
459 run_hooks(sanitize => sub {
469 sub linkify ($$$) { #{{{
470 my $lpage=shift; # the page containing the links
471 my $page=shift; # the page the link will end up on (different for inline)
474 $content =~ s{(\\?)$config{wiki_link_regexp}}{
475 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
476 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
483 sub preprocess ($$$;$) { #{{{
484 my $page=shift; # the page the data comes from
485 my $destpage=shift; # the page the data will appear in (different for inline)
493 if (length $escape) {
494 return "[[$command $params]]";
496 elsif (exists $hooks{preprocess}{$command}) {
497 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
498 # Note: preserve order of params, some plugins may
499 # consider it significant.
501 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
518 push @params, $key, $val;
521 push @params, $val, '';
524 if ($preprocessing{$page}++ > 3) {
525 # Avoid loops of preprocessed pages preprocessing
526 # other pages that preprocess them, etc.
527 #translators: The first parameter is a
528 #translators: preprocessor directive name,
529 #translators: the second a page name, the
530 #translators: third a number.
531 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
532 $command, $page, $preprocessing{$page}).
535 my $ret=$hooks{preprocess}{$command}{call}->(
538 destpage => $destpage,
540 $preprocessing{$page}--;
544 return "[[$command $params]]";
548 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
552 sub filter ($$) { #{{{
556 run_hooks(filter => sub {
557 $content=shift->(page => $page, content => $content);
563 sub indexlink () { #{{{
564 return "<a href=\"$config{url}\">$config{wikiname}</a>";
567 sub lockwiki () { #{{{
568 # Take an exclusive lock on the wiki to prevent multiple concurrent
569 # run issues. The lock will be dropped on program exit.
570 if (! -d $config{wikistatedir}) {
571 mkdir($config{wikistatedir});
573 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
574 error ("cannot write to $config{wikistatedir}/lockfile: $!");
575 if (! flock(WIKILOCK, 2 | 4)) {
576 debug("wiki seems to be locked, waiting for lock");
577 my $wait=600; # arbitrary, but don't hang forever to
578 # prevent process pileup
580 return if flock(WIKILOCK, 2 | 4);
583 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
587 sub unlockwiki () { #{{{
591 sub loadindex () { #{{{
592 open (IN, "$config{wikistatedir}/index") || return;
594 $_=possibly_foolish_untaint($_);
599 foreach my $i (split(/ /, $_)) {
600 my ($item, $val)=split(/=/, $i, 2);
601 push @{$items{$item}}, decode_entities($val);
604 next unless exists $items{src}; # skip bad lines for now
606 my $page=pagename($items{src}[0]);
607 if (! $config{rebuild}) {
608 $pagesources{$page}=$items{src}[0];
609 $oldpagemtime{$page}=$items{mtime}[0];
610 $oldlinks{$page}=[@{$items{link}}];
611 $links{$page}=[@{$items{link}}];
612 $depends{$page}=$items{depends}[0] if exists $items{depends};
613 $renderedfiles{$page}=[@{$items{dest}}];
614 $oldrenderedfiles{$page}=[@{$items{dest}}];
615 $pagecase{lc $page}=$page;
617 $pagectime{$page}=$items{ctime}[0];
622 sub saveindex () { #{{{
623 run_hooks(savestate => sub { shift->() });
625 if (! -d $config{wikistatedir}) {
626 mkdir($config{wikistatedir});
628 open (OUT, ">$config{wikistatedir}/index") ||
629 error("cannot write to $config{wikistatedir}/index: $!");
630 foreach my $page (keys %oldpagemtime) {
631 next unless $oldpagemtime{$page};
632 my $line="mtime=$oldpagemtime{$page} ".
633 "ctime=$pagectime{$page} ".
634 "src=$pagesources{$page}";
635 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
637 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
638 if (exists $depends{$page}) {
639 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
641 print OUT $line."\n";
646 sub template_file ($) { #{{{
649 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
650 return "$dir/$template" if -e "$dir/$template";
655 sub template_params (@) { #{{{
656 my $filename=template_file(shift);
658 if (! defined $filename) {
663 require HTML::Template;
666 my $text_ref = shift;
667 $$text_ref=&Encode::decode_utf8($$text_ref);
669 filename => $filename,
670 loop_context_vars => 1,
671 die_on_bad_params => 0,
674 return wantarray ? @ret : {@ret};
677 sub template ($;@) { #{{{
678 HTML::Template->new(template_params(@_));
681 sub misctemplate ($$;@) { #{{{
685 my $template=template("misc.tmpl");
688 indexlink => indexlink(),
689 wikiname => $config{wikiname},
690 pagebody => $pagebody,
691 baseurl => baseurl(),
694 run_hooks(pagetemplate => sub {
695 shift->(page => "", destpage => "", template => $template);
697 return $template->output;
703 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
704 error "hook requires type, call, and id parameters";
707 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
709 $hooks{$param{type}}{$param{id}}=\%param;
712 sub run_hooks ($$) { # {{{
713 # Calls the given sub for each hook of the given type,
714 # passing it the hook function to call.
718 if (exists $hooks{$type}) {
720 foreach my $id (keys %{$hooks{$type}}) {
721 if ($hooks{$type}{$id}{last}) {
725 $sub->($hooks{$type}{$id}{call});
727 foreach my $id (@deferred) {
728 $sub->($hooks{$type}{$id}{call});
733 sub globlist_to_pagespec ($) { #{{{
734 my @globlist=split(' ', shift);
737 foreach my $glob (@globlist) {
738 if ($glob=~/^!(.*)/) {
746 my $spec=join(" or ", @spec);
748 my $skip=join(" and ", @skip);
750 $spec="$skip and ($spec)";
759 sub is_globlist ($) { #{{{
761 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
764 sub safequote ($) { #{{{
770 sub add_depends ($$) { #{{{
774 if (! exists $depends{$page}) {
775 $depends{$page}=$pagespec;
778 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
782 sub file_pruned ($$) { #{{{
784 my $file=File::Spec->canonpath(shift);
785 my $base=File::Spec->canonpath(shift);
786 $file=~s#^\Q$base\E/*##;
788 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
793 # Only use gettext in the rare cases it's needed.
794 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
795 if (! $gettext_obj) {
797 use Locale::gettext q{textdomain};
798 Locale::gettext->domain('ikiwiki')
806 return $gettext_obj->get(shift);
813 sub pagespec_merge ($$) { #{{{
817 return $a if $a eq $b;
819 # Support for old-style GlobLists.
820 if (is_globlist($a)) {
821 $a=globlist_to_pagespec($a);
823 if (is_globlist($b)) {
824 $b=globlist_to_pagespec($b);
827 return "($a) or ($b)";
830 sub pagespec_translate ($) { #{{{
831 # This assumes that $page is in scope in the function
832 # that evalulates the translated pagespec code.
835 # Support for old-style GlobLists.
836 if (is_globlist($spec)) {
837 $spec=globlist_to_pagespec($spec);
840 # Convert spec to perl code.
842 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
844 if (lc $word eq "and") {
847 elsif (lc $word eq "or") {
850 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
853 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
854 $code.=" match_$1(\$page, ".safequote($2).")";
857 $code.=" match_glob(\$page, ".safequote($word).", \$from)";
864 sub pagespec_match ($$;$) { #{{{
868 if (! defined $from){
872 return eval pagespec_translate($spec);
875 sub match_glob ($$$) { #{{{
881 if ($glob =~ m!^\./!) {
884 $glob="$from/$glob" if length $from;
887 # turn glob into safe regexp
888 $glob=quotemeta($glob);
892 return $page=~/^$glob$/i;
895 sub match_link ($$) { #{{{
899 my $links = $links{$page} or return undef;
900 foreach my $p (@$links) {
901 return 1 if lc $p eq $link;
906 sub match_backlink ($$) { #{{{
907 match_link(pop, pop);
910 sub match_created_before ($$) { #{{{
914 if (exists $pagectime{$testpage}) {
915 return $pagectime{$page} < $pagectime{$testpage};
922 sub match_created_after ($$) { #{{{
926 if (exists $pagectime{$testpage}) {
927 return $pagectime{$page} > $pagectime{$testpage};
934 sub match_creation_day ($$) { #{{{
935 return ((gmtime($pagectime{shift()}))[3] == shift);
938 sub match_creation_month ($$) { #{{{
939 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
942 sub match_creation_year ($$) { #{{{
943 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);