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