8 use open qw{:utf8 :std};
13 memoize("pagespec_translate");
15 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
16 %renderedfiles %pagesources %depends %hooks %forcerebuild};
18 sub defaultconfig () { #{{{
19 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$|\.rss$)},
20 wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
21 wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]*)\]\]/,
22 wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
25 default_pageext => "mdwn",
47 templatedir => "/usr/share/ikiwiki/templates",
48 underlaydir => "/usr/share/ikiwiki/basewiki",
52 plugin => [qw{mdwn inline htmlscrubber}],
57 sub checkconfig () { #{{{
58 # locale stuff; avoid LC_ALL since it overrides everything
59 if (defined $ENV{LC_ALL}) {
60 $ENV{LANG} = $ENV{LC_ALL};
63 if (defined $config{locale}) {
65 $ENV{LANG} = $config{locale}
66 if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
69 if ($config{w3mmode}) {
70 eval q{use Cwd q{abs_path}};
71 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
72 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
73 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
74 unless $config{cgiurl} =~ m!file:///!;
75 $config{url}="file://".$config{destdir};
78 if ($config{cgi} && ! length $config{url}) {
79 error("Must specify url to wiki with --url when using --cgi\n");
81 if ($config{rss} && ! length $config{url}) {
82 error("Must specify url to wiki with --url when using --rss\n");
85 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
86 unless exists $config{wikistatedir};
89 eval qq{require IkiWiki::Rcs::$config{rcs}};
91 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
95 require IkiWiki::Rcs::Stub;
98 run_hooks(checkconfig => sub { shift->() });
101 sub loadplugins () { #{{{
102 foreach my $plugin (@{$config{plugin}}) {
103 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
106 error("Failed to load plugin $mod: $@");
109 run_hooks(getopt => sub { shift->() });
110 if (grep /^-/, @ARGV) {
111 print STDERR "Unknown option: $_\n"
112 foreach grep /^-/, @ARGV;
119 print "Content-type: text/html\n\n";
120 print misctemplate("Error", "<p>Error: @_</p>");
126 return unless $config{verbose};
127 if (! $config{cgi}) {
135 sub possibly_foolish_untaint ($) { #{{{
137 my ($untainted)=$tainted=~/(.*)/;
141 sub basename ($) { #{{{
148 sub dirname ($) { #{{{
155 sub pagetype ($) { #{{{
158 if ($page =~ /\.([^.]+)$/) {
159 return $1 if exists $hooks{htmlize}{$1};
164 sub pagename ($) { #{{{
167 my $type=pagetype($file);
169 $page=~s/\Q.$type\E*$// if defined $type;
173 sub htmlpage ($) { #{{{
176 return $page.".html";
179 sub srcfile ($) { #{{{
182 return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
183 return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
184 error("internal error: $file cannot be found");
187 sub readfile ($;$) { #{{{
192 error("cannot read a symlink ($file)");
196 open (IN, $file) || error("failed to read $file: $!");
197 binmode(IN) if ($binary);
203 sub writefile ($$$;$) { #{{{
204 my $file=shift; # can include subdirs
205 my $destdir=shift; # directory to put file in
210 while (length $test) {
211 if (-l "$destdir/$test") {
212 error("cannot write to a symlink ($test)");
214 $test=dirname($test);
217 my $dir=dirname("$destdir/$file");
220 foreach my $s (split(m!/+!, $dir)) {
223 mkdir($d) || error("failed to create directory $d: $!");
228 open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
229 binmode(OUT) if ($binary);
234 sub bestlink ($$) { #{{{
235 # Given a page and the text of a link on the page, determine which
236 # existing page that link best points to. Prefers pages under a
237 # subdirectory with the same name as the source page, failing that
238 # goes down the directory tree to the base looking for matching
246 $l.="/" if length $l;
249 if (exists $links{$l}) {
250 #debug("for $page, \"$link\", use $l");
253 } while $cwd=~s!/?[^/]+$!!;
255 #print STDERR "warning: page $page, broken link: $link\n";
259 sub isinlinableimage ($) { #{{{
262 $file=~/\.(png|gif|jpg|jpeg)$/i;
265 sub pagetitle ($) { #{{{
267 $page=~s/__(\d+)__/&#$1;/g;
272 sub titlepage ($) { #{{{
275 $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
279 sub cgiurl (@) { #{{{
282 return $config{cgiurl}."?".join("&", map "$_=$params{$_}", keys %params);
285 sub styleurl (;$) { #{{{
288 return "$config{url}/style.css" if ! defined $page;
291 $page=~s/[^\/]+\//..\//g;
292 return $page."style.css";
295 sub abs2rel ($$) { #{{{
296 # Work around very innefficient behavior in File::Spec if abs2rel
297 # is passed two relative paths. It's much faster if paths are
303 my $ret=File::Spec->abs2rel($path, $base);
304 $ret=~s/^// if defined $ret;
308 sub htmllink ($$$;$$$) { #{{{
309 my $lpage=shift; # the page doing the linking
310 my $page=shift; # the page that will contain the link (different for inline)
312 my $noimageinline=shift; # don't turn links into inline html images
313 my $forcesubpage=shift; # force a link to a subpage
314 my $linktext=shift; # set to force the link text to something
317 if (! $forcesubpage) {
318 $bestlink=bestlink($lpage, $link);
321 $bestlink="$lpage/".lc($link);
324 $linktext=pagetitle(basename($link)) unless defined $linktext;
326 return $linktext if length $bestlink && $page eq $bestlink;
328 # TODO BUG: %renderedfiles may not have it, if the linked to page
329 # was also added and isn't yet rendered! Note that this bug is
330 # masked by the bug that makes all new files be rendered twice.
331 if (! grep { $_ eq $bestlink } values %renderedfiles) {
332 $bestlink=htmlpage($bestlink);
334 if (! grep { $_ eq $bestlink } values %renderedfiles) {
335 return "<span><a href=\"".
336 cgiurl(do => "create", page => $link, from => $page).
337 "\">?</a>$linktext</span>"
340 $bestlink=abs2rel($bestlink, dirname($page));
342 if (! $noimageinline && isinlinableimage($bestlink)) {
343 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
345 return "<a href=\"$bestlink\">$linktext</a>";
348 sub indexlink () { #{{{
349 return "<a href=\"$config{url}\">$config{wikiname}</a>";
352 sub lockwiki () { #{{{
353 # Take an exclusive lock on the wiki to prevent multiple concurrent
354 # run issues. The lock will be dropped on program exit.
355 if (! -d $config{wikistatedir}) {
356 mkdir($config{wikistatedir});
358 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
359 error ("cannot write to $config{wikistatedir}/lockfile: $!");
360 if (! flock(WIKILOCK, 2 | 4)) {
361 debug("wiki seems to be locked, waiting for lock");
362 my $wait=600; # arbitrary, but don't hang forever to
363 # prevent process pileup
365 return if flock(WIKILOCK, 2 | 4);
368 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
372 sub unlockwiki () { #{{{
376 sub loadindex () { #{{{
377 open (IN, "$config{wikistatedir}/index") || return;
379 $_=possibly_foolish_untaint($_);
383 foreach my $i (split(/ /, $_)) {
384 my ($item, $val)=split(/=/, $i, 2);
385 push @{$items{$item}}, decode_entities($val);
388 next unless exists $items{src}; # skip bad lines for now
390 my $page=pagename($items{src}[0]);
391 if (! $config{rebuild}) {
392 $pagesources{$page}=$items{src}[0];
393 $oldpagemtime{$page}=$items{mtime}[0];
394 $oldlinks{$page}=[@{$items{link}}];
395 $links{$page}=[@{$items{link}}];
396 $depends{$page}=$items{depends}[0] if exists $items{depends};
397 $renderedfiles{$page}=$items{dest}[0];
399 $pagectime{$page}=$items{ctime}[0];
404 sub saveindex () { #{{{
405 run_hooks(savestate => sub { shift->() });
407 if (! -d $config{wikistatedir}) {
408 mkdir($config{wikistatedir});
410 open (OUT, ">$config{wikistatedir}/index") ||
411 error("cannot write to $config{wikistatedir}/index: $!");
412 foreach my $page (keys %oldpagemtime) {
413 next unless $oldpagemtime{$page};
414 my $line="mtime=$oldpagemtime{$page} ".
415 "ctime=$pagectime{$page} ".
416 "src=$pagesources{$page} ".
417 "dest=$renderedfiles{$page}";
418 $line.=" link=$_" foreach @{$links{$page}};
419 if (exists $depends{$page}) {
420 $line.=" depends=".encode_entities($depends{$page}, " \t\n");
422 print OUT $line."\n";
427 sub template_params (@) { #{{{
430 require HTML::Template;
431 return filter => sub {
432 my $text_ref = shift;
433 $$text_ref=&Encode::decode_utf8($$text_ref);
435 filename => "$config{templatedir}/$filename", @_;
438 sub template ($;@) { #{{{
439 HTML::Template->new(template_params(@_));
442 sub misctemplate ($$) { #{{{
446 my $template=template("misc.tmpl");
449 indexlink => indexlink(),
450 wikiname => $config{wikiname},
451 pagebody => $pagebody,
452 styleurl => styleurl(),
453 baseurl => "$config{url}/",
455 return $template->output;
461 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
462 error "hook requires type, call, and id parameters";
465 $hooks{$param{type}}{$param{id}}=\%param;
468 sub run_hooks ($$) { # {{{
469 # Calls the given sub for each hook of the given type,
470 # passing it the hook function to call.
474 if (exists $hooks{$type}) {
475 foreach my $id (keys %{$hooks{$type}}) {
476 $sub->($hooks{$type}{$id}{call});
481 sub globlist_to_pagespec ($) { #{{{
482 my @globlist=split(' ', shift);
485 foreach my $glob (@globlist) {
486 if ($glob=~/^!(.*)/) {
494 my $spec=join(" or ", @spec);
496 my $skip=join(" and ", @skip);
498 $spec="$skip and ($spec)";
507 sub is_globlist ($) { #{{{
509 $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
512 sub safequote ($) { #{{{
518 sub pagespec_merge ($$) { #{{{
522 # Support for old-style GlobLists.
523 if (is_globlist($a)) {
524 $a=globlist_to_pagespec($a);
526 if (is_globlist($b)) {
527 $b=globlist_to_pagespec($b);
530 return "($a) or ($b)";
533 sub pagespec_translate ($) { #{{{
534 # This assumes that $page is in scope in the function
535 # that evalulates the translated pagespec code.
538 # Support for old-style GlobLists.
539 if (is_globlist($spec)) {
540 $spec=globlist_to_pagespec($spec);
543 # Convert spec to perl code.
545 while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
547 if (lc $word eq "and") {
550 elsif (lc $word eq "or") {
553 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
556 elsif ($word =~ /^(link|backlink|creation_month|creation_year|creation_day)\((.+)\)$/) {
557 $code.=" match_$1(\$page, ".safequote($2).")";
560 $code.=" match_glob(\$page, ".safequote($word).")";
567 sub pagespec_match ($$) { #{{{
571 return eval pagespec_translate($spec);
574 sub match_glob ($$) { #{{{
578 # turn glob into safe regexp
579 $glob=quotemeta($glob);
583 return $page=~/^$glob$/i;
586 sub match_link ($$) { #{{{
590 my $links = $links{$page} or return undef;
591 foreach my $p (@$links) {
592 return 1 if lc $p eq $link;
597 sub match_backlink ($$) { #{{{
598 match_link(pop, pop);
601 sub match_creation_day ($$) { #{{{
602 return ((gmtime($pagectime{shift()}))[3] == shift);
605 sub match_creation_month ($$) { #{{{
606 return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
609 sub match_creation_year ($$) { #{{{
610 return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);