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
18 %config %links %renderedfiles %pagesources);
24 memoize("pagespec_translate");
26 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
28 sub defaultconfig () { #{{{
29 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$|.arch-ids/|{arch}/)},
30 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
31 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
35 default_pageext => "mdwn",
57 templatedir => "$installdir/share/ikiwiki/templates",
58 underlaydir => "$installdir/share/ikiwiki/basewiki",
62 plugin => [qw{mdwn inline htmlscrubber}],
69 sub checkconfig () { #{{{
70 # locale stuff; avoid LC_ALL since it overrides everything
71 if (defined $ENV{LC_ALL}) {
72 $ENV{LANG} = $ENV{LC_ALL};
75 if (defined $config{locale}) {
77 $ENV{LANG} = $config{locale}
78 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
81 if ($config{w3mmode}) {
82 eval q{use Cwd q{abs_path}};
83 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
84 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
85 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
86 unless $config{cgiurl} =~ m!file:///!;
87 $config{url}="file://".$config{destdir};
90 if ($config{cgi} && ! length $config{url}) {
91 error("Must specify url to wiki with --url when using --cgi\n");
93 if ($config{rss} && ! length $config{url}) {
94 error("Must specify url to wiki with --url when using --rss\n");
97 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
98 unless exists $config{wikistatedir};
101 eval qq{require IkiWiki::Rcs::$config{rcs}};
103 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
107 require IkiWiki::Rcs::Stub;
110 run_hooks(checkconfig => sub { shift->() });
113 sub loadplugins () { #{{{
114 foreach my $plugin (@{$config{plugin}}) {
115 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
118 error("Failed to load plugin $mod: $@");
121 run_hooks(getopt => sub { shift->() });
122 if (grep /^-/, @ARGV) {
123 print STDERR "Unknown option: $_\n"
124 foreach grep /^-/, @ARGV;
131 print "Content-type: text/html\n\n";
132 print misctemplate("Error", "<p>Error: @_</p>");
134 log_message(error => @_);
139 return unless $config{verbose};
140 log_message(debug => @_);
144 sub log_message ($$) { #{{{
147 if ($config{syslog}) {
150 Sys::Syslog::setlogsock('unix');
151 Sys::Syslog::openlog('ikiwiki', '', 'user');
155 Sys::Syslog::syslog($type, join(" ", @_));
158 elsif (! $config{cgi}) {
166 sub possibly_foolish_untaint ($) { #{{{
168 my ($untainted)=$tainted=~/(.*)/;
172 sub basename ($) { #{{{
179 sub dirname ($) { #{{{
186 sub pagetype ($) { #{{{
189 if ($page =~ /\.([^.]+)$/) {
190 return $1 if exists $hooks{htmlize}{$1};
195 sub pagename ($) { #{{{
198 my $type=pagetype($file);
200 $page=~s/\Q.$type\E*$// if defined $type;
204 sub htmlpage ($) { #{{{
207 return $page.".html";
210 sub srcfile ($) { #{{{
213 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
214 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
215 error("internal error: $file cannot be found");
218 sub readfile ($;$) { #{{{
223 error("cannot read a symlink ($file)");
227 open (IN, $file) || error("failed to read $file: $!");
228 binmode(IN) if ($binary);
234 sub writefile ($$$;$) { #{{{
235 my $file=shift; # can include subdirs
236 my $destdir=shift; # directory to put file in
241 while (length $test) {
242 if (-l "$destdir/$test") {
243 error("cannot write to a symlink ($test)");
245 $test=dirname($test);
248 my $dir=dirname("$destdir/$file");
251 foreach my $s (split(m!/+!, $dir)) {
254 mkdir($d) || error("failed to create directory $d: $!");
259 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
260 binmode(OUT) if ($binary);
265 sub will_render ($$;$) { #{{{
270 # Important security check.
271 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
272 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
273 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
277 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
280 $renderedfiles{$page}=[$dest];
284 sub bestlink ($$) { #{{{
291 $l.="/" if length $l;
294 if (exists $links{$l}) {
297 elsif (exists $pagecase{lc $l}) {
298 return $pagecase{lc $l};
300 } while $cwd=~s!/?[^/]+$!!;
302 #print STDERR "warning: page $page, broken link: $link\n";
306 sub isinlinableimage ($) { #{{{
309 $file=~/\.(png|gif|jpg|jpeg)$/i;
312 sub pagetitle ($) { #{{{
314 $page=~s/__(\d+)__/&#$1;/g;
319 sub titlepage ($) { #{{{
322 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
326 sub cgiurl (@) { #{{{
329 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
332 sub baseurl (;$) { #{{{
335 return "$config{url}/" if ! defined $page;
338 $page=~s/[^\/]+\//..\//g;
342 sub abs2rel ($$) { #{{{
343 # Work around very innefficient behavior in File::Spec if abs2rel
344 # is passed two relative paths. It's much faster if paths are
345 # absolute! (Debian bug #376658)
350 my $ret=File::Spec->abs2rel($path, $base);
351 $ret=~s/^// if defined $ret;
355 sub displaytime ($) { #{{{
359 # strftime doesn't know about encodings, so make sure
360 # its output is properly treated as utf8
361 return decode_utf8(POSIX::strftime(
362 $config{timeformat}, localtime($time)));
365 sub htmllink ($$$;$$$) { #{{{
366 my $lpage=shift; # the page doing the linking
367 my $page=shift; # the page that will contain the link (different for inline)
369 my $noimageinline=shift; # don't turn links into inline html images
370 my $forcesubpage=shift; # force a link to a subpage
371 my $linktext=shift; # set to force the link text to something
374 if (! $forcesubpage) {
375 $bestlink=bestlink($lpage, $link);
378 $bestlink="$lpage/".lc($link);
381 $linktext=pagetitle(basename($link)) unless defined $linktext;
383 return "<span class=\"selflink\">$linktext</span>"
384 if length $bestlink && $page eq $bestlink;
386 # TODO BUG: %renderedfiles may not have it, if the linked to page
387 # was also added and isn't yet rendered! Note that this bug is
388 # masked by the bug that makes all new files be rendered twice.
389 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
390 $bestlink=htmlpage($bestlink);
392 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
393 return "<span><a href=\"".
394 cgiurl(do => "create", page => lc($link), from => $page).
395 "\">?</a>$linktext</span>"
398 $bestlink=abs2rel($bestlink, dirname($page));
400 if (! $noimageinline && isinlinableimage($bestlink)) {
401 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
403 return "<a href=\"$bestlink\">$linktext</a>";
406 sub htmlize ($$$) { #{{{
411 if (exists $hooks{htmlize}{$type}) {
412 $content=$hooks{htmlize}{$type}{call}->(
418 error("htmlization of $type not supported");
421 run_hooks(sanitize => sub {
431 sub linkify ($$$) { #{{{
432 my $lpage=shift; # the page containing the links
433 my $page=shift; # the page the link will end up on (different for inline)
436 $content =~ s{(\\?)$config{wiki_link_regexp}}{
437 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
438 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
445 sub preprocess ($$$) { #{{{
446 my $page=shift; # the page the data comes from
447 my $destpage=shift; # the page the data will appear in (different for inline)
454 if (length $escape) {
455 return "[[$command $params]]";
457 elsif (exists $hooks{preprocess}{$command}) {
458 # Note: preserve order of params, some plugins may
459 # consider it significant.
461 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
478 push @params, $key, $val;
481 push @params, $val, '';
484 if ($preprocessing{$page}++ > 3) {
485 # Avoid loops of preprocessed pages preprocessing
486 # other pages that preprocess them, etc.
487 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
489 my $ret=$hooks{preprocess}{$command}{call}->(
492 destpage => $destpage,
494 $preprocessing{$page}--;
498 return "[[$command $params]]";
502 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
510 run_hooks(filter => sub {
511 $content=shift->(page => $page, content => $content);
517 sub indexlink () { #{{{
518 return "<a href=\"$config{url}\">$config{wikiname}</a>";
521 sub lockwiki () { #{{{
522 # Take an exclusive lock on the wiki to prevent multiple concurrent
523 # run issues. The lock will be dropped on program exit.
524 if (! -d $config{wikistatedir}) {
525 mkdir($config{wikistatedir});
527 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
528 error ("cannot write to $config{wikistatedir}/lockfile: $!");
529 if (! flock(WIKILOCK, 2 | 4)) {
530 debug("wiki seems to be locked, waiting for lock");
531 my $wait=600; # arbitrary, but don't hang forever to
532 # prevent process pileup
534 return if flock(WIKILOCK, 2 | 4);
537 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
541 sub unlockwiki () { #{{{
545 sub loadindex () { #{{{
546 open (IN, "$config{wikistatedir}/index") || return;
548 $_=possibly_foolish_untaint($_);
553 foreach my $i (split(/ /, $_)) {
554 my ($item, $val)=split(/=/, $i, 2);
555 push @{$items{$item}}, decode_entities($val);
558 next unless exists $items{src}; # skip bad lines for now
560 my $page=pagename($items{src}[0]);
561 if (! $config{rebuild}) {
562 $pagesources{$page}=$items{src}[0];
563 $oldpagemtime{$page}=$items{mtime}[0];
564 $oldlinks{$page}=[@{$items{link}}];
565 $links{$page}=[@{$items{link}}];
566 $depends{$page}=$items{depends}[0] if exists $items{depends};
567 $renderedfiles{$page}=[@{$items{dest}}];
568 $oldrenderedfiles{$page}=[@{$items{dest}}];
569 $pagecase{lc $page}=$page;
571 $pagectime{$page}=$items{ctime}[0];
576 sub saveindex () { #{{{
577 run_hooks(savestate => sub { shift->() });
579 if (! -d $config{wikistatedir}) {
580 mkdir($config{wikistatedir});
582 open (OUT, ">$config{wikistatedir}/index") ||
583 error("cannot write to $config{wikistatedir}/index: $!");
584 foreach my $page (keys %oldpagemtime) {
585 next unless $oldpagemtime{$page};
586 my $line="mtime=$oldpagemtime{$page} ".
587 "ctime=$pagectime{$page} ".
588 "src=$pagesources{$page}";
589 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
590 $line.=" link=$_" foreach @{$links{$page}};
591 if (exists $depends{$page}) {
592 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
594 print OUT $line."\n";
599 sub template_params (@) { #{{{
602 require HTML::Template;
603 return filter => sub {
604 my $text_ref = shift;
605 $$text_ref=&Encode::decode_utf8($$text_ref);
607 filename => "$config{templatedir}/$filename",
608 loop_context_vars => 1,
609 die_on_bad_params => 0,
613 sub template ($;@) { #{{{
614 HTML::Template->new(template_params(@_));
617 sub misctemplate ($$;@) { #{{{
621 my $template=template("misc.tmpl");
624 indexlink => indexlink(),
625 wikiname => $config{wikiname},
626 pagebody => $pagebody,
627 baseurl => baseurl(),
630 run_hooks(pagetemplate => sub {
631 shift->(page => "", destpage => "", template => $template);
633 return $template->output;
639 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
640 error "hook requires type, call, and id parameters";
643 $hooks{$param{type}}{$param{id}}=\%param;
646 sub run_hooks ($$) { # {{{
647 # Calls the given sub for each hook of the given type,
648 # passing it the hook function to call.
652 if (exists $hooks{$type}) {
653 foreach my $id (keys %{$hooks{$type}}) {
654 $sub->($hooks{$type}{$id}{call});
659 sub globlist_to_pagespec ($) { #{{{
660 my @globlist=split(' ', shift);
663 foreach my $glob (@globlist) {
664 if ($glob=~/^!(.*)/) {
672 my $spec=join(" or ", @spec);
674 my $skip=join(" and ", @skip);
676 $spec="$skip and ($spec)";
685 sub is_globlist ($) { #{{{
687 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
690 sub safequote ($) { #{{{
696 sub pagespec_merge ($$) { #{{{
700 return $a if $a eq $b;
702 # Support for old-style GlobLists.
703 if (is_globlist($a)) {
704 $a=globlist_to_pagespec($a);
706 if (is_globlist($b)) {
707 $b=globlist_to_pagespec($b);
710 return "($a) or ($b)";
713 sub pagespec_translate ($) { #{{{
714 # This assumes that $page is in scope in the function
715 # that evalulates the translated pagespec code.
718 # Support for old-style GlobLists.
719 if (is_globlist($spec)) {
720 $spec=globlist_to_pagespec($spec);
723 # Convert spec to perl code.
725 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
727 if (lc $word eq "and") {
730 elsif (lc $word eq "or") {
733 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
736 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
737 $code.=" match_$1(\$page, ".safequote($2).")";
740 $code.=" match_glob(\$page, ".safequote($word).")";
747 sub add_depends ($$) { #{{{
751 if (! exists $depends{$page}) {
752 $depends{$page}=$pagespec;
755 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
759 sub pagespec_match ($$) { #{{{
763 return eval pagespec_translate($spec);
766 sub match_glob ($$) { #{{{
770 # turn glob into safe regexp
771 $glob=quotemeta($glob);
775 return $page=~/^$glob$/i;
778 sub match_link ($$) { #{{{
782 my $links = $links{$page} or return undef;
783 foreach my $p (@$links) {
784 return 1 if lc $p eq $link;
789 sub match_backlink ($$) { #{{{
790 match_link(pop, pop);
793 sub match_created_before ($$) { #{{{
797 if (exists $pagectime{$testpage}) {
798 return $pagectime{$page} < $pagectime{$testpage};
805 sub match_created_after ($$) { #{{{
809 if (exists $pagectime{$testpage}) {
810 return $pagectime{$page} > $pagectime{$testpage};
817 sub match_creation_day ($$) { #{{{
818 return ((gmtime($pagectime{shift()}))[3] == shift);
821 sub match_creation_month ($$) { #{{{
822 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
825 sub match_creation_year ($$) { #{{{
826 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);