8 use open qw{:utf8 :std};
10 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
11 %renderedfiles %oldrenderedfiles %pagesources %depends %hooks
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
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",
62 templatedir => "$installdir/share/ikiwiki/templates",
63 underlaydir => "$installdir/share/ikiwiki/basewiki",
67 plugin => [qw{mdwn inline htmlscrubber passwordauth}],
75 sub checkconfig () { #{{{
76 # locale stuff; avoid LC_ALL since it overrides everything
77 if (defined $ENV{LC_ALL}) {
78 $ENV{LANG} = $ENV{LC_ALL};
81 if (defined $config{locale}) {
84 $ENV{LANG} = $config{locale}
85 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
88 if ($config{w3mmode}) {
89 eval q{use Cwd q{abs_path}};
91 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
92 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
93 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
94 unless $config{cgiurl} =~ m!file:///!;
95 $config{url}="file://".$config{destdir};
98 if ($config{cgi} && ! length $config{url}) {
99 error("Must specify url to wiki with --url when using --cgi\n");
102 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
103 unless exists $config{wikistatedir};
106 eval qq{require IkiWiki::Rcs::$config{rcs}};
108 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
112 require IkiWiki::Rcs::Stub;
115 run_hooks(checkconfig => sub { shift->() });
118 sub loadplugins () { #{{{
119 loadplugin($_) foreach @{$config{plugin}};
121 run_hooks(getopt => sub { shift->() });
122 if (grep /^-/, @ARGV) {
123 print STDERR "Unknown option: $_\n"
124 foreach grep /^-/, @ARGV;
129 sub loadplugin ($) { #{{{
132 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
135 error("Failed to load plugin $mod: $@");
141 print "Content-type: text/html\n\n";
142 print misctemplate("Error", "<p>Error: @_</p>");
144 log_message(error => @_);
149 return unless $config{verbose};
150 log_message(debug => @_);
154 sub log_message ($$) { #{{{
157 if ($config{syslog}) {
160 Sys::Syslog::setlogsock('unix');
161 Sys::Syslog::openlog('ikiwiki', '', 'user');
165 Sys::Syslog::syslog($type, join(" ", @_));
168 elsif (! $config{cgi}) {
176 sub possibly_foolish_untaint ($) { #{{{
178 my ($untainted)=$tainted=~/(.*)/;
182 sub basename ($) { #{{{
189 sub dirname ($) { #{{{
196 sub pagetype ($) { #{{{
199 if ($page =~ /\.([^.]+)$/) {
200 return $1 if exists $hooks{htmlize}{$1};
205 sub pagename ($) { #{{{
208 my $type=pagetype($file);
210 $page=~s/\Q.$type\E*$// if defined $type;
214 sub htmlpage ($) { #{{{
217 return $page.".html";
220 sub srcfile ($) { #{{{
223 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
224 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
225 error("internal error: $file cannot be found");
228 sub readfile ($;$) { #{{{
233 error("cannot read a symlink ($file)");
237 open (IN, $file) || error("failed to read $file: $!");
238 binmode(IN) if ($binary);
244 sub writefile ($$$;$) { #{{{
245 my $file=shift; # can include subdirs
246 my $destdir=shift; # directory to put file in
251 while (length $test) {
252 if (-l "$destdir/$test") {
253 error("cannot write to a symlink ($test)");
255 $test=dirname($test);
258 my $dir=dirname("$destdir/$file");
261 foreach my $s (split(m!/+!, $dir)) {
264 mkdir($d) || error("failed to create directory $d: $!");
269 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
270 binmode(OUT) if ($binary);
276 sub will_render ($$;$) { #{{{
281 # Important security check.
282 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
283 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
284 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
287 if (! $clear || $cleared{$page}) {
288 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
291 $renderedfiles{$page}=[$dest];
296 sub bestlink ($$) { #{{{
303 while ($link=~s!(^|/)\.\./!!g) {
309 $l.="/" if length $l;
312 if (exists $links{$l}) {
315 elsif (exists $pagecase{lc $l}) {
316 return $pagecase{lc $l};
318 } while $cwd=~s!/?[^/]+$!!;
320 #print STDERR "warning: page $page, broken link: $link\n";
324 sub isinlinableimage ($) { #{{{
327 $file=~/\.(png|gif|jpg|jpeg)$/i;
330 sub pagetitle ($) { #{{{
332 $page=~s/__(\d+)__/&#$1;/g;
337 sub titlepage ($) { #{{{
340 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
344 sub cgiurl (@) { #{{{
347 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
350 sub baseurl (;$) { #{{{
353 return "$config{url}/" if ! defined $page;
356 $page=~s/[^\/]+\//..\//g;
360 sub abs2rel ($$) { #{{{
361 # Work around very innefficient behavior in File::Spec if abs2rel
362 # is passed two relative paths. It's much faster if paths are
363 # absolute! (Debian bug #376658; fixed in debian unstable now)
368 my $ret=File::Spec->abs2rel($path, $base);
369 $ret=~s/^// if defined $ret;
373 sub displaytime ($) { #{{{
378 # strftime doesn't know about encodings, so make sure
379 # its output is properly treated as utf8
380 return decode_utf8(POSIX::strftime(
381 $config{timeformat}, localtime($time)));
384 sub htmllink ($$$;$$$) { #{{{
385 my $lpage=shift; # the page doing the linking
386 my $page=shift; # the page that will contain the link (different for inline)
388 my $noimageinline=shift; # don't turn links into inline html images
389 my $forcesubpage=shift; # force a link to a subpage
390 my $linktext=shift; # set to force the link text to something
393 if (! $forcesubpage) {
394 $bestlink=bestlink($lpage, $link);
397 $bestlink="$lpage/".lc($link);
400 $linktext=pagetitle(basename($link)) unless defined $linktext;
402 return "<span class=\"selflink\">$linktext</span>"
403 if length $bestlink && $page eq $bestlink;
405 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
406 $bestlink=htmlpage($bestlink);
408 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
409 return "<span><a href=\"".
410 cgiurl(do => "create", page => lc($link), from => $page).
411 "\">?</a>$linktext</span>"
414 $bestlink=abs2rel($bestlink, dirname($page));
416 if (! $noimageinline && isinlinableimage($bestlink)) {
417 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
419 return "<a href=\"$bestlink\">$linktext</a>";
422 sub htmlize ($$$) { #{{{
427 if (exists $hooks{htmlize}{$type}) {
428 $content=$hooks{htmlize}{$type}{call}->(
434 error("htmlization of $type not supported");
437 run_hooks(sanitize => sub {
447 sub linkify ($$$) { #{{{
448 my $lpage=shift; # the page containing the links
449 my $page=shift; # the page the link will end up on (different for inline)
452 $content =~ s{(\\?)$config{wiki_link_regexp}}{
453 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
454 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
461 sub preprocess ($$$;$) { #{{{
462 my $page=shift; # the page the data comes from
463 my $destpage=shift; # the page the data will appear in (different for inline)
471 if (length $escape) {
472 return "[[$command $params]]";
474 elsif (exists $hooks{preprocess}{$command}) {
475 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
476 # Note: preserve order of params, some plugins may
477 # consider it significant.
479 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
496 push @params, $key, $val;
499 push @params, $val, '';
502 if ($preprocessing{$page}++ > 3) {
503 # Avoid loops of preprocessed pages preprocessing
504 # other pages that preprocess them, etc.
505 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
507 my $ret=$hooks{preprocess}{$command}{call}->(
510 destpage => $destpage,
512 $preprocessing{$page}--;
516 return "[[$command $params]]";
520 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
524 sub filter ($$) { #{{{
528 run_hooks(filter => sub {
529 $content=shift->(page => $page, content => $content);
535 sub indexlink () { #{{{
536 return "<a href=\"$config{url}\">$config{wikiname}</a>";
539 sub lockwiki () { #{{{
540 # Take an exclusive lock on the wiki to prevent multiple concurrent
541 # run issues. The lock will be dropped on program exit.
542 if (! -d $config{wikistatedir}) {
543 mkdir($config{wikistatedir});
545 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
546 error ("cannot write to $config{wikistatedir}/lockfile: $!");
547 if (! flock(WIKILOCK, 2 | 4)) {
548 debug("wiki seems to be locked, waiting for lock");
549 my $wait=600; # arbitrary, but don't hang forever to
550 # prevent process pileup
552 return if flock(WIKILOCK, 2 | 4);
555 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
559 sub unlockwiki () { #{{{
563 sub loadindex () { #{{{
564 open (IN, "$config{wikistatedir}/index") || return;
566 $_=possibly_foolish_untaint($_);
571 foreach my $i (split(/ /, $_)) {
572 my ($item, $val)=split(/=/, $i, 2);
573 push @{$items{$item}}, decode_entities($val);
576 next unless exists $items{src}; # skip bad lines for now
578 my $page=pagename($items{src}[0]);
579 if (! $config{rebuild}) {
580 $pagesources{$page}=$items{src}[0];
581 $oldpagemtime{$page}=$items{mtime}[0];
582 $oldlinks{$page}=[@{$items{link}}];
583 $links{$page}=[@{$items{link}}];
584 $depends{$page}=$items{depends}[0] if exists $items{depends};
585 $renderedfiles{$page}=[@{$items{dest}}];
586 $oldrenderedfiles{$page}=[@{$items{dest}}];
587 $pagecase{lc $page}=$page;
589 $pagectime{$page}=$items{ctime}[0];
594 sub saveindex () { #{{{
595 run_hooks(savestate => sub { shift->() });
597 if (! -d $config{wikistatedir}) {
598 mkdir($config{wikistatedir});
600 open (OUT, ">$config{wikistatedir}/index") ||
601 error("cannot write to $config{wikistatedir}/index: $!");
602 foreach my $page (keys %oldpagemtime) {
603 next unless $oldpagemtime{$page};
604 my $line="mtime=$oldpagemtime{$page} ".
605 "ctime=$pagectime{$page} ".
606 "src=$pagesources{$page}";
607 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
609 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
610 if (exists $depends{$page}) {
611 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
613 print OUT $line."\n";
618 sub template_params (@) { #{{{
621 require HTML::Template;
622 return filter => sub {
623 my $text_ref = shift;
624 $$text_ref=&Encode::decode_utf8($$text_ref);
626 filename => "$config{templatedir}/$filename",
627 loop_context_vars => 1,
628 die_on_bad_params => 0,
632 sub template ($;@) { #{{{
633 HTML::Template->new(template_params(@_));
636 sub misctemplate ($$;@) { #{{{
640 my $template=template("misc.tmpl");
643 indexlink => indexlink(),
644 wikiname => $config{wikiname},
645 pagebody => $pagebody,
646 baseurl => baseurl(),
649 run_hooks(pagetemplate => sub {
650 shift->(page => "", destpage => "", template => $template);
652 return $template->output;
658 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
659 error "hook requires type, call, and id parameters";
662 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
664 $hooks{$param{type}}{$param{id}}=\%param;
667 sub run_hooks ($$) { # {{{
668 # Calls the given sub for each hook of the given type,
669 # passing it the hook function to call.
673 if (exists $hooks{$type}) {
675 foreach my $id (keys %{$hooks{$type}}) {
676 if ($hooks{$type}{$id}{last}) {
680 $sub->($hooks{$type}{$id}{call});
682 foreach my $id (@deferred) {
683 $sub->($hooks{$type}{$id}{call});
688 sub globlist_to_pagespec ($) { #{{{
689 my @globlist=split(' ', shift);
692 foreach my $glob (@globlist) {
693 if ($glob=~/^!(.*)/) {
701 my $spec=join(" or ", @spec);
703 my $skip=join(" and ", @skip);
705 $spec="$skip and ($spec)";
714 sub is_globlist ($) { #{{{
716 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
719 sub safequote ($) { #{{{
725 sub pagespec_merge ($$) { #{{{
729 return $a if $a eq $b;
731 # Support for old-style GlobLists.
732 if (is_globlist($a)) {
733 $a=globlist_to_pagespec($a);
735 if (is_globlist($b)) {
736 $b=globlist_to_pagespec($b);
739 return "($a) or ($b)";
742 sub pagespec_translate ($) { #{{{
743 # This assumes that $page is in scope in the function
744 # that evalulates the translated pagespec code.
747 # Support for old-style GlobLists.
748 if (is_globlist($spec)) {
749 $spec=globlist_to_pagespec($spec);
752 # Convert spec to perl code.
754 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
756 if (lc $word eq "and") {
759 elsif (lc $word eq "or") {
762 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
765 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
766 $code.=" match_$1(\$page, ".safequote($2).")";
769 $code.=" match_glob(\$page, ".safequote($word).")";
776 sub add_depends ($$) { #{{{
780 if (! exists $depends{$page}) {
781 $depends{$page}=$pagespec;
784 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
788 sub file_pruned ($$) { #{{{
790 my $file=File::Spec->canonpath(shift);
791 my $base=File::Spec->canonpath(shift);
792 $file=~s#^\Q$base\E/*##;
794 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
798 sub pagespec_match ($$) { #{{{
802 return eval pagespec_translate($spec);
805 sub match_glob ($$) { #{{{
809 # turn glob into safe regexp
810 $glob=quotemeta($glob);
814 return $page=~/^$glob$/i;
817 sub match_link ($$) { #{{{
821 my $links = $links{$page} or return undef;
822 foreach my $p (@$links) {
823 return 1 if lc $p eq $link;
828 sub match_backlink ($$) { #{{{
829 match_link(pop, pop);
832 sub match_created_before ($$) { #{{{
836 if (exists $pagectime{$testpage}) {
837 return $pagectime{$page} < $pagectime{$testpage};
844 sub match_created_after ($$) { #{{{
848 if (exists $pagectime{$testpage}) {
849 return $pagectime{$page} > $pagectime{$testpage};
856 sub match_creation_day ($$) { #{{{
857 return ((gmtime($pagectime{shift()}))[3] == shift);
860 sub match_creation_month ($$) { #{{{
861 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
864 sub match_creation_year ($$) { #{{{
865 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);