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)
459 if (length $escape) {
460 return "[[$command $params]]";
462 elsif (exists $hooks{preprocess}{$command}) {
463 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
464 # Note: preserve order of params, some plugins may
465 # consider it significant.
467 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
484 push @params, $key, $val;
487 push @params, $val, '';
490 if ($preprocessing{$page}++ > 3) {
491 # Avoid loops of preprocessed pages preprocessing
492 # other pages that preprocess them, etc.
493 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
495 my $ret=$hooks{preprocess}{$command}{call}->(
498 destpage => $destpage,
500 $preprocessing{$page}--;
504 return "[[$command $params]]";
508 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
516 run_hooks(filter => sub {
517 $content=shift->(page => $page, content => $content);
523 sub indexlink () { #{{{
524 return "<a href=\"$config{url}\">$config{wikiname}</a>";
527 sub lockwiki () { #{{{
528 # Take an exclusive lock on the wiki to prevent multiple concurrent
529 # run issues. The lock will be dropped on program exit.
530 if (! -d $config{wikistatedir}) {
531 mkdir($config{wikistatedir});
533 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
534 error ("cannot write to $config{wikistatedir}/lockfile: $!");
535 if (! flock(WIKILOCK, 2 | 4)) {
536 debug("wiki seems to be locked, waiting for lock");
537 my $wait=600; # arbitrary, but don't hang forever to
538 # prevent process pileup
540 return if flock(WIKILOCK, 2 | 4);
543 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
547 sub unlockwiki () { #{{{
551 sub loadindex () { #{{{
552 open (IN, "$config{wikistatedir}/index") || return;
554 $_=possibly_foolish_untaint($_);
559 foreach my $i (split(/ /, $_)) {
560 my ($item, $val)=split(/=/, $i, 2);
561 push @{$items{$item}}, decode_entities($val);
564 next unless exists $items{src}; # skip bad lines for now
566 my $page=pagename($items{src}[0]);
567 if (! $config{rebuild}) {
568 $pagesources{$page}=$items{src}[0];
569 $oldpagemtime{$page}=$items{mtime}[0];
570 $oldlinks{$page}=[@{$items{link}}];
571 $links{$page}=[@{$items{link}}];
572 $depends{$page}=$items{depends}[0] if exists $items{depends};
573 $renderedfiles{$page}=[@{$items{dest}}];
574 $oldrenderedfiles{$page}=[@{$items{dest}}];
575 $pagecase{lc $page}=$page;
577 $pagectime{$page}=$items{ctime}[0];
582 sub saveindex () { #{{{
583 run_hooks(savestate => sub { shift->() });
585 if (! -d $config{wikistatedir}) {
586 mkdir($config{wikistatedir});
588 open (OUT, ">$config{wikistatedir}/index") ||
589 error("cannot write to $config{wikistatedir}/index: $!");
590 foreach my $page (keys %oldpagemtime) {
591 next unless $oldpagemtime{$page};
592 my $line="mtime=$oldpagemtime{$page} ".
593 "ctime=$pagectime{$page} ".
594 "src=$pagesources{$page}";
595 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
596 $line.=" link=$_" foreach @{$links{$page}};
597 if (exists $depends{$page}) {
598 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
600 print OUT $line."\n";
605 sub template_params (@) { #{{{
608 require HTML::Template;
609 return filter => sub {
610 my $text_ref = shift;
611 $$text_ref=&Encode::decode_utf8($$text_ref);
613 filename => "$config{templatedir}/$filename",
614 loop_context_vars => 1,
615 die_on_bad_params => 0,
619 sub template ($;@) { #{{{
620 HTML::Template->new(template_params(@_));
623 sub misctemplate ($$;@) { #{{{
627 my $template=template("misc.tmpl");
630 indexlink => indexlink(),
631 wikiname => $config{wikiname},
632 pagebody => $pagebody,
633 baseurl => baseurl(),
636 run_hooks(pagetemplate => sub {
637 shift->(page => "", destpage => "", template => $template);
639 return $template->output;
645 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
646 error "hook requires type, call, and id parameters";
649 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
651 $hooks{$param{type}}{$param{id}}=\%param;
654 sub run_hooks ($$) { # {{{
655 # Calls the given sub for each hook of the given type,
656 # passing it the hook function to call.
660 if (exists $hooks{$type}) {
661 foreach my $id (keys %{$hooks{$type}}) {
662 $sub->($hooks{$type}{$id}{call});
667 sub globlist_to_pagespec ($) { #{{{
668 my @globlist=split(' ', shift);
671 foreach my $glob (@globlist) {
672 if ($glob=~/^!(.*)/) {
680 my $spec=join(" or ", @spec);
682 my $skip=join(" and ", @skip);
684 $spec="$skip and ($spec)";
693 sub is_globlist ($) { #{{{
695 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
698 sub safequote ($) { #{{{
704 sub pagespec_merge ($$) { #{{{
708 return $a if $a eq $b;
710 # Support for old-style GlobLists.
711 if (is_globlist($a)) {
712 $a=globlist_to_pagespec($a);
714 if (is_globlist($b)) {
715 $b=globlist_to_pagespec($b);
718 return "($a) or ($b)";
721 sub pagespec_translate ($) { #{{{
722 # This assumes that $page is in scope in the function
723 # that evalulates the translated pagespec code.
726 # Support for old-style GlobLists.
727 if (is_globlist($spec)) {
728 $spec=globlist_to_pagespec($spec);
731 # Convert spec to perl code.
733 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
735 if (lc $word eq "and") {
738 elsif (lc $word eq "or") {
741 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
744 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
745 $code.=" match_$1(\$page, ".safequote($2).")";
748 $code.=" match_glob(\$page, ".safequote($word).")";
755 sub add_depends ($$) { #{{{
759 if (! exists $depends{$page}) {
760 $depends{$page}=$pagespec;
763 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
767 sub pagespec_match ($$) { #{{{
771 return eval pagespec_translate($spec);
774 sub match_glob ($$) { #{{{
778 # turn glob into safe regexp
779 $glob=quotemeta($glob);
783 return $page=~/^$glob$/i;
786 sub match_link ($$) { #{{{
790 my $links = $links{$page} or return undef;
791 foreach my $p (@$links) {
792 return 1 if lc $p eq $link;
797 sub match_backlink ($$) { #{{{
798 match_link(pop, pop);
801 sub match_created_before ($$) { #{{{
805 if (exists $pagectime{$testpage}) {
806 return $pagectime{$page} < $pagectime{$testpage};
813 sub match_created_after ($$) { #{{{
817 if (exists $pagectime{$testpage}) {
818 return $pagectime{$page} > $pagectime{$testpage};
825 sub match_creation_day ($$) { #{{{
826 return ((gmtime($pagectime{shift()}))[3] == shift);
829 sub match_creation_month ($$) { #{{{
830 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
833 sub match_creation_year ($$) { #{{{
834 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);