8 use open qw{:utf8 :std};
10 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
11 %renderedfiles %pagesources %depends %hooks %forcerebuild};
13 use Exporter q{import};
14 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
15 bestlink htmllink readfile writefile pagetype srcfile pagename
17 %config %links %renderedfiles %pagesources);
23 memoize("pagespec_translate");
25 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
27 sub defaultconfig () { #{{{
28 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$)},
29 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
30 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
34 default_pageext => "mdwn",
56 templatedir => "$installdir/share/ikiwiki/templates",
57 underlaydir => "$installdir/share/ikiwiki/basewiki",
61 plugin => [qw{mdwn inline htmlscrubber}],
67 sub checkconfig () { #{{{
68 # locale stuff; avoid LC_ALL since it overrides everything
69 if (defined $ENV{LC_ALL}) {
70 $ENV{LANG} = $ENV{LC_ALL};
73 if (defined $config{locale}) {
75 $ENV{LANG} = $config{locale}
76 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
79 if ($config{w3mmode}) {
80 eval q{use Cwd q{abs_path}};
81 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
82 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
83 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
84 unless $config{cgiurl} =~ m!file:///!;
85 $config{url}="file://".$config{destdir};
88 if ($config{cgi} && ! length $config{url}) {
89 error("Must specify url to wiki with --url when using --cgi\n");
91 if ($config{rss} && ! length $config{url}) {
92 error("Must specify url to wiki with --url when using --rss\n");
95 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
96 unless exists $config{wikistatedir};
99 eval qq{require IkiWiki::Rcs::$config{rcs}};
101 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
105 require IkiWiki::Rcs::Stub;
108 run_hooks(checkconfig => sub { shift->() });
111 sub loadplugins () { #{{{
112 foreach my $plugin (@{$config{plugin}}) {
113 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
116 error("Failed to load plugin $mod: $@");
119 run_hooks(getopt => sub { shift->() });
120 if (grep /^-/, @ARGV) {
121 print STDERR "Unknown option: $_\n"
122 foreach grep /^-/, @ARGV;
129 print "Content-type: text/html\n\n";
130 print misctemplate("Error", "<p>Error: @_</p>");
132 log_message(error => @_);
137 return unless $config{verbose};
138 log_message(debug => @_);
142 sub log_message ($$) { #{{{
145 if ($config{syslog}) {
148 Sys::Syslog::setlogsock('unix');
149 Sys::Syslog::openlog('ikiwiki', '', 'user');
153 Sys::Syslog::syslog($type, join(" ", @_));
156 elsif (! $config{cgi}) {
164 sub possibly_foolish_untaint ($) { #{{{
166 my ($untainted)=$tainted=~/(.*)/;
170 sub basename ($) { #{{{
177 sub dirname ($) { #{{{
184 sub pagetype ($) { #{{{
187 if ($page =~ /\.([^.]+)$/) {
188 return $1 if exists $hooks{htmlize}{$1};
193 sub pagename ($) { #{{{
196 my $type=pagetype($file);
198 $page=~s/\Q.$type\E*$// if defined $type;
202 sub htmlpage ($) { #{{{
205 return $page.".html";
208 sub srcfile ($) { #{{{
211 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
212 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
213 error("internal error: $file cannot be found");
216 sub readfile ($;$) { #{{{
221 error("cannot read a symlink ($file)");
225 open (IN, $file) || error("failed to read $file: $!");
226 binmode(IN) if ($binary);
232 sub writefile ($$$;$) { #{{{
233 my $file=shift; # can include subdirs
234 my $destdir=shift; # directory to put file in
239 while (length $test) {
240 if (-l "$destdir/$test") {
241 error("cannot write to a symlink ($test)");
243 $test=dirname($test);
246 my $dir=dirname("$destdir/$file");
249 foreach my $s (split(m!/+!, $dir)) {
252 mkdir($d) || error("failed to create directory $d: $!");
257 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
258 binmode(OUT) if ($binary);
263 sub bestlink ($$) { #{{{
270 $l.="/" if length $l;
273 if (exists $links{$l}) {
276 elsif (exists $pagecase{lc $l}) {
277 return $pagecase{lc $l};
279 } while $cwd=~s!/?[^/]+$!!;
281 #print STDERR "warning: page $page, broken link: $link\n";
285 sub isinlinableimage ($) { #{{{
288 $file=~/\.(png|gif|jpg|jpeg)$/i;
291 sub pagetitle ($) { #{{{
293 $page=~s/__(\d+)__/&#$1;/g;
298 sub titlepage ($) { #{{{
301 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
305 sub cgiurl (@) { #{{{
308 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
311 sub baseurl (;$) { #{{{
314 return "$config{url}/" if ! defined $page;
317 $page=~s/[^\/]+\//..\//g;
321 sub abs2rel ($$) { #{{{
322 # Work around very innefficient behavior in File::Spec if abs2rel
323 # is passed two relative paths. It's much faster if paths are
324 # absolute! (Debian bug #376658)
329 my $ret=File::Spec->abs2rel($path, $base);
330 $ret=~s/^// if defined $ret;
334 sub displaytime ($) { #{{{
338 # strftime doesn't know about encodings, so make sure
339 # its output is properly treated as utf8
340 return decode_utf8(POSIX::strftime(
341 $config{timeformat}, localtime($time)));
344 sub htmllink ($$$;$$$) { #{{{
345 my $lpage=shift; # the page doing the linking
346 my $page=shift; # the page that will contain the link (different for inline)
348 my $noimageinline=shift; # don't turn links into inline html images
349 my $forcesubpage=shift; # force a link to a subpage
350 my $linktext=shift; # set to force the link text to something
353 if (! $forcesubpage) {
354 $bestlink=bestlink($lpage, $link);
357 $bestlink="$lpage/".lc($link);
360 $linktext=pagetitle(basename($link)) unless defined $linktext;
362 return "<span class=\"selflink\">$linktext</span>"
363 if length $bestlink && $page eq $bestlink;
365 # TODO BUG: %renderedfiles may not have it, if the linked to page
366 # was also added and isn't yet rendered! Note that this bug is
367 # masked by the bug that makes all new files be rendered twice.
368 if (! grep { $_ eq $bestlink } values %renderedfiles) {
369 $bestlink=htmlpage($bestlink);
371 if (! grep { $_ eq $bestlink } values %renderedfiles) {
372 return "<span><a href=\"".
373 cgiurl(do => "create", page => lc($link), from => $page).
374 "\">?</a>$linktext</span>"
377 $bestlink=abs2rel($bestlink, dirname($page));
379 if (! $noimageinline && isinlinableimage($bestlink)) {
380 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
382 return "<a href=\"$bestlink\">$linktext</a>";
385 sub htmlize ($$$) { #{{{
390 if (exists $hooks{htmlize}{$type}) {
391 $content=$hooks{htmlize}{$type}{call}->(
397 error("htmlization of $type not supported");
400 run_hooks(sanitize => sub {
410 sub linkify ($$$) { #{{{
411 my $lpage=shift; # the page containing the links
412 my $page=shift; # the page the link will end up on (different for inline)
415 $content =~ s{(\\?)$config{wiki_link_regexp}}{
416 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
417 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
424 sub preprocess ($$$) { #{{{
425 my $page=shift; # the page the data comes from
426 my $destpage=shift; # the page the data will appear in (different for inline)
433 if (length $escape) {
434 return "[[$command $params]]";
436 elsif (exists $hooks{preprocess}{$command}) {
437 # Note: preserve order of params, some plugins may
438 # consider it significant.
440 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
457 push @params, $key, $val;
460 push @params, $val, '';
463 if ($preprocessing{$page}++ > 3) {
464 # Avoid loops of preprocessed pages preprocessing
465 # other pages that preprocess them, etc.
466 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
468 my $ret=$hooks{preprocess}{$command}{call}->(
471 destpage => $destpage,
473 $preprocessing{$page}--;
477 return "[[$command $params]]";
481 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
489 run_hooks(filter => sub {
490 $content=shift->(page => $page, content => $content);
496 sub indexlink () { #{{{
497 return "<a href=\"$config{url}\">$config{wikiname}</a>";
500 sub lockwiki () { #{{{
501 # Take an exclusive lock on the wiki to prevent multiple concurrent
502 # run issues. The lock will be dropped on program exit.
503 if (! -d $config{wikistatedir}) {
504 mkdir($config{wikistatedir});
506 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
507 error ("cannot write to $config{wikistatedir}/lockfile: $!");
508 if (! flock(WIKILOCK, 2 | 4)) {
509 debug("wiki seems to be locked, waiting for lock");
510 my $wait=600; # arbitrary, but don't hang forever to
511 # prevent process pileup
513 return if flock(WIKILOCK, 2 | 4);
516 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
520 sub unlockwiki () { #{{{
524 sub loadindex () { #{{{
525 open (IN, "$config{wikistatedir}/index") || return;
527 $_=possibly_foolish_untaint($_);
531 foreach my $i (split(/ /, $_)) {
532 my ($item, $val)=split(/=/, $i, 2);
533 push @{$items{$item}}, decode_entities($val);
536 next unless exists $items{src}; # skip bad lines for now
538 my $page=pagename($items{src}[0]);
539 if (! $config{rebuild}) {
540 $pagesources{$page}=$items{src}[0];
541 $oldpagemtime{$page}=$items{mtime}[0];
542 $oldlinks{$page}=[@{$items{link}}];
543 $links{$page}=[@{$items{link}}];
544 $depends{$page}=$items{depends}[0] if exists $items{depends};
545 $renderedfiles{$page}=$items{dest}[0];
546 $pagecase{lc $page}=$page;
548 $pagectime{$page}=$items{ctime}[0];
553 sub saveindex () { #{{{
554 run_hooks(savestate => sub { shift->() });
556 if (! -d $config{wikistatedir}) {
557 mkdir($config{wikistatedir});
559 open (OUT, ">$config{wikistatedir}/index") ||
560 error("cannot write to $config{wikistatedir}/index: $!");
561 foreach my $page (keys %oldpagemtime) {
562 next unless $oldpagemtime{$page};
563 my $line="mtime=$oldpagemtime{$page} ".
564 "ctime=$pagectime{$page} ".
565 "src=$pagesources{$page} ".
566 "dest=$renderedfiles{$page}";
567 $line.=" link=$_" foreach @{$links{$page}};
568 if (exists $depends{$page}) {
569 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
571 print OUT $line."\n";
576 sub template_params (@) { #{{{
579 require HTML::Template;
580 return filter => sub {
581 my $text_ref = shift;
582 $$text_ref=&Encode::decode_utf8($$text_ref);
584 filename => "$config{templatedir}/$filename",
585 loop_context_vars => 1,
586 die_on_bad_params => 0,
590 sub template ($;@) { #{{{
591 HTML::Template->new(template_params(@_));
594 sub misctemplate ($$;@) { #{{{
598 my $template=template("misc.tmpl");
601 indexlink => indexlink(),
602 wikiname => $config{wikiname},
603 pagebody => $pagebody,
604 baseurl => baseurl(),
607 return $template->output;
613 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
614 error "hook requires type, call, and id parameters";
617 $hooks{$param{type}}{$param{id}}=\%param;
620 sub run_hooks ($$) { # {{{
621 # Calls the given sub for each hook of the given type,
622 # passing it the hook function to call.
626 if (exists $hooks{$type}) {
627 foreach my $id (keys %{$hooks{$type}}) {
628 $sub->($hooks{$type}{$id}{call});
633 sub globlist_to_pagespec ($) { #{{{
634 my @globlist=split(' ', shift);
637 foreach my $glob (@globlist) {
638 if ($glob=~/^!(.*)/) {
646 my $spec=join(" or ", @spec);
648 my $skip=join(" and ", @skip);
650 $spec="$skip and ($spec)";
659 sub is_globlist ($) { #{{{
661 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
664 sub safequote ($) { #{{{
670 sub pagespec_merge ($$) { #{{{
674 return $a if $a eq $b;
676 # Support for old-style GlobLists.
677 if (is_globlist($a)) {
678 $a=globlist_to_pagespec($a);
680 if (is_globlist($b)) {
681 $b=globlist_to_pagespec($b);
684 return "($a) or ($b)";
687 sub pagespec_translate ($) { #{{{
688 # This assumes that $page is in scope in the function
689 # that evalulates the translated pagespec code.
692 # Support for old-style GlobLists.
693 if (is_globlist($spec)) {
694 $spec=globlist_to_pagespec($spec);
697 # Convert spec to perl code.
699 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
701 if (lc $word eq "and") {
704 elsif (lc $word eq "or") {
707 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
710 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
711 $code.=" match_$1(\$page, ".safequote($2).")";
714 $code.=" match_glob(\$page, ".safequote($word).")";
721 sub add_depends ($$) { #{{{
725 if (! exists $depends{$page}) {
726 $depends{$page}=$pagespec;
729 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
733 sub pagespec_match ($$) { #{{{
737 return eval pagespec_translate($spec);
740 sub match_glob ($$) { #{{{
744 # turn glob into safe regexp
745 $glob=quotemeta($glob);
749 return $page=~/^$glob$/i;
752 sub match_link ($$) { #{{{
756 my $links = $links{$page} or return undef;
757 foreach my $p (@$links) {
758 return 1 if lc $p eq $link;
763 sub match_backlink ($$) { #{{{
764 match_link(pop, pop);
767 sub match_created_before ($$) { #{{{
771 if (exists $pagectime{$testpage}) {
772 return $pagectime{$page} < $pagectime{$testpage};
779 sub match_created_after ($$) { #{{{
783 if (exists $pagectime{$testpage}) {
784 return $pagectime{$page} > $pagectime{$testpage};
791 sub match_creation_day ($$) { #{{{
792 return ((gmtime($pagectime{shift()}))[3] == shift);
795 sub match_creation_month ($$) { #{{{
796 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
799 sub match_creation_year ($$) { #{{{
800 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);