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}) {
80 $ENV{LANG} = $config{locale}
81 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
84 if ($config{w3mmode}) {
85 eval q{use Cwd q{abs_path}};
87 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
88 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
89 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
90 unless $config{cgiurl} =~ m!file:///!;
91 $config{url}="file://".$config{destdir};
94 if ($config{cgi} && ! length $config{url}) {
95 error("Must specify url to wiki with --url when using --cgi\n");
97 if (($config{rss} || $config{atom}) && ! length $config{url}) {
98 error("Must specify url to wiki with --url when using --rss or --atom\n");
101 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
102 unless exists $config{wikistatedir};
105 eval qq{require IkiWiki::Rcs::$config{rcs}};
107 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
111 require IkiWiki::Rcs::Stub;
114 run_hooks(checkconfig => sub { shift->() });
117 sub loadplugins () { #{{{
118 foreach my $plugin (@{$config{plugin}}) {
119 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
122 error("Failed to load plugin $mod: $@");
125 run_hooks(getopt => sub { shift->() });
126 if (grep /^-/, @ARGV) {
127 print STDERR "Unknown option: $_\n"
128 foreach grep /^-/, @ARGV;
135 print "Content-type: text/html\n\n";
136 print misctemplate("Error", "<p>Error: @_</p>");
138 log_message(error => @_);
143 return unless $config{verbose};
144 log_message(debug => @_);
148 sub log_message ($$) { #{{{
151 if ($config{syslog}) {
154 Sys::Syslog::setlogsock('unix');
155 Sys::Syslog::openlog('ikiwiki', '', 'user');
159 Sys::Syslog::syslog($type, join(" ", @_));
162 elsif (! $config{cgi}) {
170 sub possibly_foolish_untaint ($) { #{{{
172 my ($untainted)=$tainted=~/(.*)/;
176 sub basename ($) { #{{{
183 sub dirname ($) { #{{{
190 sub pagetype ($) { #{{{
193 if ($page =~ /\.([^.]+)$/) {
194 return $1 if exists $hooks{htmlize}{$1};
199 sub pagename ($) { #{{{
202 my $type=pagetype($file);
204 $page=~s/\Q.$type\E*$// if defined $type;
208 sub htmlpage ($) { #{{{
211 return $page.".html";
214 sub srcfile ($) { #{{{
217 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
218 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
219 error("internal error: $file cannot be found");
222 sub readfile ($;$) { #{{{
227 error("cannot read a symlink ($file)");
231 open (IN, $file) || error("failed to read $file: $!");
232 binmode(IN) if ($binary);
238 sub writefile ($$$;$) { #{{{
239 my $file=shift; # can include subdirs
240 my $destdir=shift; # directory to put file in
245 while (length $test) {
246 if (-l "$destdir/$test") {
247 error("cannot write to a symlink ($test)");
249 $test=dirname($test);
252 my $dir=dirname("$destdir/$file");
255 foreach my $s (split(m!/+!, $dir)) {
258 mkdir($d) || error("failed to create directory $d: $!");
263 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
264 binmode(OUT) if ($binary);
270 sub will_render ($$;$) { #{{{
275 # Important security check.
276 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
277 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
278 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
281 if (! $clear || $cleared{$page}) {
282 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
285 $renderedfiles{$page}=[$dest];
290 sub bestlink ($$) { #{{{
297 $l.="/" if length $l;
300 if (exists $links{$l}) {
303 elsif (exists $pagecase{lc $l}) {
304 return $pagecase{lc $l};
306 } while $cwd=~s!/?[^/]+$!!;
308 #print STDERR "warning: page $page, broken link: $link\n";
312 sub isinlinableimage ($) { #{{{
315 $file=~/\.(png|gif|jpg|jpeg)$/i;
318 sub pagetitle ($) { #{{{
320 $page=~s/__(\d+)__/&#$1;/g;
325 sub titlepage ($) { #{{{
328 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
332 sub cgiurl (@) { #{{{
335 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
338 sub baseurl (;$) { #{{{
341 return "$config{url}/" if ! defined $page;
344 $page=~s/[^\/]+\//..\//g;
348 sub abs2rel ($$) { #{{{
349 # Work around very innefficient behavior in File::Spec if abs2rel
350 # is passed two relative paths. It's much faster if paths are
351 # absolute! (Debian bug #376658)
356 my $ret=File::Spec->abs2rel($path, $base);
357 $ret=~s/^// if defined $ret;
361 sub displaytime ($) { #{{{
366 # strftime doesn't know about encodings, so make sure
367 # its output is properly treated as utf8
368 return decode_utf8(POSIX::strftime(
369 $config{timeformat}, localtime($time)));
372 sub htmllink ($$$;$$$) { #{{{
373 my $lpage=shift; # the page doing the linking
374 my $page=shift; # the page that will contain the link (different for inline)
376 my $noimageinline=shift; # don't turn links into inline html images
377 my $forcesubpage=shift; # force a link to a subpage
378 my $linktext=shift; # set to force the link text to something
381 if (! $forcesubpage) {
382 $bestlink=bestlink($lpage, $link);
385 $bestlink="$lpage/".lc($link);
388 $linktext=pagetitle(basename($link)) unless defined $linktext;
390 return "<span class=\"selflink\">$linktext</span>"
391 if length $bestlink && $page eq $bestlink;
393 # TODO BUG: %renderedfiles may not have it, if the linked to page
394 # was also added and isn't yet rendered! Note that this bug is
395 # masked by the bug that makes all new files be rendered twice.
396 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
397 $bestlink=htmlpage($bestlink);
399 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
400 return "<span><a href=\"".
401 cgiurl(do => "create", page => lc($link), from => $page).
402 "\">?</a>$linktext</span>"
405 $bestlink=abs2rel($bestlink, dirname($page));
407 if (! $noimageinline && isinlinableimage($bestlink)) {
408 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
410 return "<a href=\"$bestlink\">$linktext</a>";
413 sub htmlize ($$$) { #{{{
418 if (exists $hooks{htmlize}{$type}) {
419 $content=$hooks{htmlize}{$type}{call}->(
425 error("htmlization of $type not supported");
428 run_hooks(sanitize => sub {
438 sub linkify ($$$) { #{{{
439 my $lpage=shift; # the page containing the links
440 my $page=shift; # the page the link will end up on (different for inline)
443 $content =~ s{(\\?)$config{wiki_link_regexp}}{
444 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
445 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
452 sub preprocess ($$$;$) { #{{{
453 my $page=shift; # the page the data comes from
454 my $destpage=shift; # the page the data will appear in (different for inline)
462 if (length $escape) {
463 return "[[$command $params]]";
465 elsif (exists $hooks{preprocess}{$command}) {
466 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
467 # Note: preserve order of params, some plugins may
468 # consider it significant.
470 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
487 push @params, $key, $val;
490 push @params, $val, '';
493 if ($preprocessing{$page}++ > 3) {
494 # Avoid loops of preprocessed pages preprocessing
495 # other pages that preprocess them, etc.
496 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
498 my $ret=$hooks{preprocess}{$command}{call}->(
501 destpage => $destpage,
503 $preprocessing{$page}--;
507 return "[[$command $params]]";
511 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
515 sub filter ($$) { #{{{
519 run_hooks(filter => sub {
520 $content=shift->(page => $page, content => $content);
526 sub indexlink () { #{{{
527 return "<a href=\"$config{url}\">$config{wikiname}</a>";
530 sub lockwiki () { #{{{
531 # Take an exclusive lock on the wiki to prevent multiple concurrent
532 # run issues. The lock will be dropped on program exit.
533 if (! -d $config{wikistatedir}) {
534 mkdir($config{wikistatedir});
536 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
537 error ("cannot write to $config{wikistatedir}/lockfile: $!");
538 if (! flock(WIKILOCK, 2 | 4)) {
539 debug("wiki seems to be locked, waiting for lock");
540 my $wait=600; # arbitrary, but don't hang forever to
541 # prevent process pileup
543 return if flock(WIKILOCK, 2 | 4);
546 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
550 sub unlockwiki () { #{{{
554 sub loadindex () { #{{{
555 open (IN, "$config{wikistatedir}/index") || return;
557 $_=possibly_foolish_untaint($_);
562 foreach my $i (split(/ /, $_)) {
563 my ($item, $val)=split(/=/, $i, 2);
564 push @{$items{$item}}, decode_entities($val);
567 next unless exists $items{src}; # skip bad lines for now
569 my $page=pagename($items{src}[0]);
570 if (! $config{rebuild}) {
571 $pagesources{$page}=$items{src}[0];
572 $oldpagemtime{$page}=$items{mtime}[0];
573 $oldlinks{$page}=[@{$items{link}}];
574 $links{$page}=[@{$items{link}}];
575 $depends{$page}=$items{depends}[0] if exists $items{depends};
576 $renderedfiles{$page}=[@{$items{dest}}];
577 $oldrenderedfiles{$page}=[@{$items{dest}}];
578 $pagecase{lc $page}=$page;
580 $pagectime{$page}=$items{ctime}[0];
585 sub saveindex () { #{{{
586 run_hooks(savestate => sub { shift->() });
588 if (! -d $config{wikistatedir}) {
589 mkdir($config{wikistatedir});
591 open (OUT, ">$config{wikistatedir}/index") ||
592 error("cannot write to $config{wikistatedir}/index: $!");
593 foreach my $page (keys %oldpagemtime) {
594 next unless $oldpagemtime{$page};
595 my $line="mtime=$oldpagemtime{$page} ".
596 "ctime=$pagectime{$page} ".
597 "src=$pagesources{$page}";
598 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
600 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
601 if (exists $depends{$page}) {
602 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
604 print OUT $line."\n";
609 sub template_params (@) { #{{{
612 require HTML::Template;
613 return filter => sub {
614 my $text_ref = shift;
615 $$text_ref=&Encode::decode_utf8($$text_ref);
617 filename => "$config{templatedir}/$filename",
618 loop_context_vars => 1,
619 die_on_bad_params => 0,
623 sub template ($;@) { #{{{
624 HTML::Template->new(template_params(@_));
627 sub misctemplate ($$;@) { #{{{
631 my $template=template("misc.tmpl");
634 indexlink => indexlink(),
635 wikiname => $config{wikiname},
636 pagebody => $pagebody,
637 baseurl => baseurl(),
640 run_hooks(pagetemplate => sub {
641 shift->(page => "", destpage => "", template => $template);
643 return $template->output;
649 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
650 error "hook requires type, call, and id parameters";
653 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
655 $hooks{$param{type}}{$param{id}}=\%param;
658 sub run_hooks ($$) { # {{{
659 # Calls the given sub for each hook of the given type,
660 # passing it the hook function to call.
664 if (exists $hooks{$type}) {
665 foreach my $id (keys %{$hooks{$type}}) {
666 $sub->($hooks{$type}{$id}{call});
671 sub globlist_to_pagespec ($) { #{{{
672 my @globlist=split(' ', shift);
675 foreach my $glob (@globlist) {
676 if ($glob=~/^!(.*)/) {
684 my $spec=join(" or ", @spec);
686 my $skip=join(" and ", @skip);
688 $spec="$skip and ($spec)";
697 sub is_globlist ($) { #{{{
699 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
702 sub safequote ($) { #{{{
708 sub pagespec_merge ($$) { #{{{
712 return $a if $a eq $b;
714 # Support for old-style GlobLists.
715 if (is_globlist($a)) {
716 $a=globlist_to_pagespec($a);
718 if (is_globlist($b)) {
719 $b=globlist_to_pagespec($b);
722 return "($a) or ($b)";
725 sub pagespec_translate ($) { #{{{
726 # This assumes that $page is in scope in the function
727 # that evalulates the translated pagespec code.
730 # Support for old-style GlobLists.
731 if (is_globlist($spec)) {
732 $spec=globlist_to_pagespec($spec);
735 # Convert spec to perl code.
737 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
739 if (lc $word eq "and") {
742 elsif (lc $word eq "or") {
745 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
748 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
749 $code.=" match_$1(\$page, ".safequote($2).")";
752 $code.=" match_glob(\$page, ".safequote($word).")";
759 sub add_depends ($$) { #{{{
763 if (! exists $depends{$page}) {
764 $depends{$page}=$pagespec;
767 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
771 sub pagespec_match ($$) { #{{{
775 return eval pagespec_translate($spec);
778 sub match_glob ($$) { #{{{
782 # turn glob into safe regexp
783 $glob=quotemeta($glob);
787 return $page=~/^$glob$/i;
790 sub match_link ($$) { #{{{
794 my $links = $links{$page} or return undef;
795 foreach my $p (@$links) {
796 return 1 if lc $p eq $link;
801 sub match_backlink ($$) { #{{{
802 match_link(pop, pop);
805 sub match_created_before ($$) { #{{{
809 if (exists $pagectime{$testpage}) {
810 return $pagectime{$page} < $pagectime{$testpage};
817 sub match_created_after ($$) { #{{{
821 if (exists $pagectime{$testpage}) {
822 return $pagectime{$page} > $pagectime{$testpage};
829 sub match_creation_day ($$) { #{{{
830 return ((gmtime($pagectime{shift()}))[3] == shift);
833 sub match_creation_month ($$) { #{{{
834 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
837 sub match_creation_year ($$) { #{{{
838 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);