8 use open qw{:utf8 :std};
10 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime %pagecase
11 %renderedfiles %oldrenderedfiles %pagesources %depends %hooks
12 %forcerebuild $gettext_obj};
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 gettext
18 %config %links %renderedfiles %pagesources);
19 our $VERSION = 1.02; # plugin interface version, next is ikiwiki version
20 our $version="1.45";my $installdir="/usr";
24 memoize("pagespec_translate");
25 memoize("file_pruned");
27 sub defaultconfig () { #{{{
28 wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
29 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
30 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
31 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
32 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
33 web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
37 default_pageext => "mdwn",
57 gitorigin_branch => "origin",
58 gitmaster_branch => "master",
62 templatedir => "$installdir/share/ikiwiki/templates",
63 underlaydir => "$installdir/share/ikiwiki/basewiki",
67 plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
68 lockedit conditional}],
76 sub checkconfig () { #{{{
77 # locale stuff; avoid LC_ALL since it overrides everything
78 if (defined $ENV{LC_ALL}) {
79 $ENV{LANG} = $ENV{LC_ALL};
82 if (defined $config{locale}) {
85 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
86 $ENV{LANG}=$config{locale};
91 if ($config{w3mmode}) {
92 eval q{use Cwd q{abs_path}};
94 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
95 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
96 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
97 unless $config{cgiurl} =~ m!file:///!;
98 $config{url}="file://".$config{destdir};
101 if ($config{cgi} && ! length $config{url}) {
102 error(gettext("Must specify url to wiki with --url when using --cgi"));
105 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
106 unless exists $config{wikistatedir};
109 eval qq{require IkiWiki::Rcs::$config{rcs}};
111 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
115 require IkiWiki::Rcs::Stub;
118 run_hooks(checkconfig => sub { shift->() });
121 sub loadplugins () { #{{{
122 loadplugin($_) foreach @{$config{plugin}};
124 run_hooks(getopt => sub { shift->() });
125 if (grep /^-/, @ARGV) {
126 print STDERR "Unknown option: $_\n"
127 foreach grep /^-/, @ARGV;
132 sub loadplugin ($) { #{{{
135 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
137 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
140 error("Failed to load plugin $mod: $@");
144 sub error ($;$) { #{{{
148 print "Content-type: text/html\n\n";
149 print misctemplate(gettext("Error"),
150 "<p>".gettext("Error").": $message</p>");
152 log_message(debug => $message) if $config{syslog};
153 if (defined $cleaner) {
160 return unless $config{verbose};
161 log_message(debug => @_);
165 sub log_message ($$) { #{{{
168 if ($config{syslog}) {
171 Sys::Syslog::setlogsock('unix');
172 Sys::Syslog::openlog('ikiwiki', '', 'user');
176 Sys::Syslog::syslog($type, "%s", join(" ", @_));
179 elsif (! $config{cgi}) {
187 sub possibly_foolish_untaint ($) { #{{{
189 my ($untainted)=$tainted=~/(.*)/;
193 sub basename ($) { #{{{
200 sub dirname ($) { #{{{
207 sub pagetype ($) { #{{{
210 if ($page =~ /\.([^.]+)$/) {
211 return $1 if exists $hooks{htmlize}{$1};
216 sub pagename ($) { #{{{
219 my $type=pagetype($file);
221 $page=~s/\Q.$type\E*$// if defined $type;
225 sub htmlpage ($) { #{{{
228 return $page.".html";
231 sub srcfile ($) { #{{{
234 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
235 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
236 error("internal error: $file cannot be found");
239 sub readfile ($;$$) { #{{{
245 error("cannot read a symlink ($file)");
249 open (IN, $file) || error("failed to read $file: $!");
250 binmode(IN) if ($binary);
251 return \*IN if $wantfd;
253 close IN || error("failed to read $file: $!");
257 sub writefile ($$$;$$) { #{{{
258 my $file=shift; # can include subdirs
259 my $destdir=shift; # directory to put file in
265 while (length $test) {
266 if (-l "$destdir/$test") {
267 error("cannot write to a symlink ($test)");
269 $test=dirname($test);
271 my $newfile="$destdir/$file.ikiwiki-new";
273 error("cannot write to a symlink ($newfile)");
276 my $dir=dirname($newfile);
279 foreach my $s (split(m!/+!, $dir)) {
282 mkdir($d) || error("failed to create directory $d: $!");
287 my $cleanup = sub { unlink($newfile) };
288 open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
289 binmode(OUT) if ($binary);
291 $writer->(\*OUT, $cleanup);
294 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
296 close OUT || error("failed saving $newfile: $!", $cleanup);
297 rename($newfile, "$destdir/$file") ||
298 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
302 sub will_render ($$;$) { #{{{
307 # Important security check.
308 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
309 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
310 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
313 if (! $clear || $cleared{$page}) {
314 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
317 $renderedfiles{$page}=[$dest];
322 sub bestlink ($$) { #{{{
327 if ($link=~s/^\/+//) {
334 $l.="/" if length $l;
337 if (exists $links{$l}) {
340 elsif (exists $pagecase{lc $l}) {
341 return $pagecase{lc $l};
343 } while $cwd=~s!/?[^/]+$!!;
345 if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
346 return "$config{userdir}/".lc($link);
349 #print STDERR "warning: page $page, broken link: $link\n";
353 sub isinlinableimage ($) { #{{{
356 $file=~/\.(png|gif|jpg|jpeg)$/i;
359 sub pagetitle ($;$) { #{{{
364 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
367 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
373 sub titlepage ($) { #{{{
375 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
379 sub linkpage ($) { #{{{
381 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
385 sub cgiurl (@) { #{{{
388 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
391 sub baseurl (;$) { #{{{
394 return "$config{url}/" if ! defined $page;
397 $page=~s/[^\/]+\//..\//g;
401 sub abs2rel ($$) { #{{{
402 # Work around very innefficient behavior in File::Spec if abs2rel
403 # is passed two relative paths. It's much faster if paths are
404 # absolute! (Debian bug #376658; fixed in debian unstable now)
409 my $ret=File::Spec->abs2rel($path, $base);
410 $ret=~s/^// if defined $ret;
414 sub displaytime ($) { #{{{
419 # strftime doesn't know about encodings, so make sure
420 # its output is properly treated as utf8
421 return decode_utf8(POSIX::strftime(
422 $config{timeformat}, localtime($time)));
425 sub htmllink ($$$;@) { #{{{
426 my $lpage=shift; # the page doing the linking
427 my $page=shift; # the page that will contain the link (different for inline)
432 if (! $opts{forcesubpage}) {
433 $bestlink=bestlink($lpage, $link);
436 $bestlink="$lpage/".lc($link);
440 if (defined $opts{linktext}) {
441 $linktext=$opts{linktext};
444 $linktext=pagetitle(basename($link));
447 return "<span class=\"selflink\">$linktext</span>"
448 if length $bestlink && $page eq $bestlink;
450 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
451 $bestlink=htmlpage($bestlink);
453 if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
454 return $linktext unless length $config{cgiurl};
455 return "<span><a href=\"".
456 cgiurl(do => "create", page => lc($link), from => $page).
457 "\">?</a>$linktext</span>"
460 $bestlink=abs2rel($bestlink, dirname($page));
462 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
463 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
466 if (defined $opts{anchor}) {
467 $bestlink.="#".$opts{anchor};
470 return "<a href=\"$bestlink\">$linktext</a>";
473 sub htmlize ($$$) { #{{{
478 if (exists $hooks{htmlize}{$type}) {
479 $content=$hooks{htmlize}{$type}{call}->(
485 error("htmlization of $type not supported");
488 run_hooks(sanitize => sub {
498 sub linkify ($$$) { #{{{
499 my $lpage=shift; # the page containing the links
500 my $page=shift; # the page the link will end up on (different for inline)
503 $content =~ s{(\\?)$config{wiki_link_regexp}}{
505 ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4, linktext => pagetitle($2)))
506 : ( $1 ? "[[$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4))
513 our $preprocess_preview=0;
514 sub preprocess ($$$;$$) { #{{{
515 my $page=shift; # the page the data comes from
516 my $destpage=shift; # the page the data will appear in (different for inline)
521 # Using local because it needs to be set within any nested calls
523 local $preprocess_preview=$preview if defined $preview;
529 if (length $escape) {
530 return "[[$command $params]]";
532 elsif (exists $hooks{preprocess}{$command}) {
533 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
534 # Note: preserve order of params, some plugins may
535 # consider it significant.
537 while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
554 push @params, $key, $val;
557 push @params, $val, '';
560 if ($preprocessing{$page}++ > 3) {
561 # Avoid loops of preprocessed pages preprocessing
562 # other pages that preprocess them, etc.
563 #translators: The first parameter is a
564 #translators: preprocessor directive name,
565 #translators: the second a page name, the
566 #translators: third a number.
567 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
568 $command, $page, $preprocessing{$page}).
571 my $ret=$hooks{preprocess}{$command}{call}->(
574 destpage => $destpage,
575 preview => $preprocess_preview,
577 $preprocessing{$page}--;
581 return "[[$command $params]]";
585 $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
589 sub filter ($$) { #{{{
593 run_hooks(filter => sub {
594 $content=shift->(page => $page, content => $content);
600 sub indexlink () { #{{{
601 return "<a href=\"$config{url}\">$config{wikiname}</a>";
604 sub lockwiki () { #{{{
605 # Take an exclusive lock on the wiki to prevent multiple concurrent
606 # run issues. The lock will be dropped on program exit.
607 if (! -d $config{wikistatedir}) {
608 mkdir($config{wikistatedir});
610 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
611 error ("cannot write to $config{wikistatedir}/lockfile: $!");
612 if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
613 debug("wiki seems to be locked, waiting for lock");
614 my $wait=600; # arbitrary, but don't hang forever to
615 # prevent process pileup
617 return if flock(WIKILOCK, 2 | 4);
620 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
624 sub unlockwiki () { #{{{
628 sub commit_hook_enabled () { #{{{
629 open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
630 error ("cannot write to $config{wikistatedir}/commitlock: $!");
631 if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
639 sub disable_commit_hook () { #{{{
640 open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
641 error ("cannot write to $config{wikistatedir}/commitlock: $!");
642 if (! flock(COMMITLOCK, 2)) { # LOCK_EX
643 error("failed to get commit lock");
647 sub enable_commit_hook () { #{{{
651 sub loadindex () { #{{{
652 open (IN, "$config{wikistatedir}/index") || return;
654 $_=possibly_foolish_untaint($_);
659 foreach my $i (split(/ /, $_)) {
660 my ($item, $val)=split(/=/, $i, 2);
661 push @{$items{$item}}, decode_entities($val);
664 next unless exists $items{src}; # skip bad lines for now
666 my $page=pagename($items{src}[0]);
667 if (! $config{rebuild}) {
668 $pagesources{$page}=$items{src}[0];
669 $oldpagemtime{$page}=$items{mtime}[0];
670 $oldlinks{$page}=[@{$items{link}}];
671 $links{$page}=[@{$items{link}}];
672 $depends{$page}=$items{depends}[0] if exists $items{depends};
673 $renderedfiles{$page}=[@{$items{dest}}];
674 $oldrenderedfiles{$page}=[@{$items{dest}}];
675 $pagecase{lc $page}=$page;
677 $pagectime{$page}=$items{ctime}[0];
682 sub saveindex () { #{{{
683 run_hooks(savestate => sub { shift->() });
685 if (! -d $config{wikistatedir}) {
686 mkdir($config{wikistatedir});
688 my $newfile="$config{wikistatedir}/index.new";
689 my $cleanup = sub { unlink($newfile) };
690 open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
691 foreach my $page (keys %oldpagemtime) {
692 next unless $oldpagemtime{$page};
693 my $line="mtime=$oldpagemtime{$page} ".
694 "ctime=$pagectime{$page} ".
695 "src=$pagesources{$page}";
696 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
698 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
699 if (exists $depends{$page}) {
700 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
702 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
704 close OUT || error("failed saving to $newfile: $!", $cleanup);
705 rename($newfile, "$config{wikistatedir}/index") ||
706 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
709 sub template_file ($) { #{{{
712 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
713 return "$dir/$template" if -e "$dir/$template";
718 sub template_params (@) { #{{{
719 my $filename=template_file(shift);
721 if (! defined $filename) {
726 require HTML::Template;
729 my $text_ref = shift;
730 $$text_ref=&Encode::decode_utf8($$text_ref);
732 filename => $filename,
733 loop_context_vars => 1,
734 die_on_bad_params => 0,
737 return wantarray ? @ret : {@ret};
740 sub template ($;@) { #{{{
741 HTML::Template->new(template_params(@_));
744 sub misctemplate ($$;@) { #{{{
748 my $template=template("misc.tmpl");
751 indexlink => indexlink(),
752 wikiname => $config{wikiname},
753 pagebody => $pagebody,
754 baseurl => baseurl(),
757 run_hooks(pagetemplate => sub {
758 shift->(page => "", destpage => "", template => $template);
760 return $template->output;
766 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
767 error "hook requires type, call, and id parameters";
770 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
772 $hooks{$param{type}}{$param{id}}=\%param;
775 sub run_hooks ($$) { # {{{
776 # Calls the given sub for each hook of the given type,
777 # passing it the hook function to call.
781 if (exists $hooks{$type}) {
783 foreach my $id (keys %{$hooks{$type}}) {
784 if ($hooks{$type}{$id}{last}) {
788 $sub->($hooks{$type}{$id}{call});
790 foreach my $id (@deferred) {
791 $sub->($hooks{$type}{$id}{call});
796 sub globlist_to_pagespec ($) { #{{{
797 my @globlist=split(' ', shift);
800 foreach my $glob (@globlist) {
801 if ($glob=~/^!(.*)/) {
809 my $spec=join(" or ", @spec);
811 my $skip=join(" and ", @skip);
813 $spec="$skip and ($spec)";
822 sub is_globlist ($) { #{{{
824 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
827 sub safequote ($) { #{{{
833 sub add_depends ($$) { #{{{
837 if (! exists $depends{$page}) {
838 $depends{$page}=$pagespec;
841 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
845 sub file_pruned ($$) { #{{{
847 my $file=File::Spec->canonpath(shift);
848 my $base=File::Spec->canonpath(shift);
849 $file=~s#^\Q$base\E/*##;
851 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
856 # Only use gettext in the rare cases it's needed.
857 if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
858 if (! $gettext_obj) {
860 use Locale::gettext q{textdomain};
861 Locale::gettext->domain('ikiwiki')
869 return $gettext_obj->get(shift);
876 sub pagespec_merge ($$) { #{{{
880 return $a if $a eq $b;
882 # Support for old-style GlobLists.
883 if (is_globlist($a)) {
884 $a=globlist_to_pagespec($a);
886 if (is_globlist($b)) {
887 $b=globlist_to_pagespec($b);
890 return "($a) or ($b)";
893 sub pagespec_translate ($) { #{{{
894 # This assumes that $page is in scope in the function
895 # that evalulates the translated pagespec code.
898 # Support for old-style GlobLists.
899 if (is_globlist($spec)) {
900 $spec=globlist_to_pagespec($spec);
903 # Convert spec to perl code.
905 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
907 if (lc $word eq "and") {
910 elsif (lc $word eq "or") {
913 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
916 elsif ($word =~ /^(\w+)\((.*)\)$/) {
917 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
918 $code.=" IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).")";
925 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
932 sub pagespec_match ($$;$) { #{{{
937 return eval pagespec_translate($spec);
940 package IkiWiki::PageSpec;
942 sub match_glob ($$$) { #{{{
946 if (! defined $from){
951 if ($glob =~ m!^\./!) {
954 $glob="$from/$glob" if length $from;
957 # turn glob into safe regexp
958 $glob=quotemeta($glob);
962 return $page=~/^$glob$/i;
965 sub match_link ($$) { #{{{
969 my $links = $IkiWiki::links{$page} or return undef;
970 foreach my $p (@$links) {
971 return 1 if lc $p eq $link;
976 sub match_backlink ($$) { #{{{
977 match_link(pop, pop);
980 sub match_created_before ($$) { #{{{
984 if (exists $IkiWiki::pagectime{$testpage}) {
985 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
992 sub match_created_after ($$) { #{{{
996 if (exists $IkiWiki::pagectime{$testpage}) {
997 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1004 sub match_creation_day ($$) { #{{{
1005 return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1008 sub match_creation_month ($$) { #{{{
1009 return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1012 sub match_creation_year ($$) { #{{{
1013 return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);