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}],
72 sub checkconfig () { #{{{
73 # locale stuff; avoid LC_ALL since it overrides everything
74 if (defined $ENV{LC_ALL}) {
75 $ENV{LANG} = $ENV{LC_ALL};
78 if (defined $config{locale}) {
81 $ENV{LANG} = $config{locale}
82 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
85 if ($config{w3mmode}) {
86 eval q{use Cwd q{abs_path}};
88 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
89 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
90 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
91 unless $config{cgiurl} =~ m!file:///!;
92 $config{url}="file://".$config{destdir};
95 if ($config{cgi} && ! length $config{url}) {
96 error("Must specify url to wiki with --url when using --cgi\n");
98 if (($config{rss} || $config{atom}) && ! length $config{url}) {
99 error("Must specify url to wiki with --url when using --rss or --atom\n");
102 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
103 unless exists $config{wikistatedir};
106 eval qq{require IkiWiki::Rcs::$config{rcs}};
108 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
112 require IkiWiki::Rcs::Stub;
115 run_hooks(checkconfig => sub { shift->() });
118 sub loadplugins () { #{{{
119 foreach my $plugin (@{$config{plugin}}) {
120 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
123 error("Failed to load plugin $mod: $@");
126 run_hooks(getopt => sub { shift->() });
127 if (grep /^-/, @ARGV) {
128 print STDERR "Unknown option: $_\n"
129 foreach grep /^-/, @ARGV;
136 print "Content-type: text/html\n\n";
137 print misctemplate("Error", "<p>Error: @_</p>");
139 log_message(error => @_);
144 return unless $config{verbose};
145 log_message(debug => @_);
149 sub log_message ($$) { #{{{
152 if ($config{syslog}) {
155 Sys::Syslog::setlogsock('unix');
156 Sys::Syslog::openlog('ikiwiki', '', 'user');
160 Sys::Syslog::syslog($type, join(" ", @_));
163 elsif (! $config{cgi}) {
171 sub possibly_foolish_untaint ($) { #{{{
173 my ($untainted)=$tainted=~/(.*)/;
177 sub basename ($) { #{{{
184 sub dirname ($) { #{{{
191 sub pagetype ($) { #{{{
194 if ($page =~ /\.([^.]+)$/) {
195 return $1 if exists $hooks{htmlize}{$1};
200 sub pagename ($) { #{{{
203 my $type=pagetype($file);
205 $page=~s/\Q.$type\E*$// if defined $type;
209 sub htmlpage ($) { #{{{
212 return $page.".html";
215 sub srcfile ($) { #{{{
218 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
219 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
220 error("internal error: $file cannot be found");
223 sub readfile ($;$) { #{{{
228 error("cannot read a symlink ($file)");
232 open (IN, $file) || error("failed to read $file: $!");
233 binmode(IN) if ($binary);
239 sub writefile ($$$;$) { #{{{
240 my $file=shift; # can include subdirs
241 my $destdir=shift; # directory to put file in
246 while (length $test) {
247 if (-l "$destdir/$test") {
248 error("cannot write to a symlink ($test)");
250 $test=dirname($test);
253 my $dir=dirname("$destdir/$file");
256 foreach my $s (split(m!/+!, $dir)) {
259 mkdir($d) || error("failed to create directory $d: $!");
264 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
265 binmode(OUT) if ($binary);
271 sub will_render ($$;$) { #{{{
276 # Important security check.
277 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
278 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
279 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
282 if (! $clear || $cleared{$page}) {
283 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
286 $renderedfiles{$page}=[$dest];
291 sub bestlink ($$) { #{{{
298 $l.="/" if length $l;
301 if (exists $links{$l}) {
304 elsif (exists $pagecase{lc $l}) {
305 return $pagecase{lc $l};
307 } while $cwd=~s!/?[^/]+$!!;
309 #print STDERR "warning: page $page, broken link: $link\n";
313 sub isinlinableimage ($) { #{{{
316 $file=~/\.(png|gif|jpg|jpeg)$/i;
319 sub pagetitle ($) { #{{{
321 $page=~s/__(\d+)__/&#$1;/g;
326 sub titlepage ($) { #{{{
329 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
333 sub cgiurl (@) { #{{{
336 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
339 sub baseurl (;$) { #{{{
342 return "$config{url}/" if ! defined $page;
345 $page=~s/[^\/]+\//..\//g;
349 sub abs2rel ($$) { #{{{
350 # Work around very innefficient behavior in File::Spec if abs2rel
351 # is passed two relative paths. It's much faster if paths are
352 # absolute! (Debian bug #376658)
357 my $ret=File::Spec->abs2rel($path, $base);
358 $ret=~s/^// if defined $ret;
362 sub displaytime ($) { #{{{
367 # strftime doesn't know about encodings, so make sure
368 # its output is properly treated as utf8
369 return decode_utf8(POSIX::strftime(
370 $config{timeformat}, localtime($time)));
373 sub htmllink ($$$;$$$) { #{{{
374 my $lpage=shift; # the page doing the linking
375 my $page=shift; # the page that will contain the link (different for inline)
377 my $noimageinline=shift; # don't turn links into inline html images
378 my $forcesubpage=shift; # force a link to a subpage
379 my $linktext=shift; # set to force the link text to something
382 if (! $forcesubpage) {
383 $bestlink=bestlink($lpage, $link);
386 $bestlink="$lpage/".lc($link);
389 $linktext=pagetitle(basename($link)) unless defined $linktext;
391 return "<span class=\"selflink\">$linktext</span>"
392 if length $bestlink && $page eq $bestlink;
394 # TODO BUG: %renderedfiles may not have it, if the linked to page
395 # was also added and isn't yet rendered! Note that this bug is
396 # masked by the bug that makes all new files be rendered twice.
397 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
398 $bestlink=htmlpage($bestlink);
400 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
401 return "<span><a href=\"".
402 cgiurl(do => "create", page => lc($link), from => $page).
403 "\">?</a>$linktext</span>"
406 $bestlink=abs2rel($bestlink, dirname($page));
408 if (! $noimageinline && isinlinableimage($bestlink)) {
409 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
411 return "<a href=\"$bestlink\">$linktext</a>";
414 sub htmlize ($$$) { #{{{
419 if (exists $hooks{htmlize}{$type}) {
420 $content=$hooks{htmlize}{$type}{call}->(
426 error("htmlization of $type not supported");
429 run_hooks(sanitize => sub {
439 sub linkify ($$$) { #{{{
440 my $lpage=shift; # the page containing the links
441 my $page=shift; # the page the link will end up on (different for inline)
444 $content =~ s{(\\?)$config{wiki_link_regexp}}{
445 $2 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, titlepage($3), 0, 0, pagetitle($2)))
446 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, titlepage($3)))
453 sub preprocess ($$$;$) { #{{{
454 my $page=shift; # the page the data comes from
455 my $destpage=shift; # the page the data will appear in (different for inline)
463 if (length $escape) {
464 return "[[$command $params]]";
466 elsif (exists $hooks{preprocess}{$command}) {
467 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
468 # Note: preserve order of params, some plugins may
469 # consider it significant.
471 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
488 push @params, $key, $val;
491 push @params, $val, '';
494 if ($preprocessing{$page}++ > 3) {
495 # Avoid loops of preprocessed pages preprocessing
496 # other pages that preprocess them, etc.
497 return "[[$command preprocessing loop detected on $page at depth $preprocessing{$page}]]";
499 my $ret=$hooks{preprocess}{$command}{call}->(
502 destpage => $destpage,
504 $preprocessing{$page}--;
508 return "[[$command $params]]";
512 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
516 sub filter ($$) { #{{{
520 run_hooks(filter => sub {
521 $content=shift->(page => $page, content => $content);
527 sub indexlink () { #{{{
528 return "<a href=\"$config{url}\">$config{wikiname}</a>";
531 sub lockwiki () { #{{{
532 # Take an exclusive lock on the wiki to prevent multiple concurrent
533 # run issues. The lock will be dropped on program exit.
534 if (! -d $config{wikistatedir}) {
535 mkdir($config{wikistatedir});
537 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
538 error ("cannot write to $config{wikistatedir}/lockfile: $!");
539 if (! flock(WIKILOCK, 2 | 4)) {
540 debug("wiki seems to be locked, waiting for lock");
541 my $wait=600; # arbitrary, but don't hang forever to
542 # prevent process pileup
544 return if flock(WIKILOCK, 2 | 4);
547 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
551 sub unlockwiki () { #{{{
555 sub loadindex () { #{{{
556 open (IN, "$config{wikistatedir}/index") || return;
558 $_=possibly_foolish_untaint($_);
563 foreach my $i (split(/ /, $_)) {
564 my ($item, $val)=split(/=/, $i, 2);
565 push @{$items{$item}}, decode_entities($val);
568 next unless exists $items{src}; # skip bad lines for now
570 my $page=pagename($items{src}[0]);
571 if (! $config{rebuild}) {
572 $pagesources{$page}=$items{src}[0];
573 $oldpagemtime{$page}=$items{mtime}[0];
574 $oldlinks{$page}=[@{$items{link}}];
575 $links{$page}=[@{$items{link}}];
576 $depends{$page}=$items{depends}[0] if exists $items{depends};
577 $renderedfiles{$page}=[@{$items{dest}}];
578 $oldrenderedfiles{$page}=[@{$items{dest}}];
579 $pagecase{lc $page}=$page;
581 $pagectime{$page}=$items{ctime}[0];
586 sub saveindex () { #{{{
587 run_hooks(savestate => sub { shift->() });
589 if (! -d $config{wikistatedir}) {
590 mkdir($config{wikistatedir});
592 open (OUT, ">$config{wikistatedir}/index") ||
593 error("cannot write to $config{wikistatedir}/index: $!");
594 foreach my $page (keys %oldpagemtime) {
595 next unless $oldpagemtime{$page};
596 my $line="mtime=$oldpagemtime{$page} ".
597 "ctime=$pagectime{$page} ".
598 "src=$pagesources{$page}";
599 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
601 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
602 if (exists $depends{$page}) {
603 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
605 print OUT $line."\n";
610 sub template_params (@) { #{{{
613 require HTML::Template;
614 return filter => sub {
615 my $text_ref = shift;
616 $$text_ref=&Encode::decode_utf8($$text_ref);
618 filename => "$config{templatedir}/$filename",
619 loop_context_vars => 1,
620 die_on_bad_params => 0,
624 sub template ($;@) { #{{{
625 HTML::Template->new(template_params(@_));
628 sub misctemplate ($$;@) { #{{{
632 my $template=template("misc.tmpl");
635 indexlink => indexlink(),
636 wikiname => $config{wikiname},
637 pagebody => $pagebody,
638 baseurl => baseurl(),
641 run_hooks(pagetemplate => sub {
642 shift->(page => "", destpage => "", template => $template);
644 return $template->output;
650 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
651 error "hook requires type, call, and id parameters";
654 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
656 $hooks{$param{type}}{$param{id}}=\%param;
659 sub run_hooks ($$) { # {{{
660 # Calls the given sub for each hook of the given type,
661 # passing it the hook function to call.
665 if (exists $hooks{$type}) {
667 foreach my $id (keys %{$hooks{$type}}) {
668 if ($hooks{$type}{$id}{last}) {
672 $sub->($hooks{$type}{$id}{call});
674 foreach my $id (@deferred) {
675 $sub->($hooks{$type}{$id}{call});
680 sub globlist_to_pagespec ($) { #{{{
681 my @globlist=split(' ', shift);
684 foreach my $glob (@globlist) {
685 if ($glob=~/^!(.*)/) {
693 my $spec=join(" or ", @spec);
695 my $skip=join(" and ", @skip);
697 $spec="$skip and ($spec)";
706 sub is_globlist ($) { #{{{
708 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
711 sub safequote ($) { #{{{
717 sub pagespec_merge ($$) { #{{{
721 return $a if $a eq $b;
723 # Support for old-style GlobLists.
724 if (is_globlist($a)) {
725 $a=globlist_to_pagespec($a);
727 if (is_globlist($b)) {
728 $b=globlist_to_pagespec($b);
731 return "($a) or ($b)";
734 sub pagespec_translate ($) { #{{{
735 # This assumes that $page is in scope in the function
736 # that evalulates the translated pagespec code.
739 # Support for old-style GlobLists.
740 if (is_globlist($spec)) {
741 $spec=globlist_to_pagespec($spec);
744 # Convert spec to perl code.
746 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
748 if (lc $word eq "and") {
751 elsif (lc $word eq "or") {
754 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
757 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
758 $code.=" match_$1(\$page, ".safequote($2).")";
761 $code.=" match_glob(\$page, ".safequote($word).")";
768 sub add_depends ($$) { #{{{
772 if (! exists $depends{$page}) {
773 $depends{$page}=$pagespec;
776 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
780 sub pagespec_match ($$) { #{{{
784 return eval pagespec_translate($spec);
787 sub match_glob ($$) { #{{{
791 # turn glob into safe regexp
792 $glob=quotemeta($glob);
796 return $page=~/^$glob$/i;
799 sub match_link ($$) { #{{{
803 my $links = $links{$page} or return undef;
804 foreach my $p (@$links) {
805 return 1 if lc $p eq $link;
810 sub match_backlink ($$) { #{{{
811 match_link(pop, pop);
814 sub match_created_before ($$) { #{{{
818 if (exists $pagectime{$testpage}) {
819 return $pagectime{$page} < $pagectime{$testpage};
826 sub match_created_after ($$) { #{{{
830 if (exists $pagectime{$testpage}) {
831 return $pagectime{$page} > $pagectime{$testpage};
838 sub match_creation_day ($$) { #{{{
839 return ((gmtime($pagectime{shift()}))[3] == shift);
842 sub match_creation_month ($$) { #{{{
843 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
846 sub match_creation_year ($$) { #{{{
847 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);