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);
267 sub will_render ($$;$) { #{{{
272 # Important security check.
273 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
274 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
275 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
279 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
282 $renderedfiles{$page}=[$dest];
286 sub bestlink ($$) { #{{{
293 $l.="/" if length $l;
296 if (exists $links{$l}) {
299 elsif (exists $pagecase{lc $l}) {
300 return $pagecase{lc $l};
302 } while $cwd=~s!/?[^/]+$!!;
304 #print STDERR "warning: page $page, broken link: $link\n";
308 sub isinlinableimage ($) { #{{{
311 $file=~/\.(png|gif|jpg|jpeg)$/i;
314 sub pagetitle ($) { #{{{
316 $page=~s/__(\d+)__/&#$1;/g;
321 sub titlepage ($) { #{{{
324 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
328 sub cgiurl (@) { #{{{
331 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
334 sub baseurl (;$) { #{{{
337 return "$config{url}/" if ! defined $page;
340 $page=~s/[^\/]+\//..\//g;
344 sub abs2rel ($$) { #{{{
345 # Work around very innefficient behavior in File::Spec if abs2rel
346 # is passed two relative paths. It's much faster if paths are
347 # absolute! (Debian bug #376658)
352 my $ret=File::Spec->abs2rel($path, $base);
353 $ret=~s/^// if defined $ret;
357 sub displaytime ($) { #{{{
361 # strftime doesn't know about encodings, so make sure
362 # its output is properly treated as utf8
363 return decode_utf8(POSIX::strftime(
364 $config{timeformat}, localtime($time)));
367 sub htmllink ($$$;$$$) { #{{{
368 my $lpage=shift; # the page doing the linking
369 my $page=shift; # the page that will contain the link (different for inline)
371 my $noimageinline=shift; # don't turn links into inline html images
372 my $forcesubpage=shift; # force a link to a subpage
373 my $linktext=shift; # set to force the link text to something
376 if (! $forcesubpage) {
377 $bestlink=bestlink($lpage, $link);
380 $bestlink="$lpage/".lc($link);
383 $linktext=pagetitle(basename($link)) unless defined $linktext;
385 return "<span class=\"selflink\">$linktext</span>"
386 if length $bestlink && $page eq $bestlink;
388 # TODO BUG: %renderedfiles may not have it, if the linked to page
389 # was also added and isn't yet rendered! Note that this bug is
390 # masked by the bug that makes all new files be rendered twice.
391 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
392 $bestlink=htmlpage($bestlink);
394 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
395 return "<span><a href=\"".
396 cgiurl(do => "create", page => lc($link), from => $page).
397 "\">?</a>$linktext</span>"
400 $bestlink=abs2rel($bestlink, dirname($page));
402 if (! $noimageinline && isinlinableimage($bestlink)) {
403 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
405 return "<a href=\"$bestlink\">$linktext</a>";
408 sub htmlize ($$$) { #{{{
413 if (exists $hooks{htmlize}{$type}) {
414 $content=$hooks{htmlize}{$type}{call}->(
420 error("htmlization of $type not supported");
423 run_hooks(sanitize => sub {
433 sub linkify ($$$) { #{{{
434 my $lpage=shift; # the page containing the links
435 my $page=shift; # the page the link will end up on (different for inline)
438 $content =~ s{(\\?)$config{wiki_link_regexp}}{
439 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
440 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
447 sub preprocess ($$$) { #{{{
448 my $page=shift; # the page the data comes from
449 my $destpage=shift; # the page the data will appear in (different for inline)
456 if (length $escape) {
457 return "[[$command $params]]";
459 elsif (exists $hooks{preprocess}{$command}) {
460 # Note: preserve order of params, some plugins may
461 # consider it significant.
463 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
480 push @params, $key, $val;
483 push @params, $val, '';
486 if ($preprocessing{$page}++ > 3) {
487 # Avoid loops of preprocessed pages preprocessing
488 # other pages that preprocess them, etc.
489 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
491 my $ret=$hooks{preprocess}{$command}{call}->(
494 destpage => $destpage,
496 $preprocessing{$page}--;
500 return "[[$command $params]]";
504 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
512 run_hooks(filter => sub {
513 $content=shift->(page => $page, content => $content);
519 sub indexlink () { #{{{
520 return "<a href=\"$config{url}\">$config{wikiname}</a>";
523 sub lockwiki () { #{{{
524 # Take an exclusive lock on the wiki to prevent multiple concurrent
525 # run issues. The lock will be dropped on program exit.
526 if (! -d $config{wikistatedir}) {
527 mkdir($config{wikistatedir});
529 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
530 error ("cannot write to $config{wikistatedir}/lockfile: $!");
531 if (! flock(WIKILOCK, 2 | 4)) {
532 debug("wiki seems to be locked, waiting for lock");
533 my $wait=600; # arbitrary, but don't hang forever to
534 # prevent process pileup
536 return if flock(WIKILOCK, 2 | 4);
539 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
543 sub unlockwiki () { #{{{
547 sub loadindex () { #{{{
548 open (IN, "$config{wikistatedir}/index") || return;
550 $_=possibly_foolish_untaint($_);
555 foreach my $i (split(/ /, $_)) {
556 my ($item, $val)=split(/=/, $i, 2);
557 push @{$items{$item}}, decode_entities($val);
560 next unless exists $items{src}; # skip bad lines for now
562 my $page=pagename($items{src}[0]);
563 if (! $config{rebuild}) {
564 $pagesources{$page}=$items{src}[0];
565 $oldpagemtime{$page}=$items{mtime}[0];
566 $oldlinks{$page}=[@{$items{link}}];
567 $links{$page}=[@{$items{link}}];
568 $depends{$page}=$items{depends}[0] if exists $items{depends};
569 $renderedfiles{$page}=[@{$items{dest}}];
570 $oldrenderedfiles{$page}=[@{$items{dest}}];
571 $pagecase{lc $page}=$page;
573 $pagectime{$page}=$items{ctime}[0];
578 sub saveindex () { #{{{
579 run_hooks(savestate => sub { shift->() });
581 if (! -d $config{wikistatedir}) {
582 mkdir($config{wikistatedir});
584 open (OUT, ">$config{wikistatedir}/index") ||
585 error("cannot write to $config{wikistatedir}/index: $!");
586 foreach my $page (keys %oldpagemtime) {
587 next unless $oldpagemtime{$page};
588 my $line="mtime=$oldpagemtime{$page} ".
589 "ctime=$pagectime{$page} ".
590 "src=$pagesources{$page}";
591 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
592 $line.=" link=$_" foreach @{$links{$page}};
593 if (exists $depends{$page}) {
594 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
596 print OUT $line."\n";
601 sub template_params (@) { #{{{
604 require HTML::Template;
605 return filter => sub {
606 my $text_ref = shift;
607 $$text_ref=&Encode::decode_utf8($$text_ref);
609 filename => "$config{templatedir}/$filename",
610 loop_context_vars => 1,
611 die_on_bad_params => 0,
615 sub template ($;@) { #{{{
616 HTML::Template->new(template_params(@_));
619 sub misctemplate ($$;@) { #{{{
623 my $template=template("misc.tmpl");
626 indexlink => indexlink(),
627 wikiname => $config{wikiname},
628 pagebody => $pagebody,
629 baseurl => baseurl(),
632 run_hooks(pagetemplate => sub {
633 shift->(page => "", destpage => "", template => $template);
635 return $template->output;
641 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
642 error "hook requires type, call, and id parameters";
645 $hooks{$param{type}}{$param{id}}=\%param;
648 sub run_hooks ($$) { # {{{
649 # Calls the given sub for each hook of the given type,
650 # passing it the hook function to call.
654 if (exists $hooks{$type}) {
655 foreach my $id (keys %{$hooks{$type}}) {
656 $sub->($hooks{$type}{$id}{call});
661 sub globlist_to_pagespec ($) { #{{{
662 my @globlist=split(' ', shift);
665 foreach my $glob (@globlist) {
666 if ($glob=~/^!(.*)/) {
674 my $spec=join(" or ", @spec);
676 my $skip=join(" and ", @skip);
678 $spec="$skip and ($spec)";
687 sub is_globlist ($) { #{{{
689 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
692 sub safequote ($) { #{{{
698 sub pagespec_merge ($$) { #{{{
702 return $a if $a eq $b;
704 # Support for old-style GlobLists.
705 if (is_globlist($a)) {
706 $a=globlist_to_pagespec($a);
708 if (is_globlist($b)) {
709 $b=globlist_to_pagespec($b);
712 return "($a) or ($b)";
715 sub pagespec_translate ($) { #{{{
716 # This assumes that $page is in scope in the function
717 # that evalulates the translated pagespec code.
720 # Support for old-style GlobLists.
721 if (is_globlist($spec)) {
722 $spec=globlist_to_pagespec($spec);
725 # Convert spec to perl code.
727 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
729 if (lc $word eq "and") {
732 elsif (lc $word eq "or") {
735 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
738 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
739 $code.=" match_$1(\$page, ".safequote($2).")";
742 $code.=" match_glob(\$page, ".safequote($word).")";
749 sub add_depends ($$) { #{{{
753 if (! exists $depends{$page}) {
754 $depends{$page}=$pagespec;
757 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
761 sub pagespec_match ($$) { #{{{
765 return eval pagespec_translate($spec);
768 sub match_glob ($$) { #{{{
772 # turn glob into safe regexp
773 $glob=quotemeta($glob);
777 return $page=~/^$glob$/i;
780 sub match_link ($$) { #{{{
784 my $links = $links{$page} or return undef;
785 foreach my $p (@$links) {
786 return 1 if lc $p eq $link;
791 sub match_backlink ($$) { #{{{
792 match_link(pop, pop);
795 sub match_created_before ($$) { #{{{
799 if (exists $pagectime{$testpage}) {
800 return $pagectime{$page} < $pagectime{$testpage};
807 sub match_created_after ($$) { #{{{
811 if (exists $pagectime{$testpage}) {
812 return $pagectime{$page} > $pagectime{$testpage};
819 sub match_creation_day ($$) { #{{{
820 return ((gmtime($pagectime{shift()}))[3] == shift);
823 sub match_creation_month ($$) { #{{{
824 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
827 sub match_creation_year ($$) { #{{{
828 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);