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");
26 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
27 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 sub defaultconfig () { #{{{
30 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$|\.atom$|.arch-ids/|{arch}/)},
31 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
32 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
36 default_pageext => "mdwn",
59 templatedir => "$installdir/share/ikiwiki/templates",
60 underlaydir => "$installdir/share/ikiwiki/basewiki",
64 plugin => [qw{mdwn inline htmlscrubber}],
71 sub checkconfig () { #{{{
72 # locale stuff; avoid LC_ALL since it overrides everything
73 if (defined $ENV{LC_ALL}) {
74 $ENV{LANG} = $ENV{LC_ALL};
77 if (defined $config{locale}) {
79 $ENV{LANG} = $config{locale}
80 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
83 if ($config{w3mmode}) {
84 eval q{use Cwd q{abs_path}};
85 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
86 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
87 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
88 unless $config{cgiurl} =~ m!file:///!;
89 $config{url}="file://".$config{destdir};
92 if ($config{cgi} && ! length $config{url}) {
93 error("Must specify url to wiki with --url when using --cgi\n");
95 if (($config{rss} || $config{atom}) && ! length $config{url}) {
96 error("Must specify url to wiki with --url when using --rss or --atom\n");
99 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
100 unless exists $config{wikistatedir};
103 eval qq{require IkiWiki::Rcs::$config{rcs}};
105 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
109 require IkiWiki::Rcs::Stub;
112 run_hooks(checkconfig => sub { shift->() });
115 sub loadplugins () { #{{{
116 foreach my $plugin (@{$config{plugin}}) {
117 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
120 error("Failed to load plugin $mod: $@");
123 run_hooks(getopt => sub { shift->() });
124 if (grep /^-/, @ARGV) {
125 print STDERR "Unknown option: $_\n"
126 foreach grep /^-/, @ARGV;
133 print "Content-type: text/html\n\n";
134 print misctemplate("Error", "<p>Error: @_</p>");
136 log_message(error => @_);
141 return unless $config{verbose};
142 log_message(debug => @_);
146 sub log_message ($$) { #{{{
149 if ($config{syslog}) {
152 Sys::Syslog::setlogsock('unix');
153 Sys::Syslog::openlog('ikiwiki', '', 'user');
157 Sys::Syslog::syslog($type, join(" ", @_));
160 elsif (! $config{cgi}) {
168 sub possibly_foolish_untaint ($) { #{{{
170 my ($untainted)=$tainted=~/(.*)/;
174 sub basename ($) { #{{{
181 sub dirname ($) { #{{{
188 sub pagetype ($) { #{{{
191 if ($page =~ /\.([^.]+)$/) {
192 return $1 if exists $hooks{htmlize}{$1};
197 sub pagename ($) { #{{{
200 my $type=pagetype($file);
202 $page=~s/\Q.$type\E*$// if defined $type;
206 sub htmlpage ($) { #{{{
209 return $page.".html";
212 sub srcfile ($) { #{{{
215 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
216 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
217 error("internal error: $file cannot be found");
220 sub readfile ($;$) { #{{{
225 error("cannot read a symlink ($file)");
229 open (IN, $file) || error("failed to read $file: $!");
230 binmode(IN) if ($binary);
236 sub writefile ($$$;$) { #{{{
237 my $file=shift; # can include subdirs
238 my $destdir=shift; # directory to put file in
243 while (length $test) {
244 if (-l "$destdir/$test") {
245 error("cannot write to a symlink ($test)");
247 $test=dirname($test);
250 my $dir=dirname("$destdir/$file");
253 foreach my $s (split(m!/+!, $dir)) {
256 mkdir($d) || error("failed to create directory $d: $!");
261 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
262 binmode(OUT) if ($binary);
268 sub will_render ($$;$) { #{{{
273 # Important security check.
274 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
275 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
276 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
279 if (! $clear || $cleared{$page}) {
280 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
283 $renderedfiles{$page}=[$dest];
288 sub bestlink ($$) { #{{{
295 $l.="/" if length $l;
298 if (exists $links{$l}) {
301 elsif (exists $pagecase{lc $l}) {
302 return $pagecase{lc $l};
304 } while $cwd=~s!/?[^/]+$!!;
306 #print STDERR "warning: page $page, broken link: $link\n";
310 sub isinlinableimage ($) { #{{{
313 $file=~/\.(png|gif|jpg|jpeg)$/i;
316 sub pagetitle ($) { #{{{
318 $page=~s/__(\d+)__/&#$1;/g;
323 sub titlepage ($) { #{{{
326 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
330 sub cgiurl (@) { #{{{
333 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
336 sub baseurl (;$) { #{{{
339 return "$config{url}/" if ! defined $page;
342 $page=~s/[^\/]+\//..\//g;
346 sub abs2rel ($$) { #{{{
347 # Work around very innefficient behavior in File::Spec if abs2rel
348 # is passed two relative paths. It's much faster if paths are
349 # absolute! (Debian bug #376658)
354 my $ret=File::Spec->abs2rel($path, $base);
355 $ret=~s/^// if defined $ret;
359 sub displaytime ($) { #{{{
363 # strftime doesn't know about encodings, so make sure
364 # its output is properly treated as utf8
365 return decode_utf8(POSIX::strftime(
366 $config{timeformat}, localtime($time)));
369 sub htmllink ($$$;$$$) { #{{{
370 my $lpage=shift; # the page doing the linking
371 my $page=shift; # the page that will contain the link (different for inline)
373 my $noimageinline=shift; # don't turn links into inline html images
374 my $forcesubpage=shift; # force a link to a subpage
375 my $linktext=shift; # set to force the link text to something
378 if (! $forcesubpage) {
379 $bestlink=bestlink($lpage, $link);
382 $bestlink="$lpage/".lc($link);
385 $linktext=pagetitle(basename($link)) unless defined $linktext;
387 return "<span class=\"selflink\">$linktext</span>"
388 if length $bestlink && $page eq $bestlink;
390 # TODO BUG: %renderedfiles may not have it, if the linked to page
391 # was also added and isn't yet rendered! Note that this bug is
392 # masked by the bug that makes all new files be rendered twice.
393 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
394 $bestlink=htmlpage($bestlink);
396 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
397 return "<span><a href=\"".
398 cgiurl(do => "create", page => lc($link), from => $page).
399 "\">?</a>$linktext</span>"
402 $bestlink=abs2rel($bestlink, dirname($page));
404 if (! $noimageinline && isinlinableimage($bestlink)) {
405 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
407 return "<a href=\"$bestlink\">$linktext</a>";
410 sub htmlize ($$$) { #{{{
415 if (exists $hooks{htmlize}{$type}) {
416 $content=$hooks{htmlize}{$type}{call}->(
422 error("htmlization of $type not supported");
425 run_hooks(sanitize => sub {
435 sub linkify ($$$) { #{{{
436 my $lpage=shift; # the page containing the links
437 my $page=shift; # the page the link will end up on (different for inline)
440 $content =~ s{(\\?)$config{wiki_link_regexp}}{
441 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
442 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
449 sub preprocess ($$$) { #{{{
450 my $page=shift; # the page the data comes from
451 my $destpage=shift; # the page the data will appear in (different for inline)
458 if (length $escape) {
459 return "[[$command $params]]";
461 elsif (exists $hooks{preprocess}{$command}) {
462 # Note: preserve order of params, some plugins may
463 # consider it significant.
465 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
482 push @params, $key, $val;
485 push @params, $val, '';
488 if ($preprocessing{$page}++ > 3) {
489 # Avoid loops of preprocessed pages preprocessing
490 # other pages that preprocess them, etc.
491 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
493 my $ret=$hooks{preprocess}{$command}{call}->(
496 destpage => $destpage,
498 $preprocessing{$page}--;
502 return "[[$command $params]]";
506 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
514 run_hooks(filter => sub {
515 $content=shift->(page => $page, content => $content);
521 sub indexlink () { #{{{
522 return "<a href=\"$config{url}\">$config{wikiname}</a>";
525 sub lockwiki () { #{{{
526 # Take an exclusive lock on the wiki to prevent multiple concurrent
527 # run issues. The lock will be dropped on program exit.
528 if (! -d $config{wikistatedir}) {
529 mkdir($config{wikistatedir});
531 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
532 error ("cannot write to $config{wikistatedir}/lockfile: $!");
533 if (! flock(WIKILOCK, 2 | 4)) {
534 debug("wiki seems to be locked, waiting for lock");
535 my $wait=600; # arbitrary, but don't hang forever to
536 # prevent process pileup
538 return if flock(WIKILOCK, 2 | 4);
541 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
545 sub unlockwiki () { #{{{
549 sub loadindex () { #{{{
550 open (IN, "$config{wikistatedir}/index") || return;
552 $_=possibly_foolish_untaint($_);
557 foreach my $i (split(/ /, $_)) {
558 my ($item, $val)=split(/=/, $i, 2);
559 push @{$items{$item}}, decode_entities($val);
562 next unless exists $items{src}; # skip bad lines for now
564 my $page=pagename($items{src}[0]);
565 if (! $config{rebuild}) {
566 $pagesources{$page}=$items{src}[0];
567 $oldpagemtime{$page}=$items{mtime}[0];
568 $oldlinks{$page}=[@{$items{link}}];
569 $links{$page}=[@{$items{link}}];
570 $depends{$page}=$items{depends}[0] if exists $items{depends};
571 $renderedfiles{$page}=[@{$items{dest}}];
572 $oldrenderedfiles{$page}=[@{$items{dest}}];
573 $pagecase{lc $page}=$page;
575 $pagectime{$page}=$items{ctime}[0];
580 sub saveindex () { #{{{
581 run_hooks(savestate => sub { shift->() });
583 if (! -d $config{wikistatedir}) {
584 mkdir($config{wikistatedir});
586 open (OUT, ">$config{wikistatedir}/index") ||
587 error("cannot write to $config{wikistatedir}/index: $!");
588 foreach my $page (keys %oldpagemtime) {
589 next unless $oldpagemtime{$page};
590 my $line="mtime=$oldpagemtime{$page} ".
591 "ctime=$pagectime{$page} ".
592 "src=$pagesources{$page}";
593 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
594 $line.=" link=$_" foreach @{$links{$page}};
595 if (exists $depends{$page}) {
596 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
598 print OUT $line."\n";
603 sub template_params (@) { #{{{
606 require HTML::Template;
607 return filter => sub {
608 my $text_ref = shift;
609 $$text_ref=&Encode::decode_utf8($$text_ref);
611 filename => "$config{templatedir}/$filename",
612 loop_context_vars => 1,
613 die_on_bad_params => 0,
617 sub template ($;@) { #{{{
618 HTML::Template->new(template_params(@_));
621 sub misctemplate ($$;@) { #{{{
625 my $template=template("misc.tmpl");
628 indexlink => indexlink(),
629 wikiname => $config{wikiname},
630 pagebody => $pagebody,
631 baseurl => baseurl(),
634 run_hooks(pagetemplate => sub {
635 shift->(page => "", destpage => "", template => $template);
637 return $template->output;
643 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
644 error "hook requires type, call, and id parameters";
647 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
649 $hooks{$param{type}}{$param{id}}=\%param;
652 sub run_hooks ($$) { # {{{
653 # Calls the given sub for each hook of the given type,
654 # passing it the hook function to call.
658 if (exists $hooks{$type}) {
659 foreach my $id (keys %{$hooks{$type}}) {
660 $sub->($hooks{$type}{$id}{call});
665 sub globlist_to_pagespec ($) { #{{{
666 my @globlist=split(' ', shift);
669 foreach my $glob (@globlist) {
670 if ($glob=~/^!(.*)/) {
678 my $spec=join(" or ", @spec);
680 my $skip=join(" and ", @skip);
682 $spec="$skip and ($spec)";
691 sub is_globlist ($) { #{{{
693 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
696 sub safequote ($) { #{{{
702 sub pagespec_merge ($$) { #{{{
706 return $a if $a eq $b;
708 # Support for old-style GlobLists.
709 if (is_globlist($a)) {
710 $a=globlist_to_pagespec($a);
712 if (is_globlist($b)) {
713 $b=globlist_to_pagespec($b);
716 return "($a) or ($b)";
719 sub pagespec_translate ($) { #{{{
720 # This assumes that $page is in scope in the function
721 # that evalulates the translated pagespec code.
724 # Support for old-style GlobLists.
725 if (is_globlist($spec)) {
726 $spec=globlist_to_pagespec($spec);
729 # Convert spec to perl code.
731 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
733 if (lc $word eq "and") {
736 elsif (lc $word eq "or") {
739 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
742 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
743 $code.=" match_$1(\$page, ".safequote($2).")";
746 $code.=" match_glob(\$page, ".safequote($word).")";
753 sub add_depends ($$) { #{{{
757 if (! exists $depends{$page}) {
758 $depends{$page}=$pagespec;
761 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
765 sub pagespec_match ($$) { #{{{
769 return eval pagespec_translate($spec);
772 sub match_glob ($$) { #{{{
776 # turn glob into safe regexp
777 $glob=quotemeta($glob);
781 return $page=~/^$glob$/i;
784 sub match_link ($$) { #{{{
788 my $links = $links{$page} or return undef;
789 foreach my $p (@$links) {
790 return 1 if lc $p eq $link;
795 sub match_backlink ($$) { #{{{
796 match_link(pop, pop);
799 sub match_created_before ($$) { #{{{
803 if (exists $pagectime{$testpage}) {
804 return $pagectime{$page} < $pagectime{$testpage};
811 sub match_created_after ($$) { #{{{
815 if (exists $pagectime{$testpage}) {
816 return $pagectime{$page} > $pagectime{$testpage};
823 sub match_creation_day ($$) { #{{{
824 return ((gmtime($pagectime{shift()}))[3] == shift);
827 sub match_creation_month ($$) { #{{{
828 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
831 sub match_creation_year ($$) { #{{{
832 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);