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:]_.:\/+]+$)/,
33 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
37 default_pageext => "mdwn",
60 templatedir => "$installdir/share/ikiwiki/templates",
61 underlaydir => "$installdir/share/ikiwiki/basewiki",
65 plugin => [qw{mdwn inline htmlscrubber passwordauth}],
73 sub checkconfig () { #{{{
74 # locale stuff; avoid LC_ALL since it overrides everything
75 if (defined $ENV{LC_ALL}) {
76 $ENV{LANG} = $ENV{LC_ALL};
79 if (defined $config{locale}) {
82 $ENV{LANG} = $config{locale}
83 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
86 if ($config{w3mmode}) {
87 eval q{use Cwd q{abs_path}};
89 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
90 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
91 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
92 unless $config{cgiurl} =~ m!file:///!;
93 $config{url}="file://".$config{destdir};
96 if ($config{cgi} && ! length $config{url}) {
97 error("Must specify url to wiki with --url when using --cgi\n");
99 if (($config{rss} || $config{atom}) && ! length $config{url}) {
100 error("Must specify url to wiki with --url when using --rss or --atom\n");
103 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
104 unless exists $config{wikistatedir};
107 eval qq{require IkiWiki::Rcs::$config{rcs}};
109 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
113 require IkiWiki::Rcs::Stub;
116 run_hooks(checkconfig => sub { shift->() });
119 sub loadplugins () { #{{{
120 loadplugin($_) foreach @{$config{plugin}};
122 run_hooks(getopt => sub { shift->() });
123 if (grep /^-/, @ARGV) {
124 print STDERR "Unknown option: $_\n"
125 foreach grep /^-/, @ARGV;
130 sub loadplugin ($) { #{{{
133 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
136 error("Failed to load plugin $mod: $@");
142 print "Content-type: text/html\n\n";
143 print misctemplate("Error", "<p>Error: @_</p>");
145 log_message(error => @_);
150 return unless $config{verbose};
151 log_message(debug => @_);
155 sub log_message ($$) { #{{{
158 if ($config{syslog}) {
161 Sys::Syslog::setlogsock('unix');
162 Sys::Syslog::openlog('ikiwiki', '', 'user');
166 Sys::Syslog::syslog($type, join(" ", @_));
169 elsif (! $config{cgi}) {
177 sub possibly_foolish_untaint ($) { #{{{
179 my ($untainted)=$tainted=~/(.*)/;
183 sub basename ($) { #{{{
190 sub dirname ($) { #{{{
197 sub pagetype ($) { #{{{
200 if ($page =~ /\.([^.]+)$/) {
201 return $1 if exists $hooks{htmlize}{$1};
206 sub pagename ($) { #{{{
209 my $type=pagetype($file);
211 $page=~s/\Q.$type\E*$// if defined $type;
215 sub htmlpage ($) { #{{{
218 return $page.".html";
221 sub srcfile ($) { #{{{
224 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
225 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
226 error("internal error: $file cannot be found");
229 sub readfile ($;$) { #{{{
234 error("cannot read a symlink ($file)");
238 open (IN, $file) || error("failed to read $file: $!");
239 binmode(IN) if ($binary);
245 sub writefile ($$$;$) { #{{{
246 my $file=shift; # can include subdirs
247 my $destdir=shift; # directory to put file in
252 while (length $test) {
253 if (-l "$destdir/$test") {
254 error("cannot write to a symlink ($test)");
256 $test=dirname($test);
259 my $dir=dirname("$destdir/$file");
262 foreach my $s (split(m!/+!, $dir)) {
265 mkdir($d) || error("failed to create directory $d: $!");
270 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
271 binmode(OUT) if ($binary);
277 sub will_render ($$;$) { #{{{
282 # Important security check.
283 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
284 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
285 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
288 if (! $clear || $cleared{$page}) {
289 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
292 $renderedfiles{$page}=[$dest];
297 sub bestlink ($$) { #{{{
304 $l.="/" if length $l;
307 if (exists $links{$l}) {
310 elsif (exists $pagecase{lc $l}) {
311 return $pagecase{lc $l};
313 } while $cwd=~s!/?[^/]+$!!;
315 #print STDERR "warning: page $page, broken link: $link\n";
319 sub isinlinableimage ($) { #{{{
322 $file=~/\.(png|gif|jpg|jpeg)$/i;
325 sub pagetitle ($) { #{{{
327 $page=~s/__(\d+)__/&#$1;/g;
332 sub titlepage ($) { #{{{
335 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
339 sub cgiurl (@) { #{{{
342 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
345 sub baseurl (;$) { #{{{
348 return "$config{url}/" if ! defined $page;
351 $page=~s/[^\/]+\//..\//g;
355 sub abs2rel ($$) { #{{{
356 # Work around very innefficient behavior in File::Spec if abs2rel
357 # is passed two relative paths. It's much faster if paths are
358 # absolute! (Debian bug #376658; fixed in debian unstable now)
363 my $ret=File::Spec->abs2rel($path, $base);
364 $ret=~s/^// if defined $ret;
368 sub displaytime ($) { #{{{
373 # strftime doesn't know about encodings, so make sure
374 # its output is properly treated as utf8
375 return decode_utf8(POSIX::strftime(
376 $config{timeformat}, localtime($time)));
379 sub htmllink ($$$;$$$) { #{{{
380 my $lpage=shift; # the page doing the linking
381 my $page=shift; # the page that will contain the link (different for inline)
383 my $noimageinline=shift; # don't turn links into inline html images
384 my $forcesubpage=shift; # force a link to a subpage
385 my $linktext=shift; # set to force the link text to something
388 if (! $forcesubpage) {
389 $bestlink=bestlink($lpage, $link);
392 $bestlink="$lpage/".lc($link);
395 $linktext=pagetitle(basename($link)) unless defined $linktext;
397 return "<span class=\"selflink\">$linktext</span>"
398 if length $bestlink && $page eq $bestlink;
400 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
401 $bestlink=htmlpage($bestlink);
403 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
404 return "<span><a href=\"".
405 cgiurl(do => "create", page => lc($link), from => $page).
406 "\">?</a>$linktext</span>"
409 $bestlink=abs2rel($bestlink, dirname($page));
411 if (! $noimageinline && isinlinableimage($bestlink)) {
412 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
414 return "<a href=\"$bestlink\">$linktext</a>";
417 sub htmlize ($$$) { #{{{
422 if (exists $hooks{htmlize}{$type}) {
423 $content=$hooks{htmlize}{$type}{call}->(
429 error("htmlization of $type not supported");
432 run_hooks(sanitize => sub {
442 sub linkify ($$$) { #{{{
443 my $lpage=shift; # the page containing the links
444 my $page=shift; # the page the link will end up on (different for inline)
447 $content =~ s{(\\?)$config{wiki_link_regexp}}{
448 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
449 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
456 sub preprocess ($$$;$) { #{{{
457 my $page=shift; # the page the data comes from
458 my $destpage=shift; # the page the data will appear in (different for inline)
466 if (length $escape) {
467 return "[[$command $params]]";
469 elsif (exists $hooks{preprocess}{$command}) {
470 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
471 # Note: preserve order of params, some plugins may
472 # consider it significant.
474 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
491 push @params, $key, $val;
494 push @params, $val, '';
497 if ($preprocessing{$page}++ > 3) {
498 # Avoid loops of preprocessed pages preprocessing
499 # other pages that preprocess them, etc.
500 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
502 my $ret=$hooks{preprocess}{$command}{call}->(
505 destpage => $destpage,
507 $preprocessing{$page}--;
511 return "[[$command $params]]";
515 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
519 sub filter ($$) { #{{{
523 run_hooks(filter => sub {
524 $content=shift->(page => $page, content => $content);
530 sub indexlink () { #{{{
531 return "<a href=\"$config{url}\">$config{wikiname}</a>";
534 sub lockwiki () { #{{{
535 # Take an exclusive lock on the wiki to prevent multiple concurrent
536 # run issues. The lock will be dropped on program exit.
537 if (! -d $config{wikistatedir}) {
538 mkdir($config{wikistatedir});
540 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
541 error ("cannot write to $config{wikistatedir}/lockfile: $!");
542 if (! flock(WIKILOCK, 2 | 4)) {
543 debug("wiki seems to be locked, waiting for lock");
544 my $wait=600; # arbitrary, but don't hang forever to
545 # prevent process pileup
547 return if flock(WIKILOCK, 2 | 4);
550 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
554 sub unlockwiki () { #{{{
558 sub loadindex () { #{{{
559 open (IN, "$config{wikistatedir}/index") || return;
561 $_=possibly_foolish_untaint($_);
566 foreach my $i (split(/ /, $_)) {
567 my ($item, $val)=split(/=/, $i, 2);
568 push @{$items{$item}}, decode_entities($val);
571 next unless exists $items{src}; # skip bad lines for now
573 my $page=pagename($items{src}[0]);
574 if (! $config{rebuild}) {
575 $pagesources{$page}=$items{src}[0];
576 $oldpagemtime{$page}=$items{mtime}[0];
577 $oldlinks{$page}=[@{$items{link}}];
578 $links{$page}=[@{$items{link}}];
579 $depends{$page}=$items{depends}[0] if exists $items{depends};
580 $renderedfiles{$page}=[@{$items{dest}}];
581 $oldrenderedfiles{$page}=[@{$items{dest}}];
582 $pagecase{lc $page}=$page;
584 $pagectime{$page}=$items{ctime}[0];
589 sub saveindex () { #{{{
590 run_hooks(savestate => sub { shift->() });
592 if (! -d $config{wikistatedir}) {
593 mkdir($config{wikistatedir});
595 open (OUT, ">$config{wikistatedir}/index") ||
596 error("cannot write to $config{wikistatedir}/index: $!");
597 foreach my $page (keys %oldpagemtime) {
598 next unless $oldpagemtime{$page};
599 my $line="mtime=$oldpagemtime{$page} ".
600 "ctime=$pagectime{$page} ".
601 "src=$pagesources{$page}";
602 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
604 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
605 if (exists $depends{$page}) {
606 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
608 print OUT $line."\n";
613 sub template_params (@) { #{{{
616 require HTML::Template;
617 return filter => sub {
618 my $text_ref = shift;
619 $$text_ref=&Encode::decode_utf8($$text_ref);
621 filename => "$config{templatedir}/$filename",
622 loop_context_vars => 1,
623 die_on_bad_params => 0,
627 sub template ($;@) { #{{{
628 HTML::Template->new(template_params(@_));
631 sub misctemplate ($$;@) { #{{{
635 my $template=template("misc.tmpl");
638 indexlink => indexlink(),
639 wikiname => $config{wikiname},
640 pagebody => $pagebody,
641 baseurl => baseurl(),
644 run_hooks(pagetemplate => sub {
645 shift->(page => "", destpage => "", template => $template);
647 return $template->output;
653 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
654 error "hook requires type, call, and id parameters";
657 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
659 $hooks{$param{type}}{$param{id}}=\%param;
662 sub run_hooks ($$) { # {{{
663 # Calls the given sub for each hook of the given type,
664 # passing it the hook function to call.
668 if (exists $hooks{$type}) {
670 foreach my $id (keys %{$hooks{$type}}) {
671 if ($hooks{$type}{$id}{last}) {
675 $sub->($hooks{$type}{$id}{call});
677 foreach my $id (@deferred) {
678 $sub->($hooks{$type}{$id}{call});
683 sub globlist_to_pagespec ($) { #{{{
684 my @globlist=split(' ', shift);
687 foreach my $glob (@globlist) {
688 if ($glob=~/^!(.*)/) {
696 my $spec=join(" or ", @spec);
698 my $skip=join(" and ", @skip);
700 $spec="$skip and ($spec)";
709 sub is_globlist ($) { #{{{
711 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
714 sub safequote ($) { #{{{
720 sub pagespec_merge ($$) { #{{{
724 return $a if $a eq $b;
726 # Support for old-style GlobLists.
727 if (is_globlist($a)) {
728 $a=globlist_to_pagespec($a);
730 if (is_globlist($b)) {
731 $b=globlist_to_pagespec($b);
734 return "($a) or ($b)";
737 sub pagespec_translate ($) { #{{{
738 # This assumes that $page is in scope in the function
739 # that evalulates the translated pagespec code.
742 # Support for old-style GlobLists.
743 if (is_globlist($spec)) {
744 $spec=globlist_to_pagespec($spec);
747 # Convert spec to perl code.
749 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
751 if (lc $word eq "and") {
754 elsif (lc $word eq "or") {
757 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
760 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
761 $code.=" match_$1(\$page, ".safequote($2).")";
764 $code.=" match_glob(\$page, ".safequote($word).")";
771 sub add_depends ($$) { #{{{
775 if (! exists $depends{$page}) {
776 $depends{$page}=$pagespec;
779 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
783 sub pagespec_match ($$) { #{{{
787 return eval pagespec_translate($spec);
790 sub match_glob ($$) { #{{{
794 # turn glob into safe regexp
795 $glob=quotemeta($glob);
799 return $page=~/^$glob$/i;
802 sub match_link ($$) { #{{{
806 my $links = $links{$page} or return undef;
807 foreach my $p (@$links) {
808 return 1 if lc $p eq $link;
813 sub match_backlink ($$) { #{{{
814 match_link(pop, pop);
817 sub match_created_before ($$) { #{{{
821 if (exists $pagectime{$testpage}) {
822 return $pagectime{$page} < $pagectime{$testpage};
829 sub match_created_after ($$) { #{{{
833 if (exists $pagectime{$testpage}) {
834 return $pagectime{$page} > $pagectime{$testpage};
841 sub match_creation_day ($$) { #{{{
842 return ((gmtime($pagectime{shift()}))[3] == shift);
845 sub match_creation_month ($$) { #{{{
846 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
849 sub match_creation_year ($$) { #{{{
850 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);