]> sipb.mit.edu Git - ikiwiki.git/blob - ikiwiki
Implemented --underlaydir, and moved files provided by underlay out of doc
[ikiwiki.git] / ikiwiki
1 #!/usr/bin/perl -T
2 $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
3
4 package IkiWiki;
5 use warnings;
6 use strict;
7 use File::Spec;
8 use HTML::Template;
9 use lib '.'; # For use without installation, removed by Makefile.
10
11 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
12             %renderedfiles %pagesources %inlinepages};
13
14 sub usage () { #{{{
15         die "usage: ikiwiki [options] source dest\n";
16 } #}}}
17
18 sub getconfig () { #{{{
19         if (! exists $ENV{WRAPPED_OPTIONS}) {
20                 %config=(
21                         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$|\.rss$)},
22                         wiki_link_regexp => qr/\[\[(?:([^\s\]\|]+)\|)?([^\s\]]+)\]\]/,
23                         wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]+)\]\]/,
24                         wiki_file_regexp => qr/(^[-A-Za-z0-9_.:\/+]+$)/,
25                         verbose => 0,
26                         wikiname => "wiki",
27                         default_pageext => ".mdwn",
28                         cgi => 0,
29                         svn => 1,
30                         url => '',
31                         cgiurl => '',
32                         historyurl => '',
33                         diffurl => '',
34                         anonok => 0,
35                         rss => 0,
36                         rebuild => 0,
37                         refresh => 0,
38                         getctime => 0,
39                         wrapper => undef,
40                         wrappermode => undef,
41                         srcdir => undef,
42                         destdir => undef,
43                         templatedir => "/usr/share/ikiwiki/templates",
44                         underlaydir => "/usr/share/ikiwiki/basewiki",
45                         setup => undef,
46                         adminuser => undef,
47                 );
48
49                 eval q{use Getopt::Long};
50                 GetOptions(
51                         "setup|s=s" => \$config{setup},
52                         "wikiname=s" => \$config{wikiname},
53                         "verbose|v!" => \$config{verbose},
54                         "rebuild!" => \$config{rebuild},
55                         "refresh!" => \$config{refresh},
56                         "getctime" => \$config{getctime},
57                         "wrappermode=i" => \$config{wrappermode},
58                         "svn!" => \$config{svn},
59                         "anonok!" => \$config{anonok},
60                         "rss!" => \$config{rss},
61                         "cgi!" => \$config{cgi},
62                         "url=s" => \$config{url},
63                         "cgiurl=s" => \$config{cgiurl},
64                         "historyurl=s" => \$config{historyurl},
65                         "diffurl=s" => \$config{diffurl},
66                         "exclude=s@" => sub {
67                                 $config{wiki_file_prune_regexp}=qr/$config{wiki_file_prune_regexp}|$_[1]/;
68                         },
69                         "adminuser=s@" => sub {
70                                 push @{$config{adminuser}}, $_[1]
71                         },
72                         "templatedir=s" => sub {
73                                 $config{templatedir}=possibly_foolish_untaint($_[1])
74                         },
75                         "underlaydir=s" => sub {
76                                 $config{underlaydir}=possibly_foolish_untaint($_[1])
77                         },
78                         "wrapper:s" => sub {
79                                 $config{wrapper}=$_[1] ? $_[1] : "ikiwiki-wrap"
80                         },
81                 ) || usage();
82
83                 if (! $config{setup}) {
84                         usage() unless @ARGV == 2;
85                         $config{srcdir} = possibly_foolish_untaint(shift @ARGV);
86                         $config{destdir} = possibly_foolish_untaint(shift @ARGV);
87                         checkconfig();
88                 }
89         }
90         else {
91                 # wrapper passes a full config structure in the environment
92                 # variable
93                 eval possibly_foolish_untaint($ENV{WRAPPED_OPTIONS});
94                 checkconfig();
95         }
96 } #}}}
97
98 sub checkconfig () { #{{{
99         if ($config{cgi} && ! length $config{url}) {
100                 error("Must specify url to wiki with --url when using --cgi\n");
101         }
102         if ($config{rss} && ! length $config{url}) {
103                 error("Must specify url to wiki with --url when using --rss\n");
104         }
105         
106         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
107                 unless exists $config{wikistatedir};
108         
109         if ($config{svn}) {
110                 require IkiWiki::Rcs::SVN;
111                 $config{rcs}=1;
112         }
113         else {
114                 require IkiWiki::Rcs::Stub;
115                 $config{rcs}=0;
116         }
117 } #}}}
118
119 sub error ($) { #{{{
120         if ($config{cgi}) {
121                 print "Content-type: text/html\n\n";
122                 print misctemplate("Error", "<p>Error: @_</p>");
123         }
124         die @_;
125 } #}}}
126
127 sub possibly_foolish_untaint ($) { #{{{
128         my $tainted=shift;
129         my ($untainted)=$tainted=~/(.*)/;
130         return $untainted;
131 } #}}}
132
133 sub debug ($) { #{{{
134         return unless $config{verbose};
135         if (! $config{cgi}) {
136                 print "@_\n";
137         }
138         else {
139                 print STDERR "@_\n";
140         }
141 } #}}}
142
143 sub basename ($) { #{{{
144         my $file=shift;
145
146         $file=~s!.*/!!;
147         return $file;
148 } #}}}
149
150 sub dirname ($) { #{{{
151         my $file=shift;
152
153         $file=~s!/?[^/]+$!!;
154         return $file;
155 } #}}}
156
157 sub pagetype ($) { #{{{
158         my $page=shift;
159         
160         if ($page =~ /\.mdwn$/) {
161                 return ".mdwn";
162         }
163         else {
164                 return "unknown";
165         }
166 } #}}}
167
168 sub pagename ($) { #{{{
169         my $file=shift;
170
171         my $type=pagetype($file);
172         my $page=$file;
173         $page=~s/\Q$type\E*$// unless $type eq 'unknown';
174         return $page;
175 } #}}}
176
177 sub htmlpage ($) { #{{{
178         my $page=shift;
179
180         return $page.".html";
181 } #}}}
182
183 sub srcfile ($) { #{{{
184         my $file=shift;
185
186         return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
187         return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
188         error("internal error: $file cannot be found");
189 } #}}}
190
191 sub readfile ($) { #{{{
192         my $file=shift;
193
194         if (-l $file) {
195                 error("cannot read a symlink ($file)");
196         }
197         
198         local $/=undef;
199         open (IN, "$file") || error("failed to read $file: $!");
200         my $ret=<IN>;
201         close IN;
202         return $ret;
203 } #}}}
204
205 sub writefile ($$) { #{{{
206         my $file=shift;
207         my $content=shift;
208         
209         if (-l $file) {
210                 error("cannot write to a symlink ($file)");
211         }
212
213         my $dir=dirname($file);
214         if (! -d $dir) {
215                 my $d="";
216                 foreach my $s (split(m!/+!, $dir)) {
217                         $d.="$s/";
218                         if (! -d $d) {
219                                 mkdir($d) || error("failed to create directory $d: $!");
220                         }
221                 }
222         }
223         
224         open (OUT, ">$file") || error("failed to write $file: $!");
225         print OUT $content;
226         close OUT;
227 } #}}}
228
229 sub bestlink ($$) { #{{{
230         # Given a page and the text of a link on the page, determine which
231         # existing page that link best points to. Prefers pages under a
232         # subdirectory with the same name as the source page, failing that
233         # goes down the directory tree to the base looking for matching
234         # pages.
235         my $page=shift;
236         my $link=lc(shift);
237         
238         my $cwd=$page;
239         do {
240                 my $l=$cwd;
241                 $l.="/" if length $l;
242                 $l.=$link;
243
244                 if (exists $links{$l}) {
245                         #debug("for $page, \"$link\", use $l");
246                         return $l;
247                 }
248         } while $cwd=~s!/?[^/]+$!!;
249
250         #print STDERR "warning: page $page, broken link: $link\n";
251         return "";
252 } #}}}
253
254 sub isinlinableimage ($) { #{{{
255         my $file=shift;
256         
257         $file=~/\.(png|gif|jpg|jpeg)$/i;
258 } #}}}
259
260 sub pagetitle ($) { #{{{
261         my $page=shift;
262         $page=~s/__(\d+)__/&#$1;/g;
263         $page=~y/_/ /;
264         return $page;
265 } #}}}
266
267 sub titlepage ($) { #{{{
268         my $title=shift;
269         $title=~y/ /_/;
270         $title=~s/([^-A-Za-z0-9_:+\/.])/"__".ord($1)."__"/eg;
271         return $title;
272 } #}}}
273
274 sub cgiurl (@) { #{{{
275         my %params=@_;
276
277         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
278 } #}}}
279
280 sub styleurl (;$) { #{{{
281         my $page=shift;
282
283         return "$config{url}/style.css" if ! defined $page;
284         
285         $page=~s/[^\/]+$//;
286         $page=~s/[^\/]+\//..\//g;
287         return $page."style.css";
288 } #}}}
289
290 sub htmllink ($$;$$$) { #{{{
291         my $page=shift;
292         my $link=shift;
293         my $noimageinline=shift; # don't turn links into inline html images
294         my $forcesubpage=shift; # force a link to a subpage
295         my $linktext=shift; # set to force the link text to something
296
297         my $bestlink;
298         if (! $forcesubpage) {
299                 $bestlink=bestlink($page, $link);
300         }
301         else {
302                 $bestlink="$page/".lc($link);
303         }
304
305         $linktext=pagetitle(basename($link)) unless defined $linktext;
306         
307         return $linktext if length $bestlink && $page eq $bestlink;
308         
309         # TODO BUG: %renderedfiles may not have it, if the linked to page
310         # was also added and isn't yet rendered! Note that this bug is
311         # masked by the bug mentioned below that makes all new files
312         # be rendered twice.
313         if (! grep { $_ eq $bestlink } values %renderedfiles) {
314                 $bestlink=htmlpage($bestlink);
315         }
316         if (! grep { $_ eq $bestlink } values %renderedfiles) {
317                 return "<span><a href=\"".
318                         cgiurl(do => "create", page => $link, from =>$page).
319                         "\">?</a>$linktext</span>"
320         }
321         
322         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
323         
324         if (! $noimageinline && isinlinableimage($bestlink)) {
325                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
326         }
327         return "<a href=\"$bestlink\">$linktext</a>";
328 } #}}}
329
330 sub indexlink () { #{{{
331         return "<a href=\"$config{url}\">$config{wikiname}</a>";
332 } #}}}
333
334 sub lockwiki () { #{{{
335         # Take an exclusive lock on the wiki to prevent multiple concurrent
336         # run issues. The lock will be dropped on program exit.
337         if (! -d $config{wikistatedir}) {
338                 mkdir($config{wikistatedir});
339         }
340         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
341                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
342         if (! flock(WIKILOCK, 2 | 4)) {
343                 debug("wiki seems to be locked, waiting for lock");
344                 my $wait=600; # arbitrary, but don't hang forever to 
345                               # prevent process pileup
346                 for (1..600) {
347                         return if flock(WIKILOCK, 2 | 4);
348                         sleep 1;
349                 }
350                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
351         }
352 } #}}}
353
354 sub unlockwiki () { #{{{
355         close WIKILOCK;
356 } #}}}
357
358 sub loadindex () { #{{{
359         open (IN, "$config{wikistatedir}/index") || return;
360         while (<IN>) {
361                 $_=possibly_foolish_untaint($_);
362                 chomp;
363                 my %items;
364                 $items{link}=[];
365                 foreach my $i (split(/ /, $_)) {
366                         my ($item, $val)=split(/=/, $i, 2);
367                         push @{$items{$item}}, $val;
368                 }
369
370                 next unless exists $items{src}; # skip bad lines for now
371
372                 my $page=pagename($items{src}[0]);
373                 if (! $config{rebuild}) {
374                         $pagesources{$page}=$items{src}[0];
375                         $oldpagemtime{$page}=$items{mtime}[0];
376                         $oldlinks{$page}=[@{$items{link}}];
377                         $links{$page}=[@{$items{link}}];
378                         $inlinepages{$page}=join(" ", @{$items{inlinepage}})
379                                 if exists $items{inlinepage};
380                         $renderedfiles{$page}=$items{dest}[0];
381                 }
382                 $pagectime{$page}=$items{ctime}[0];
383         }
384         close IN;
385 } #}}}
386
387 sub saveindex () { #{{{
388         if (! -d $config{wikistatedir}) {
389                 mkdir($config{wikistatedir});
390         }
391         open (OUT, ">$config{wikistatedir}/index") || 
392                 error("cannot write to $config{wikistatedir}/index: $!");
393         foreach my $page (keys %oldpagemtime) {
394                 next unless $oldpagemtime{$page};
395                 my $line="mtime=$oldpagemtime{$page} ".
396                         "ctime=$pagectime{$page} ".
397                         "src=$pagesources{$page} ".
398                         "dest=$renderedfiles{$page}";
399                 $line.=" link=$_" foreach @{$links{$page}};
400                 if (exists $inlinepages{$page}) {
401                         $line.=" inlinepage=$_" foreach split " ", $inlinepages{$page};
402                 }
403                 print OUT $line."\n";
404         }
405         close OUT;
406 } #}}}
407
408 sub misctemplate ($$) { #{{{
409         my $title=shift;
410         my $pagebody=shift;
411         
412         my $template=HTML::Template->new(
413                 filename => "$config{templatedir}/misc.tmpl"
414         );
415         $template->param(
416                 title => $title,
417                 indexlink => indexlink(),
418                 wikiname => $config{wikiname},
419                 pagebody => $pagebody,
420                 styleurl => styleurl(),
421         );
422         return $template->output;
423 }#}}}
424
425 sub userinfo_get ($$) { #{{{
426         my $user=shift;
427         my $field=shift;
428
429         eval q{use Storable};
430         my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
431         if (! defined $userdata || ! ref $userdata || 
432             ! exists $userdata->{$user} || ! ref $userdata->{$user} ||
433             ! exists $userdata->{$user}->{$field}) {
434                 return "";
435         }
436         return $userdata->{$user}->{$field};
437 } #}}}
438
439 sub userinfo_set ($$$) { #{{{
440         my $user=shift;
441         my $field=shift;
442         my $value=shift;
443         
444         eval q{use Storable};
445         my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
446         if (! defined $userdata || ! ref $userdata || 
447             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
448                 return "";
449         }
450         
451         $userdata->{$user}->{$field}=$value;
452         my $oldmask=umask(077);
453         my $ret=Storable::lock_store($userdata, "$config{wikistatedir}/userdb");
454         umask($oldmask);
455         return $ret;
456 } #}}}
457
458 sub userinfo_setall ($$) { #{{{
459         my $user=shift;
460         my $info=shift;
461         
462         eval q{use Storable};
463         my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
464         if (! defined $userdata || ! ref $userdata) {
465                 $userdata={};
466         }
467         $userdata->{$user}=$info;
468         my $oldmask=umask(077);
469         my $ret=Storable::lock_store($userdata, "$config{wikistatedir}/userdb");
470         umask($oldmask);
471         return $ret;
472 } #}}}
473
474 sub is_admin ($) { #{{{
475         my $user_name=shift;
476
477         return grep { $_ eq $user_name } @{$config{adminuser}};
478 } #}}}
479
480 sub glob_match ($$) { #{{{
481         my $page=shift;
482         my $glob=shift;
483
484         # turn glob into safe regexp
485         $glob=quotemeta($glob);
486         $glob=~s/\\\*/.*/g;
487         $glob=~s/\\\?/./g;
488         $glob=~s!\\/!/!g;
489         
490         $page=~/^$glob$/i;
491 } #}}}
492
493 sub globlist_match ($$) { #{{{
494         my $page=shift;
495         my @globlist=split(" ", shift);
496
497         # check any negated globs first
498         foreach my $glob (@globlist) {
499                 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
500         }
501
502         foreach my $glob (@globlist) {
503                 return 1 if glob_match($page, $glob);
504         }
505         
506         return 0;
507 } #}}}
508
509 sub main () { #{{{
510         getconfig();
511         
512         if ($config{cgi}) {
513                 lockwiki();
514                 loadindex();
515                 require IkiWiki::CGI;
516                 cgi();
517         }
518         elsif ($config{setup}) {
519                 require IkiWiki::Setup;
520                 setup();
521         }
522         elsif ($config{wrapper}) {
523                 lockwiki();
524                 require IkiWiki::Wrapper;
525                 gen_wrapper();
526         }
527         else {
528                 lockwiki();
529                 loadindex();
530                 require IkiWiki::Render;
531                 rcs_update();
532                 rcs_getctime() if $config{getctime};
533                 refresh();
534                 saveindex();
535         }
536 } #}}}
537
538 main;