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