odd dir for apache logs
[koha.git] / misc / Install.pm
1 package Install; #assumes Install.pm
2
3
4 # Copyright 2000-2002 Katipo Communications
5 # Contains parts Copyright 2003 MJ Ray
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21 #
22 # Recent Authors
23 # MJR: my.cnf, etcdir, prefix, new display, apache conf, copying fixups
24
25 use strict;
26 use POSIX;
27 #MJR: everyone will have these modules, right?
28 # They look like part of perl core to me
29 use Term::Cap;
30 use Term::ANSIColor qw(:constants);
31 use Text::Wrap;
32 require Exporter;
33
34 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
35
36 =head1 NAME
37
38 Install.pm - Perl module containing the bulk of the installation logic
39
40 =head1 DESCRIPTION
41
42 The Install.pm module contains the bulk
43 of the code to do installation;
44 this code is used by installer.pl
45 to perform an actual installation.
46
47 =head2 Internal functions (not meant to be used outside of Install.pm)
48
49 =over 4
50
51 =cut
52
53 # set the version for version checking
54 $VERSION = 0.01;
55
56 @ISA = qw(Exporter);
57 @EXPORT = qw(   &checkperlmodules
58                 &checkabortedinstall
59                 &getmessage
60                 &showmessage
61                 &releasecandidatewarning
62                 &getinstallationdirectories
63                 &getdatabaseinfo
64                 &getapacheinfo
65                 &getapachevhostinfo
66                 &updateapacheconf
67                 &basicauthentication
68                 &installfiles
69                 &databasesetup
70                 &updatedatabase
71                 &populatedatabase
72                 &restartapache
73                 &finalizeconfigfile
74                 &loadconfigfile
75                 &backupmycnf
76                 &restoremycnf
77                 );
78
79 use vars qw( $kohaversion );                    # set in installer.pl
80 use vars qw( $language );                       # set in installer.pl
81 use vars qw( $domainname );                     # set in installer.pl
82
83 use vars qw( $etcdir );                         # set in installer.pl, usu. /etc
84 use vars qw( $intranetdir $opacdir $kohalogdir );
85 use vars qw( $realhttpdconf $httpduser );
86 use vars qw( $servername $svr_admin $opacport $intranetport );
87 use vars qw( $mysqldir );
88 use vars qw( $database $mysqluser );
89 use vars qw( $mysqlpass );                      # normally should not be used
90 use vars qw( $dbname $hostname $user $pass );   # virtual hosting
91
92 use vars qw( $newversion );                     # XXX this seems to be unused
93
94 =item heading
95
96     $messages->{'WelcomeToKohaInstaller'
97         = heading('Welcome to the Koha Installer') . qq|...|;
98
99 The heading function takes one string, the text to be displayed as
100 the heading, and returns a formatted heading (currently formatted
101 with ANSI colours).
102
103 This reduces the likelihood of pod2man(1) etc. misinterpreting
104 a line of equal signs as illegal POD directives.
105
106 =cut
107
108 my $termios = POSIX::Termios->new();
109 $termios->getattr();
110 my $terminal = Term::Cap->Tgetent({OSPEED=>$termios->getospeed()});
111 my $clear_string = $terminal->Tputs('cl');
112
113 sub heading ($) {
114   my $title = shift;
115   my $bal = 5;
116   return($clear_string."koha-".$kohaversion." Installer\n".ON_BLUE.WHITE.BOLD." "x$bal.uc($title)." "x$bal.RESET."\n\n");
117 }
118
119 my $mycnf = $ENV{HOME}."/.my.cnf";
120 my $mytmpcnf = `mktemp my.cnf.koha.XXXXXX`;
121
122 my $messages;
123 $messages->{'continuing'}->{en}="Great!  Continuing setup.\n\n";
124 $messages->{'WelcomeToKohaInstaller'}->{en} =
125    heading('Welcome to the Koha Installer') . qq|
126 Welcome to the Koha install script!  This script will prompt you for some
127 basic information about your desired setup, then install Koha for you.
128
129 If you want to install the Koha configuration file somewhere other than /etc
130 (eg for non-root installation, or multiple Koha versions on one system), you
131 should set the etcdir and prefix environment variables.  If this is your
132 only koha installation on this machine and you are running this as root, the
133 default should be OK.
134
135 To accept the default value for any question, simply hit Enter at the prompt.
136
137 Please be sure to read the documentation, or visit the Koha website at
138 http://www.koha.org for more information.
139
140 Are you ready to begin the installation? ([Y]/N): |;
141 $messages->{'ReleaseCandidateWarning'}->{en} =
142    heading('RELEASE CANDIDATE') . qq|
143 WARNING WARNING WARNING WARNING WARNING
144
145 You are about to install Koha version %s.  This version of Koha is a
146 release candidate.  It is not intended to be installed on production systems.
147 It is being released so that users can test it before we release a final
148 version.
149
150 Are you sure you want to install Koha %s? (Y/[N]): |;
151 $messages->{'WatchForReleaseAnnouncements'}->{en}=qq|
152
153 Watch for announcements of Koha releases on the Koha mailing list or the Koha
154 web site (http://www.koha.org/).
155
156 |;
157
158 $messages->{'NETZ3950Missing'}->{en}=qq|
159
160 The Net::Z3950 module is missing.  This module is necessary if you want to use
161 Koha's Z39.50 client to download bibliographic records from other libraries.
162
163 To install this module, you will need the yaz client installed from
164 http://www.indexdata.dk/yaz/ and then you can install the perl module with the
165 command:
166
167 perl -MCPAN -e 'install Net::Z3950'
168
169 IMPORTANT NOTE : If you use PERL5.8.0 (RedHat 8.0 or Mandrake 9.x), you MUST install 
170 manually the Net::Z3950 and edit Makefile.PL and yazwrap/Makefile.PL to include:
171     'DEFINE' => '-D_GNU_SOURCE',
172 Also note that some installations of Perl on Red Hat will generate a lot of
173 "'my_perl' undeclared" errors when running make in Net-Z3950.  This is fixed by
174 inserting the following line in yazwrap/ywpriv.h :
175    #include "XSUB.h"
176
177 Press the <ENTER> key to continue: |;   #'
178
179 $messages->{'CheckingPerlModules'}->{en} = heading('PERL & MODULES') . qq|
180 Checking perl modules ...
181 |;
182
183 $messages->{'PerlVersionFailure'}->{en}="Sorry, you need at least Perl %s\n";
184
185 $messages->{'MissingPerlModules'}->{en} = heading('MISSING PERL MODULES') . qq|
186 You are missing some Perl modules which are required by Koha.
187 Once these modules have been installed, rerun this installer.
188 They can be installed by running (as root) the following:
189
190 %s
191 |;
192
193 $messages->{'AllPerlModulesInstalled'}->{en} =
194    heading('ALL PERL MODULES INSTALLED') . qq|
195 All mandatory perl modules are installed.
196
197 Press <ENTER> to continue: |;
198 $messages->{'KohaVersionInstalled'}->{en}="You currently have Koha %s on your system.";
199 $messages->{'KohaUnknownVersionInstalled'}->{en}="I am not able to determine what version of Koha is installed now.";
200 $messages->{'KohaAlreadyInstalled'}->{en} =
201    heading('Koha already installed') . qq|
202 It looks like Koha is already installed on your system (%s/koha.conf exists
203 already).  If you would like to upgrade your system to %s, please use
204 the koha.upgrade script in this directory.
205
206 %s
207
208 |;
209 $messages->{'GetOpacDir'}->{en} = heading('OPAC DIRECTORY') . qq|
210 Please supply the directory you want Koha to store its OPAC files in.  This
211 directory will be auto-created for you if it doesn't exist.
212
213 OPAC Directory [%s]: |; #'
214
215 $messages->{'GetIntranetDir'}->{en} =
216    heading('INTRANET/LIBRARIANS DIRECTORY') . qq|
217 Please supply the directory you want Koha to store its Intranet/Librarians
218 files in.  This directory will be auto-created for you if it doesn't exist.
219
220 Intranet Directory [%s]: |;     #'
221
222 $messages->{'GetKohaLogDir'}->{en} = heading('KOHA LOG DIRECTORY') . qq|
223 Specify a log directory where any Koha daemons can create log files.
224
225 Koha Log Directory [%s]: |;
226
227 $messages->{'AuthenticationWarning'}->{en} = heading('Authentication') . qq|
228 This release of Koha has a new authentication module.  If you are not already
229 using basic authentication on your intranet, you will be required to log in to
230 access some of the features of the intranet.  You can log in using the userid
231 and password from the %s/koha.conf configuration file at any time.  Use the
232 "Members" module to add passwords for other accounts and set their permissions.
233
234 Press the <ENTER> key to continue: |;
235
236 $messages->{'Completed'}->{en} = heading('KOHA INSTALLATION COMPLETE') . qq|
237 Congratulations ... your Koha installation is complete!
238
239 You will be able to connect to your Librarian interface at:
240
241    http://%s\:%s/
242    use mysql login and password to connect to this interface. Then, go to admin page, and create whatever fits your needs.
243
244 and the OPAC interface at :
245
246    http://%s\:%s/
247
248 Be sure to read the Hints file.
249
250 For more information visit http://www.koha.org
251
252 Press <ENTER> to exit the installer: |;
253
254 sub releasecandidatewarning {
255     my $message=getmessage('ReleaseCandidateWarning', [$newversion, $newversion]);
256     my $answer=showmessage($message, 'yn', 'n');
257
258     if ($answer =~ /y/i) {
259         print getmessage('continuing');
260     } else {
261         my $message=getmessage('WatchForReleaseAnnouncements');
262         print $message;
263         exit;
264     };
265 }
266
267
268 =back
269
270 =head2 Accessor functions (for installer.pl)
271
272 =over 4
273
274 =cut
275
276 =item setlanguage
277
278     setlanguage('en');
279
280 Sets the installation language, normally "en" (English).
281 In fact, only "en" is supported.
282
283 =cut
284
285 sub setlanguage ($) {
286     ($language) = @_;
287 }
288
289 =item setdomainname
290
291     setdomainname('example.org');
292
293 Sets the domain name of the host.
294
295 The domain name should not contain a leading dot;
296 otherwise, the results are undefined.
297
298 =cut
299
300 sub setdomainname ($) {
301     ($domainname) = @_;
302 }
303
304 =item setetcdir
305
306     setetcdir('/etc');
307
308 Sets the sysconfdir, normally /etc.
309 This should be an absolute path; a trailing / is not required.
310
311 =cut
312
313 sub setetcdir ($) {
314     ($etcdir) = @_;
315 }
316
317 =item setkohaversion
318
319     setkohaversion('1.3.3RC26');
320
321 Sets the Koha version as known by the installer.
322
323 =cut
324
325 sub setkohaversion ($) {
326     ($kohaversion) = @_;
327 }
328
329 =item getservername
330
331     my $servername = getservername;
332
333 Gets the name of the Koha virtual server as specified by the user.
334
335 =cut
336
337 sub getservername () {
338     $servername;
339 }
340
341 =item getopacport
342
343     $port = getopacport;
344
345 Gets the port that will run the Koha OPAC virtual server,
346 as specified by the user.
347
348 =cut
349
350 sub getopacport () {
351     $opacport;
352 }
353
354 =item getintranetport
355
356     $port = getintranetport;
357
358 Gets the port that will run the Koha INTRANET virtual server,
359 as specified by the user.
360
361 =cut
362
363 sub getintranetport () {
364     $intranetport;
365 }
366
367 =back
368
369 =head2 Miscellaneous utility functions
370
371 =over 4
372
373 =cut
374
375 =item dirname
376
377     dirname $path;
378
379 Does the equivalent of dirname(1). Given a path $path, return the
380 parent directory of $path (best guess), except when $path seems to
381 be the same as /, in which case $path itself is returned unchanged.
382
383 =cut
384
385 sub dirname ($;$) {
386     my($path) = @_;
387     if ($path =~ /[^\/]/s) {
388         if ($path =~ /\//) {
389             $path =~ s/\/+[^\/]+\/*$//s;
390         } else {
391             $path = '.';
392         }
393     }
394     return $path;
395 }
396
397 =item mkdir_parents
398
399     mkdir_parents $path;
400     mkdir_parents $path, $mode;
401
402 Does the equivalent of mkdir -p, or mkdir --parents. Given a path $path,
403 create the directory $path, recursively creating any intermediate
404 directories. If $mode is given, the directory will be created with
405 mode $mode.
406
407 WARNING: If $path already exists, mkdir_parents will just return
408 successfully (just like mkdir -p), whether the mode of $path conforms
409 to $mode or not. (This is the behaviour of the mkdir -p command.)
410
411 =cut
412
413 sub mkdir_parents ($;$) {
414     my($path, $mode) = @_;
415     my $ok = -d($path)? 1: defined $mode? mkdir($path, $mode): mkdir($path);
416
417     if (!$ok && $! == ENOENT) {
418         my $parent = dirname($path);
419         $ok = mkdir_parents($parent, $mode);
420
421         # retry and at the same time make sure that $! is set correctly
422         $ok = defined $mode? mkdir($path, $mode): mkdir($path);
423     }
424     return $ok;
425 }
426
427
428 =item getmessage
429
430     getmessage($msgid);
431     getmessage($msgid, $variables);
432
433 Gets a localized message (format string) with message id $msgid,
434 and, if an array reference of variables $variables is given,
435 substitutes variables in the format string with @$variables.
436 Returns the found message string, with variable substitutions
437 if specified.
438
439 $msgid must be the message identifier corresponding to a defined
440 message string (a valid key to the $messages hash in the Installer
441 package). getmessage throws an exception if the message cannot be
442 found.
443
444 =cut
445
446 sub getmessage {
447     my $messagename=shift;
448     my $variables=shift;
449     my $message=$messages->{$messagename}->{$language} || $messages->{$messagename}->{en} || "Error: No message named $messagename in Install.pm\n";
450     if (defined($variables)) {
451         $message=sprintf $message, @$variables;
452     }
453     return $message;
454 }
455
456
457 =item showmessage
458
459     showmessage($message, 'none');
460     showmessage($message, 'none', undef, $noclear);
461
462     $result = showmessage($message, 'yn');
463     $result = showmessage($message, 'yn', $defaultresponse);
464     $result = showmessage($message, 'yn', $defaultresponse, $noclear);
465
466     $result = showmessage($message, 'restrictchar CHARS');
467     $result = showmessage($message, 'free');
468     $result = showmessage($message, 'silentfree');
469     $result = showmessage($message, 'numerical');
470     $result = showmessage($message, 'email');
471     $result = showmessage($message, 'PressEnter');
472
473 Shows a message and optionally gets a response from the user.
474
475 The first two arguments, the message and the response type,
476 are mandatory.  The message must be the actual string to
477 display; the caller is responsible for calling getmessage if
478 required.
479
480 The response type must be one of "none", "yn", "free", "silentfree"
481 "numerical", "email", "PressEnter", or a string consisting
482 of "restrictchar " followed by a list of allowed characters
483 (space can be specified). (Case is not significant, but case is
484 significant in the list of allowed characters.) If a response
485 type other than the above-listed is specified, the result is
486 undefined.
487
488 Note that the response type "yn" is equivalent to "restrictchar yn".
489 Because "restrictchar" is case-sensitive, the user is expected
490 to enter "y" or "n" in lowercase only.
491
492 Note that the response type of "email" does not actually
493 guarantee that the returned value is a well-formed RFC-822
494 email address, nor does it accept all well-formed RFC-822 email
495 addresses. What it does is to restrict the returned value to a
496 string that is looks reasonably likely to be an email address
497 in the "real world", given the premise that the user is trying
498 to enter a real email address.
499
500 If a response type other than "none" or "PressEnter" is
501 specified, a third argument, specifying the default value, can
502 be specified:  If this default response is not specified, the
503 default response is the first allowed character if the response
504 type is "restrictchar", otherwise the default response is the
505 empty string. This default response is used when the user does
506 not specify a value (i.e., presses Enter without typing in
507 anything), showmessage will assume that the default response is
508 the user's response.
509
510 Note that because the response type "yn" is equivalent to
511 "restrictchar yn", the default value for response type "yn",
512 if unspecified, is "y".
513
514 The screen is normally cleared before the message is displayed;
515 if a fourth argument is specified and is nonzero, this
516 screen-clearing is not done.
517
518 =cut
519 #'
520
521 sub showmessage {
522     #MJR: Maybe refactor to use anonymous functions that
523     # check the responses instead of RnP branching.
524     my $message=shift;
525     my $responsetype=shift;
526     my $defaultresponse=shift;
527     my $noclear=shift;
528     $noclear = 0 unless defined $noclear; # defaults to "clear"
529     ($noclear) || (print $clear_string);
530     if ($responsetype =~ /^yn$/) {
531         $responsetype='restrictchar ynYN';
532     }
533     print $message;
534     if ($responsetype =~/^restrictchar (.*)/i) {
535         my $response='\0';
536         my $options=$1;
537         until ($options=~/$response/) {
538             (defined($defaultresponse)) || ($defaultresponse=substr($options,0,1));
539             $response=<STDIN>;
540             chomp $response;
541             (length($response)) || ($response=$defaultresponse);
542             if ( $response=~/.*[\:\(\)\^\$\*\!\\].*/ ) {
543                 ($noclear) || (print $clear_string);
544                 print "Response contains invalid characters.  Choose from [$options].\n\n";
545                 print $message;
546                 $response='\0';
547             } else {
548                 unless ($options=~/$response/) {
549                     ($noclear) || (print $clear_string);
550                     print "Invalid Response.  Choose from [$options].\n\n";
551                     print $message;
552                 }
553             }
554         }
555         return $response;
556     } elsif ($responsetype =~/^(silent)?free$/i) {
557         (defined($defaultresponse)) || ($defaultresponse='');
558         if ($responsetype =~/^(silent)/i) { setecho(0) }; 
559         my $response=<STDIN>;
560         if ($responsetype =~/^(silent)/i) { setecho(1) }; 
561         chomp $response;
562         ($response) || ($response=$defaultresponse);
563         return $response;
564     } elsif ($responsetype =~/^numerical$/i) {
565         (defined($defaultresponse)) || ($defaultresponse='');
566         my $response='';
567         until ($response=~/^\d+$/) {
568             $response=<STDIN>;
569             chomp $response;
570             ($response) || ($response=$defaultresponse);
571             unless ($response=~/^\d+$/) {
572                 ($noclear) || (print $clear_string);
573                 print "Invalid Response ($response).  Response must be a number.\n\n";
574                 print $message;
575             }
576         }
577         return $response;
578     } elsif ($responsetype =~/^email$/i) {
579         (defined($defaultresponse)) || ($defaultresponse='');
580         my $response='';
581         until ($response=~/.*\@.*\..*/) {
582             $response=<STDIN>;
583             chomp $response;
584             ($response) || ($response=$defaultresponse);
585             if ($response!~/.*\@.*\..*/) {
586                         ($noclear) || (print $clear_string);
587                         print "Invalid Response ($response).  Response must be a valid email address.\n\n";
588                         print $message;
589             }
590         }
591         return $response;
592     } elsif ($responsetype =~/^PressEnter$/i) {
593         <STDIN>;
594         return;
595     } elsif ($responsetype =~/^none$/i) {
596         return;
597     } else {
598         # FIXME: There are a few places where we will get an undef as the
599         # response type. Should we thrown an exception here, or should we
600         # legitimize this usage and say "none" is the default if not specified?
601         #die "Illegal response type \"$responsetype\"";
602     }
603 }
604
605
606 =back
607
608 =head2 Subtasks of doing an installation
609
610 =over 4
611
612 =cut
613
614 =item checkabortedinstall
615
616     checkabortedinstall;
617
618 Checks whether a previous installation process has been abnormally
619 aborted, by checking whether $etcidr/koha.conf is a symlink matching
620 a particular pattern.  If an aborted installation is detected, give
621 the user a chance to abort, before trying to recover the aborted
622 installation.
623
624 FIXME: The recovery is not complete; it only partially rolls back
625 some changes.
626
627 =cut
628
629 sub checkabortedinstall () {
630     if (-l("$etcdir/koha.conf")
631         && readlink("$etcdir/koha.conf") =~ /\.tmp$/
632     ) {
633         print qq|
634 I have detected that you tried to install Koha before, but the installation
635 was aborted.  I will try to continue, but there might be problems if the
636 database is already created.
637
638 |;
639         print "Please press <ENTER> to continue: ";
640         <STDIN>;
641
642         # Remove the symlink after the <STDIN>, so the user can back out
643         unlink "$etcdir/koha.conf"
644             || die "Failed to remove incomplete $etcdir/koha.conf: $!\n";
645     }
646 }
647
648
649 =item checkperlmodules
650
651     checkperlmodules;
652
653 Test whether the version of Perl is new enough, whether Perl is
654 found at the expected location, and whether all required modules
655 have been installed.
656
657 =cut
658
659 sub checkperlmodules {
660 #
661 # Test for Perl and Modules
662 #
663
664     my $message = getmessage('CheckingPerlModules');
665     showmessage($message, 'none');
666
667     unless ($] >= 5.006001) {                   # Bug 179
668         die getmessage('PerlVersionFailure', ['5.6.1']);
669     }
670
671     my @missing = ();
672     unless (eval {require DBI})              { push @missing,"DBI" };
673     unless (eval {require Date::Manip})      { push @missing,"Date::Manip" };
674     unless (eval {require DBD::mysql})       { push @missing,"DBD::mysql" };
675     unless (eval {require HTML::Template})   { push @missing,"HTML::Template" };
676 #    unless (eval {require Set::Scalar})      { push @missing,"Set::Scalar" };
677     unless (eval {require Digest::MD5})      { push @missing,"Digest::MD5" };
678     unless (eval {require MARC::Record})     { push @missing,"MARC::Record" };
679     unless (eval {require Mail::Sendmail})   { push @missing,"Mail::Sendmail" };
680     unless (eval {require Net::Z3950})       {
681         showmessage(getmessage('NETZ3950Missing'), 'PressEnter', '', 1);
682         if ($#missing>=0) { # XXX why only when $#missing >= 0?
683             push @missing, "Net::Z3950";
684         }
685     }
686
687 #
688 # Print out a list of any missing modules
689 #
690
691     if (@missing > 0) {
692         my $missing='';
693         foreach my $module (@missing) {
694             $missing.="   perl -MCPAN -e 'install \"$module\"'\n";
695         }
696         my $message=getmessage('MissingPerlModules', [$missing]);
697         showmessage($message, 'none');
698         exit;
699     } else {
700         showmessage(getmessage('AllPerlModulesInstalled'), 'PressEnter', '', 1);
701     }
702
703
704     unless (-x "/usr/bin/perl") {
705         my $realperl=`which perl`;
706         chomp $realperl;
707         $realperl = showmessage(getmessage('NoUsrBinPerl'), 'none');
708         until (-x $realperl) {
709             $realperl=showmessage(getmessage('AskLocationOfPerlExecutable', $realperl), 'free', $realperl, 1);
710         }
711         my $response=showmessage(getmessage('ConfirmPerlExecutableSymlink', $realperl), 'yn', 'y', 1);
712         unless ($response eq 'n') {
713             system("ln -s $realperl /usr/bin/perl");
714         }
715     }
716
717
718 }
719
720 $messages->{'NoUsrBinPerl'}->{en} =
721    heading('Perl is not located in /usr/bin/perl') . qq|
722 The Koha perl scripts expect to find the perl executable in the /usr/bin
723 directory.  It is not there on your system.
724
725 |;
726
727 $messages->{'AskLocationOfPerlExecutable'}->{en}=qq|Location of Perl Executable: [%s]: |;
728 $messages->{'ConfirmPerlExecutableSymlink'}->{en}=qq|
729 The Koha scripts will _not_ work without a symlink from %s to /usr/bin/perl
730
731 May I create this symlink? ([Y]/N):
732 : |;
733
734 $messages->{'DirFailed'}->{en} = qq|
735 We could not create %s, but continuing anyway...
736
737 |;
738
739
740
741 =item getinstallationdirectories
742
743     getinstallationdirectories;
744
745 Get the various installation directories from the user, and then
746 create those directories (if they do not already exist).
747
748 These pieces of information are saved to global variables; the
749 function does not return any values.
750
751 =cut
752
753 sub getinstallationdirectories {
754         if (!$ENV{prefix}) { $ENV{prefix} = "/usr/local"; }
755     $opacdir = $ENV{prefix}.'/koha/opac';
756     $intranetdir = $ENV{prefix}.'/koha/intranet';
757     my $getdirinfo=1;
758     while ($getdirinfo) {
759         # Loop until opac directory and koha directory are different
760         my $message=getmessage('GetOpacDir', [$opacdir]);
761         $opacdir=showmessage($message, 'free', $opacdir);
762
763         $message=getmessage('GetIntranetDir', [$intranetdir]);
764         $intranetdir=showmessage($message, 'free', $intranetdir);
765
766         if ($intranetdir eq $opacdir) {
767             print qq|
768
769 You must specify different directories for the OPAC and INTRANET files!
770  :: $intranetdir :: $opacdir ::
771 |;
772 <STDIN>
773         } else {
774             $getdirinfo=0;
775         }
776     }
777     $kohalogdir=$ENV{prefix}.'/koha/log';
778     my $message=getmessage('GetKohaLogDir', [$kohalogdir]);
779     $kohalogdir=showmessage($message, 'free', $kohalogdir);
780
781
782     # FIXME: Need better error handling for all mkdir calls here
783     unless ( -d $intranetdir ) {
784        mkdir_parents (dirname($intranetdir), 0775) || print getmessage('DirFailed','parents of '.$intranetdir);
785        mkdir ($intranetdir,                  0770) || print getmessage('DirFailed',$intranetdir);
786        if ($>==0) { chown (oct(0), (getgrnam($httpduser))[2], "$intranetdir"); }
787        chmod 0770, "$intranetdir";
788     }
789     mkdir_parents ("$intranetdir/htdocs",    0750);
790     mkdir_parents ("$intranetdir/cgi-bin",   0750);
791     mkdir_parents ("$intranetdir/modules",   0750);
792     mkdir_parents ("$intranetdir/scripts",   0750);
793     unless ( -d $opacdir ) {
794        mkdir_parents (dirname($opacdir),     0775) || print getmessage('DirFailed','parents of '.$opacdir);
795        mkdir ($opacdir,                      0770) || print getmessage('DirFailed',$opacdir);
796        if ($>==0) { chown (oct(0), (getgrnam($httpduser))[2], "$opacdir"); }
797        chmod (oct(770), "$opacdir");
798     }
799     mkdir_parents ("$opacdir/htdocs",        0750);
800     mkdir_parents ("$opacdir/cgi-bin",       0750);
801
802
803     unless ( -d $kohalogdir ) {
804        mkdir_parents (dirname($kohalogdir),  0775) || print getmessage('DirFailed','parents of '.$kohalogdir);
805        mkdir ($kohalogdir,                   0770) || print getmessage('DirFailed',$kohalogdir);
806        if ($>==0) { chown (oct(0), (getgrnam($httpduser))[2,3], "$kohalogdir"); }
807        chmod (oct(770), "$kohalogdir");
808     }
809 }
810
811
812
813 =item getdatabaseinfo
814
815     getdatabaseinfo;
816
817 Get various pieces of information related to the Koha database:
818 the name of the database, the host on which the SQL server is
819 running, and the database user name.
820
821 These pieces of information are saved to global variables; the
822 function does not return any values.
823
824 =cut
825
826 $messages->{'DatabaseName'}->{en} = heading('Name of MySQL database') . qq|
827 Please provide the name that you wish to give your koha database.
828 It must not exist already on the database server.
829
830 Database name [%s]: |;
831
832 $messages->{'DatabaseHost'}->{en} = heading('Database Host') . qq|
833 Please provide the hostname for mysql.  Unless the database is located on
834 another machine this will be "localhost".
835
836 Database host [%s]: |;
837
838 $messages->{'DatabaseUser'}->{en} = heading('Database User') . qq|
839 Please provide the name of the user who will have full administrative rights
840 to the %s database, when authenticating from %s.
841
842 This user will also be used to access Koha's INTRANET interface.
843
844 Database user [%s]: |;
845
846 $messages->{'DatabasePassword'}->{en} = heading('Database Password') . qq|
847 Please provide a good password for the user %s.
848
849 This password will also be used to access Koha's INTRANET interface.
850
851 Password for database user %s: |;
852
853 $messages->{'BlankPassword'}->{en} = heading('BLANK PASSWORD') . qq|
854 You must not use a blank password for your MySQL user.
855
856 Press <ENTER> to try again: 
857 |;
858
859 sub getdatabaseinfo {
860
861     $dbname = 'Koha';
862     $hostname = 'localhost';
863     $user = 'kohaadmin';
864     $pass = '';
865
866 #Get the database name
867
868     my $message=getmessage('DatabaseName', [$dbname]);
869     $dbname=showmessage($message, 'free', $dbname);
870
871 #Get the hostname for the database
872     
873     $message=getmessage('DatabaseHost', [$hostname]);
874     $hostname=showmessage($message, 'free', $hostname);
875
876 #Get the username for the database
877
878     $message=getmessage('DatabaseUser', [$dbname, $hostname, $user]);
879     $user=showmessage($message, 'free', $user);
880
881 #Get the password for the database user
882
883     while ($pass eq '') {
884         my $message=getmessage('DatabasePassword', [$user, $user]);
885         $pass=showmessage($message, 'free', $pass);
886         if ($pass eq '') {
887             my $message=getmessage('BlankPassword');
888             showmessage($message,'PressEnter');
889         }
890     }
891 }
892
893
894
895 =item getapacheinfo
896
897     getapacheinfo;
898
899 Get various pieces of information related to the Apache server:
900 the location of the configuration file and, if needed, the Unix
901 user that the Koha CGI will be run under.
902
903 These pieces of information are saved to global variables; the
904 function does not return any values.
905
906 =cut
907
908 $messages->{'FoundMultipleApacheConfFiles'}->{en} = 
909    heading('MULTIPLE APACHE CONFIG FILES') . qq|
910 I found more than one possible Apache configuration file:
911
912 %s
913
914 Choose the correct file [1]: |;
915
916 $messages->{'NoApacheConfFiles'}->{en} =
917    heading('NO APACHE CONFIG FILE FOUND') . qq|
918 I was not able to find your Apache configuration file.
919
920 The file is usually called httpd.conf or apache.conf.
921
922 Please specify the location of your config file: |;
923
924 $messages->{'NotAFile'}->{en} = heading('FILE DOES NOT EXIST') . qq|
925 The file %s does not exist.
926
927 Please press <ENTER> to continue: |;
928
929 $messages->{'EnterApacheUser'}->{en} = heading('NEED APACHE USER') . qq|
930 I was not able to determine the user that Apache is running as.  This
931 information is necessary in order to set the access privileges correctly on
932 %s/koha.conf.  This user should be set in one of the Apache configuration
933 files using the "User" directive.
934
935 Enter the Apache userid: |;
936
937 $messages->{'InvalidUserid'}->{en} = heading('INVALID USERID') . qq|
938 The userid %s is not a valid userid on this system.
939
940 Press <ENTER> to continue: |;
941
942 sub getapacheinfo {
943     my @confpossibilities;
944
945     foreach my $httpdconf (qw(/usr/local/apache/conf/httpd.conf
946                           /usr/local/etc/apache/httpd.conf
947                           /usr/local/etc/apache/apache.conf
948                           /var/www/conf/httpd.conf
949                           /etc/apache2/httpd.conf
950                           /etc/apache2/apache.conf
951                           /etc/apache/conf/httpd.conf
952                           /etc/apache/conf/apache.conf
953                           /etc/apache-ssl/conf/apache.conf
954                           /etc/apache-ssl/httpd.conf
955                           /etc/httpd/conf/httpd.conf
956                           /etc/httpd/httpd.conf)) {
957         if ( -f $httpdconf ) {
958             push @confpossibilities, $httpdconf;
959         }
960     }
961
962     if ($#confpossibilities==-1) {
963         my $message=getmessage('NoApacheConfFiles');
964         my $choice='';
965         until (-f $realhttpdconf) {
966             $choice=showmessage($message, "free", 1);
967             if (-f $choice) {
968                 $realhttpdconf=$choice;
969             } else {
970                 showmessage(getmessage('NotAFile', [$choice]),'PressEnter', '', 1);
971             }
972         }
973     } elsif ($#confpossibilities>0) {
974         my $conffiles='';
975         my $counter=1;
976         my $options='';
977         foreach (@confpossibilities) {
978             $conffiles.="   $counter: $_\n";
979             $options.="$counter";
980             $counter++;
981         }
982         my $message=getmessage('FoundMultipleApacheConfFiles', [$conffiles]);
983         my $choice=showmessage($message, "restrictchar $options", 1);
984         $realhttpdconf=$confpossibilities[$choice-1];
985     } else {
986         $realhttpdconf=$confpossibilities[0];
987     }
988     unless (open (HTTPDCONF, "<$realhttpdconf")) {
989         warn "Insufficient privileges to open $realhttpdconf for reading.\n";
990         sleep 4;
991     }
992
993     while (<HTTPDCONF>) {
994         if (/^\s*User\s+"?([-\w]+)"?\s*$/) {
995             $httpduser = $1;
996         }
997     }
998     close(HTTPDCONF);
999
1000
1001
1002
1003     unless ($httpduser) {
1004         my $message=getmessage('EnterApacheUser', [$etcdir]);
1005         until (length($httpduser) && getpwnam($httpduser)) {
1006             $httpduser=showmessage($message, "free", '');
1007             if (length($httpduser)>0) {
1008                 unless (getpwnam($httpduser)) {
1009                     my $message=getmessage('InvalidUserid', [$httpduser]);
1010                     showmessage($message,'PressEnter');
1011                 }
1012             } else {
1013             }
1014         }
1015         print "AU: $httpduser\n";
1016     }
1017 }
1018
1019
1020 =item getapachevhostinfo
1021
1022     getapachevhostinfo;
1023
1024 Gets various pieces of information related to virtual hosting:
1025 the webmaster email address, virtual hostname, and the ports
1026 that the OPAC and INTRANET modules run on.
1027
1028 These pieces of information are saved to global variables; the
1029 function does not return any values.
1030
1031 =cut
1032
1033 $messages->{'ApacheConfigIntroduction'}->{en} =
1034    heading('APACHE CONFIGURATION') . qq|
1035 Koha needs to write an Apache configuration file for the
1036 OPAC and LIBRARIAN virtual hosts.  By default this installer
1037 will do this by using one ip address and two different ports
1038 for the virtual hosts.  There are other ways to set this up,
1039 and the installer will leave comments in
1040 %s/koha-httpd.conf detailing
1041 what these other options are.
1042
1043 NOTE: You will need to add lines to your main httpd.conf to
1044   Include %s/koha-httpd.conf
1045 and to make sure it is listening on the right ports
1046 (using the Listen directive).
1047
1048 Press <ENTER> to continue: |;
1049
1050 $messages->{'GetVirtualHostEmail'}->{en} =
1051    heading('WEB SERVER E-MAIL CONTACT') . qq|
1052 Enter the e-mail address to be used as a contact for the virtual hosts (this
1053 address is displayed if any errors are encountered).
1054
1055 E-mail contact [%s]: |;
1056
1057 $messages->{'GetServerName'}->{en} =
1058    heading('WEB SERVER HOST NAME OR IP ADDRESS') . qq|
1059 Please enter the host name or IP address that you wish to use for koha.
1060 Normally, this should be a name or IP that belongs to this machine.
1061
1062 Host name or IP Address [%s]: |;
1063
1064 $messages->{'GetOpacPort'}->{en} = heading('OPAC VIRTUAL HOST PORT') . qq|
1065 Please enter the port for your OPAC interface.  This defaults to port 80, but
1066 if you are already serving web content from this host, you should change it
1067 to a different port (8000 might be a good choice).
1068
1069 Enter the OPAC Port [%s]: |;
1070
1071 $messages->{'GetIntranetPort'}->{en} =
1072    heading('INTRANET VIRTUAL HOST PORT') . qq|
1073 Please enter the port for your Intranet interface.  This must be different from
1074 the OPAC port (%s).
1075
1076 Enter the Intranet Port [%s]: |;
1077
1078
1079 sub getapachevhostinfo {
1080
1081     $svr_admin = "webmaster\@$domainname";
1082     $servername=`hostname`;
1083     chomp $servername;
1084     $opacport=80;
1085     $intranetport=8080;
1086
1087     showmessage(getmessage('ApacheConfigIntroduction',[$etcdir,$etcdir]), 'PressEnter');
1088
1089     $svr_admin=showmessage(getmessage('GetVirtualHostEmail', [$svr_admin]), 'email', $svr_admin);
1090     $servername=showmessage(getmessage('GetServerName', [$servername]), 'free', $servername);
1091
1092
1093     $opacport=showmessage(getmessage('GetOpacPort', [$opacport]), 'numerical', $opacport);
1094     $intranetport=showmessage(getmessage('GetIntranetPort', [$opacport, $intranetport]), 'numerical', $intranetport);
1095
1096 }
1097
1098
1099 =item updateapacheconf
1100
1101     updateapacheconf;
1102
1103 Updates the Apache config file according to parameters previously
1104 specified by the user.
1105
1106 It will append fully-commented directives at the end of the original
1107 Apache config file.  The old config file is renamed with an extension
1108 of .prekoha.
1109
1110 If you need to uninstall Koha for any reason, the lines between
1111
1112     # Ports to listen to for Koha
1113
1114 and the block of comments beginning with
1115
1116     # If you want to use name based Virtual Hosting:
1117
1118 must be removed.
1119
1120 =cut
1121
1122 $messages->{'StartUpdateApache'}->{en} =
1123    heading('UPDATING APACHE CONFIGURATION') . qq|
1124 Checking for modules that need to be loaded...
1125 |;
1126
1127 $messages->{'ApacheConfigMissingModules'}->{en} =
1128    heading('APACHE CONFIGURATION NEEDS UPDATE') . qq|
1129 Koha uses the mod_env and mod_include apache features, but the
1130 installer did not find statements for them in your config.  Please
1131 make sure that they are enabled for your Koha host.
1132
1133 Press <ENTER> to continue: |;
1134
1135
1136 $messages->{'ApacheAlreadyConfigured'}->{en} =
1137    heading('APACHE ALREADY CONFIGURED') . qq|
1138 %s appears to already have an entry for Koha
1139 Virtual Hosts.  You may need to edit %s
1140 if anything has changed since it was last set up.  This
1141 script will not attempt to modify an existing Koha apache
1142 configuration.
1143
1144 Press <ENTER> to continue: |;
1145
1146 sub updateapacheconf {
1147     my $logfiledir=$kohalogdir;
1148     my $httpdconf = $etcdir."/koha-httpd.conf";
1149    
1150     showmessage(getmessage('StartUpdateApache'), 'none');
1151         # to be polite about it: I don't think this should touch the main httpd.conf
1152
1153         # QUESTION: Should we warn for includes_module too?
1154     my $envmodule=0;
1155     my $includesmodule=0;
1156     open HC, "<$realhttpdconf";
1157     while (<HC>) {
1158         if (/^\s*#\s*LoadModule env_module /) {
1159             showmessage(getmessage('ApacheConfigMissingModules'));
1160             $envmodule=1;
1161         }
1162         if (/\s*LoadModule includes_module / ) {
1163             $includesmodule=1;
1164         }
1165     }
1166
1167     if (`grep 'VirtualHost $servername' "$httpdconf"`) {
1168         showmessage(getmessage('ApacheAlreadyConfigured', [$httpdconf, $httpdconf]), 'PressEnter');
1169         return;
1170     } else {
1171         my $includesdirectives='';
1172         if ($includesmodule) {
1173             $includesdirectives.="Options +Includes\n";
1174             $includesdirectives.="   AddHandler server-parsed .html\n";
1175         }
1176         open(SITE,">$httpdconf") or warn "Insufficient priveleges to open $httpdconf for writing.\n";
1177         my $opaclisten = '';
1178         if ($opacport != 80) {
1179             $opaclisten="Listen $opacport";
1180         }
1181         my $intranetlisten = '';
1182         if ($intranetport != 80) {
1183             $intranetlisten="Listen $intranetport";
1184         }
1185         print SITE <<EOP
1186
1187 # Ports to listen to for Koha
1188 # uncomment these if they aren't already in main httpd.conf
1189 #$opaclisten
1190 #$intranetlisten
1191
1192 # NameVirtualHost is used by one of the optional configurations detailed below
1193
1194 #NameVirtualHost 11.22.33.44
1195
1196 # KOHA's OPAC Configuration
1197 <VirtualHost $servername\:$opacport>
1198    ServerAdmin $svr_admin
1199    DocumentRoot $opacdir/htdocs
1200    ServerName $servername
1201    ScriptAlias /cgi-bin/koha/ $opacdir/cgi-bin/
1202    ErrorLog $logfiledir/opac-error_log
1203    TransferLog $logfiledir/opac-access_log
1204    SetEnv PERL5LIB "$intranetdir/modules"
1205    SetEnv KOHA_CONF "$etcdir/koha.conf"
1206    $includesdirectives
1207 </VirtualHost>
1208
1209 # KOHA's INTRANET Configuration
1210 <VirtualHost $servername\:$intranetport>
1211    ServerAdmin $svr_admin
1212    DocumentRoot $intranetdir/htdocs
1213    ServerName $servername
1214    ScriptAlias /cgi-bin/koha/ "$intranetdir/cgi-bin/"
1215    ErrorLog $logfiledir/koha-error_log
1216    TransferLog $logfiledir/koha-access_log
1217    SetEnv PERL5LIB "$intranetdir/modules"
1218    SetEnv KOHA_CONF "$etcdir/koha.conf"
1219    $includesdirectives
1220 </VirtualHost>
1221
1222 # If you want to use name based Virtual Hosting:
1223 #   1. remove the two Listen lines
1224 #   2. replace $servername\:$opacport wih your.opac.domain.name
1225 #   3. replace ServerName $servername wih ServerName your.opac.domain.name
1226 #   4. replace $servername\:$intranetport wih your intranet domain name
1227 #   5. replace ServerName $servername wih ServerName your.intranet.domain.name
1228 #
1229 # If you want to use NameVirtualHost'ing (using two names on one ip address):
1230 #   1.  Follow steps 1-5 above
1231 #   2.  Uncomment the NameVirtualHost line and set the correct ip address
1232
1233 EOP
1234
1235
1236     }
1237 }
1238
1239
1240 =item basicauthentication
1241
1242     basicauthentication;
1243
1244 Asks the user whether HTTP basic authentication is wanted, and,
1245 if so, the user name and password for the basic authentication.
1246
1247 These pieces of information are saved to global variables; the
1248 function does not return any values.
1249
1250 =cut
1251
1252 $messages->{'IntranetAuthenticationQuestion'}->{en} =
1253    heading('INTRANET AUTHENTICATION') . qq|
1254 I can set it up so that the Intranet/Librarian site is password protected using
1255 Apache's Basic Authorization.
1256
1257 This is going to be phased out very soon. However, setting this up can provide
1258 an extra layer of security before the new authentication system is completely
1259 in place.
1260
1261 Would you like to do this ([Y]/N): |;   #'
1262
1263 $messages->{'BasicAuthUsername'}->{en}="Please enter a userid for intranet access [%s]: ";
1264 $messages->{'BasicAuthPassword'}->{en}="Please enter a password for %s: ";
1265 $messages->{'BasicAuthPasswordWasBlank'}->{en}="\nYou cannot use a blank password!\n\n";
1266
1267 sub basicauthentication {
1268     my $message=getmessage('IntranetAuthenticationQuestion');
1269     my $answer=showmessage($message, 'yn', 'y');
1270     my $httpdconf = $etcdir."/koha-httpd.conf";
1271
1272     my $apacheauthusername='librarian';
1273     my $apacheauthpassword='';
1274     if ($answer=~/^y/i) {
1275         ($apacheauthusername) = showmessage(getmessage('BasicAuthUsername', [ $apacheauthusername]), 'free', $apacheauthusername, 1);
1276         $apacheauthusername=~s/[^a-zA-Z0-9]//g;
1277         while (! $apacheauthpassword) {
1278             ($apacheauthpassword) = showmessage(getmessage('BasicAuthPassword', [ $apacheauthusername]), 'free', 1);
1279             if (!$apacheauthpassword) {
1280                 ($apacheauthpassword) = showmessage(getmessage('BasicAuthPasswordWasBlank'), 'none', '', 1);
1281             }
1282         }
1283         open AUTH, ">$etcdir/kohaintranet.pass";
1284         my $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
1285         my $salt=substr($chars, int(rand(length($chars))),1);
1286         $salt.=substr($chars, int(rand(length($chars))),1);
1287         print AUTH $apacheauthusername.":".crypt($apacheauthpassword, $salt)."\n";
1288         close AUTH;
1289         open(SITE,">>$httpdconf") or warn "Insufficient priveleges to open $realhttpdconf for writing.\n";
1290         print SITE <<EOP
1291
1292 <Directory $intranetdir>
1293     AuthUserFile $etcdir/kohaintranet.pass
1294     AuthType Basic
1295     AuthName "Koha Intranet (for librarians only)"
1296     Require  valid-user
1297 </Directory>
1298 EOP
1299     }
1300     close(SITE);
1301 }
1302
1303
1304 =item installfiles
1305
1306     installfiles
1307
1308 Install the Koha files to the specified OPAC and INTRANET
1309 directories (usually in /usr/local/koha).
1310
1311 The koha.conf file is created, but as koha.conf.tmp. The
1312 caller is responsible for calling finalizeconfigfile when
1313 installation is completed, to rename it back to koha.conf.
1314
1315 =cut
1316
1317 $messages->{'InstallFiles'}->{en} = heading('INSTALLING FILES') . qq|
1318 Copying files to installation directories:
1319
1320 |;
1321
1322
1323 $messages->{'CopyingFiles'}->{en}="Copying %s to %s.\n";
1324
1325
1326
1327 sub installfiles {
1328
1329         #MJR: preserve old files, just in case
1330         sub neatcopy {
1331                 my $desc = shift;
1332                 my $src = shift;
1333                 my $tgt = shift;
1334                 
1335                 if (-d $tgt) {
1336                 print getmessage('CopyingFiles', ["old ".$desc,$tgt.".old"]);
1337                         system("mv ".$tgt." ".$tgt.".old");
1338                 }
1339
1340         print getmessage('CopyingFiles', [$desc,$tgt]);
1341             system("cp -R ".$src." ".$tgt);
1342         }
1343
1344     showmessage(getmessage('InstallFiles'),'none');
1345
1346     neatcopy("admin templates", 'intranet-html', "$intranetdir/htdocs");
1347     neatcopy("admin interface", 'intranet-cgi', "$intranetdir/cgi-bin");
1348     neatcopy("main scripts", 'scripts', "$intranetdir/scripts");
1349     neatcopy("perl modules", 'modules', "$intranetdir/modules");
1350     neatcopy("OPAC templates", 'opac-html', "$opacdir/htdocs");
1351     neatcopy("OPAC interface", 'opac-cgi', "$opacdir/cgi-bin");
1352     system("touch $opacdir/cgi-bin/opac");
1353
1354         #MJR: is this necessary?
1355         if ($> == 0) {
1356             system("chown -R $httpduser:$httpduser $opacdir $intranetdir");
1357     }
1358         system("chmod -R a+rx $opacdir $intranetdir");
1359
1360     # Create /etc/koha.conf
1361
1362     my $old_umask = umask(027); # make sure koha.conf is never world-readable
1363     open(SITES,">$etcdir/koha.conf.tmp") or warn "Couldn't create file at $etcdir. Must have write capability.\n";
1364     print SITES qq|
1365 database=$dbname
1366 hostname=$hostname
1367 user=$user
1368 pass=$pass
1369 includes=$opacdir/htdocs/includes
1370 intranetdir=$intranetdir
1371 opacdir=$opacdir
1372 kohalogdir=$kohalogdir
1373 kohaversion=$kohaversion
1374 httpduser=$httpduser
1375 intrahtdocs=$intranetdir/htdocs/intranet-tmpl
1376 opachtdocs=$opacdir/htdocs/opac-tmpl
1377 |;
1378     close(SITES);
1379     umask($old_umask);
1380
1381         #MJR: can't help but this be broken, can we?
1382     chmod 0440, "$etcdir/koha.conf.tmp";
1383         
1384         #MJR: does this contain any passwords?
1385     chmod 0755, "$intranetdir/scripts/z3950daemon/z3950-daemon-launch.sh", "$intranetdir/scripts/z3950daemon/z3950-daemon-shell.sh", "$intranetdir/scripts/z3950daemon/processz3950queue";
1386
1387         if ($> == 0) {
1388             chown((getpwnam($httpduser)) [2,3], "$etcdir/koha.conf.tmp") or warn "can't chown koha.conf: $!";
1389         chown(0, (getpwnam($httpduser)) [3], "$intranetdir/scripts/z3950daemon/z3950-daemon-shell.sh") or warn "can't chown $intranetdir/scripts/z3950daemon/z3950-daemon-shell.sh: $!";
1390         chown(0, (getpwnam($httpduser)) [3], "$intranetdir/scripts/z3950daemon/processz3950queue") or warn "can't chown $intranetdir/scripts/z3950daemon/processz3950queue: $!";
1391         } #MJR: FIXME: Should report that we haven't chown()d.
1392 }
1393
1394
1395 =item databasesetup
1396
1397     databasesetup;
1398
1399 Finds out where the MySQL utitlities are located in the system,
1400 then create the Koha database structure and MySQL permissions.
1401
1402 =cut
1403
1404 $messages->{'MysqlRootPassword'}->{en} =
1405    heading('MYSQL ROOT USER PASSWORD') . qq|
1406 To allow us to create the koha database please enter your
1407 mysql server's root user password:
1408
1409 Password: |;    #'
1410
1411 $messages->{'CreatingDatabase'}->{en} = heading('CREATING DATABASE') . qq|
1412 Creating the MySQL database for Koha...
1413
1414 |;
1415
1416 $messages->{'CreatingDatabaseError'}->{en} =
1417    heading('ERROR CREATING DATABASE') . qq|
1418 Couldn't connect to the MySQL server for the reason given above.
1419 This is a serious problem, the database will not get installed.\a
1420
1421 Press <ENTER> to continue: |;   #'
1422
1423 $messages->{'SampleData'}->{en} = heading('SAMPLE DATA') . qq|
1424 If you are installing Koha for evaluation purposes,  I have a batch of sample
1425 data that you can install now.
1426
1427 If you are installing Koha with the intention of populating it with your own
1428 data, you probably don't want this sample data installed.
1429
1430 Would you like to install the sample data? Y/[N]: |;    #'
1431
1432 $messages->{'SampleDataInstalled'}->{en} =
1433    heading('SAMPLE DATA INSTALLED') . qq|
1434 Sample data has been installed.  For some suggestions on testing Koha, please
1435 read the file doc/HOWTO-Testing.  If you find any bugs, please submit them at
1436 http://bugs.koha.org/.  If you need help with testing Koha, you can post a
1437 question through the koha-devel mailing list, or you can check for a developer
1438 online at +irc.katipo.co.nz:6667 channel #koha.
1439
1440 You can find instructions for subscribing to the Koha mailing lists at:
1441
1442     http://www.koha.org
1443
1444
1445 Press <ENTER> to continue: |;
1446
1447 $messages->{'AddBranchPrinter'}->{en} = heading('Add Branch and Printer') . qq|
1448 Would you like to install an initial branch and printer? [Y]/N: |;
1449
1450 $messages->{'BranchName'}->{en}="Branch Name [%s]: ";
1451 $messages->{'BranchCode'}->{en}="Branch Code (4 letters or numbers) [%s]: ";
1452 $messages->{'PrinterQueue'}->{en}="Printer Queue [%s]: ";
1453 $messages->{'PrinterName'}->{en}="Printer Name [%s]: ";
1454
1455 sub databasesetup {
1456     $mysqluser = 'root';
1457     $mysqlpass = '';
1458
1459     foreach my $mysql (qw(/usr/local/mysql
1460                           /opt/mysql
1461                           /usr
1462                           )) {
1463        if ( -d $mysql  && -f "$mysql/bin/mysqladmin") {
1464             $mysqldir=$mysql;
1465        }
1466     }
1467     if (!$mysqldir){
1468         print "I don't see mysql in the usual places.\n";
1469         for (;;) {
1470             print "Where have you installed mysql? ";
1471             chomp($mysqldir = <STDIN>);
1472             last if -f "$mysqldir/bin/mysqladmin";
1473         print <<EOP;
1474
1475 I can't find it there either. If you compiled mysql yourself,
1476 please give the value of --prefix when you ran configure.
1477
1478 The file mysqladmin should be in bin/mysqladmin under the directory that you
1479 provide here.
1480
1481 EOP
1482 #'
1483         }
1484     }
1485     # we must not put the mysql root password on the command line
1486         $mysqlpass=     showmessage(getmessage('MysqlRootPassword'),'silentfree');
1487         
1488         showmessage(getmessage('CreatingDatabase'),'none');
1489         # set the login up
1490         setmysqlclipass($mysqlpass);
1491         # Set up permissions
1492         print system("$mysqldir/bin/mysql -u$mysqluser mysql -e \"insert into user (Host,User,Password) values ('$hostname','$user',password('$pass'))\"\;");
1493         system("$mysqldir/bin/mysql -u$mysqluser mysql -e \"insert into db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv, index_priv, alter_priv) values ('%','$dbname','$user','Y','Y','Y','Y','Y','Y','Y','Y')\"");
1494         system("$mysqldir/bin/mysqladmin -u$mysqluser reload");
1495         # Change to admin user login
1496         setmysqlclipass($pass);
1497         my $result=system("$mysqldir/bin/mysqladmin", "-u$user", "create", "$dbname");
1498         if ($result) {
1499                 showmessage(getmessage('CreatingDatabaseError'),'PressEnter', '', 1);
1500         } else {
1501                 # Create the database structure
1502                 system("$mysqldir/bin/mysql -u$user $dbname < koha.mysql");
1503         }
1504
1505 }
1506
1507
1508 =item updatedatabase
1509
1510     updatedatabase;
1511
1512 Updates the Koha database structure, including the addition of
1513 MARC tables.
1514
1515 The MARC tables are also populated in addition to being created.
1516
1517 Because updatedatabase calls scripts/updater/updatedatabase to
1518 do the actual update, and that script uses C4::Context,
1519 $etcdir/koha.conf must exist at this point. We use the KOHA_CONF
1520 environment variable to do this.
1521
1522 FIXME: (See checkabortedinstall as it depends on old symlink way.)
1523
1524 =cut
1525
1526 $messages->{'UpdateMarcTables'}->{en} =
1527    heading('UPDATING MARC FIELD DEFINITION TABLES') . qq|
1528 You can import marc parameters for :
1529
1530   1 MARC21
1531   2 UNIMARC
1532   N none
1533
1534 Please choose which parameter you want to install. Note if you choose N,
1535 nothing will be added, and it can be a BIG job to manually create those tables
1536
1537 Choose MARC definition [1]: |;
1538
1539 $messages->{'Language'}->{en} = heading('CHOOSE LANGUAGES') . qq|
1540 This version of koha supports a few languages.
1541 Enter your language preference : either en, fr, es, pl or zh_TW
1542
1543 Note that the en is always choosen when the system does not finds the
1544 language you choose in a specific screen.
1545
1546 fr : all is translated (except pictures)
1547 es : a few intranet is translated (including pictures)
1548 pl : OPAC and a few intranet is translated
1549 zh_TW : partial translation
1550
1551 Whether you specify a language here, you can always go to the
1552 intranet interface and change it from the system preferences.
1553
1554 Which language do you choose? |;
1555
1556 sub updatedatabase {
1557     # At this point, $etcdir/koha.conf must exist, for C4::Context
1558     $ENV{"KOHA_CONF"}=$etcdir.'/koha.conf.tmp';
1559         my $result=system ("perl -I $intranetdir/modules scripts/updater/updatedatabase");
1560         if ($result) {
1561                 restoremycnf();
1562                 print "Problem updating database...\n";
1563                 exit;
1564         }
1565
1566         my $response=showmessage(getmessage('UpdateMarcTables'), 'restrictchar 12N', '1');
1567
1568         if ($response eq '1') {
1569                 system("cat scripts/misc/marc_datas/marc21_en/structure_def.sql | $mysqldir/bin/mysql -u$user $dbname");
1570         }
1571         if ($response eq '2') {
1572                 system("cat scripts/misc/marc_datas/unimarc_fr/structure_def.sql | $mysqldir/bin/mysql -u$user $dbname");
1573                 system("cat scripts/misc/lang-datas/fr/stopwords.sql | $mysqldir/bin/mysql -u$user $dbname");
1574         }
1575
1576         $result = system ("perl -I $intranetdir/modules scripts/marc/updatedb2marc.pl");
1577         if ($result) {
1578                 print "Problem updating database to MARC...\n";
1579                 restoremycnf();
1580                 exit;
1581         }
1582         delete($ENV{"KOHA_CONF"});
1583
1584         print "\n\nFinished updating of database. Press <ENTER> to continue...";
1585         <STDIN>;
1586 }
1587
1588
1589 =item populatedatabase
1590
1591     populatedatabase;
1592
1593 Populate the non-MARC tables. If the user wants to install the
1594 sample data, install them.
1595
1596 =cut
1597
1598 sub populatedatabase {
1599 #       my $response=showmessage(getmessage('SampleData'), 'yn', 'n');
1600 #       if ($response =~/^y/i) {
1601 #
1602 # FIXME: These calls are now unsafe and should either be removed
1603 # or updated to use -u$user and no mysqlpass_quoted
1604 #
1605 #               system("gunzip -d < sampledata-1.2.gz | $mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname");
1606 #               system("$mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname -e \"insert into branches (branchcode,branchname,issuing) values ('MAIN', 'Main Library', 1)\"");
1607 #               system("$mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'IS')\"");
1608 #               system("$mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'CU')\"");
1609 #               system("$mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname -e \"insert into printers (printername,printqueue,printtype) values ('Circulation Desk Printer', 'lp', 'hp')\"");
1610 #               showmessage(getmessage('SampleDataInstalled'), 'PressEnter','',1);
1611 #       } else {
1612                 my $input;
1613                 my $response=showmessage(getmessage('AddBranchPrinter'), 'yn', 'y');
1614
1615                 unless ($response =~/^n/i) {
1616                 my $branch='Main Library';
1617                 $branch=showmessage(getmessage('BranchName', [$branch]), 'free', $branch, 1);
1618                 $branch=~s/[^A-Za-z0-9\s]//g;
1619
1620                 my $branchcode=$branch;
1621                 $branchcode=~s/[^A-Za-z0-9]//g;
1622                 $branchcode=uc($branchcode);
1623                 $branchcode=substr($branchcode,0,4);
1624                 $branchcode=showmessage(getmessage('BranchCode', [$branchcode]), 'free', $branchcode, 1);
1625                 $branchcode=~s/[^A-Za-z0-9]//g;
1626                 $branchcode=uc($branchcode);
1627                 $branchcode=substr($branchcode,0,4);
1628                 $branchcode or $branchcode='DEF';
1629
1630                 system("$mysqldir/bin/mysql -u$user $dbname -e \"insert into branches (branchcode,branchname,issuing) values ('$branchcode', '$branch', 1)\"");
1631                 system("$mysqldir/bin/mysql -u$user $dbname -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'IS')\"");
1632                 system("$mysqldir/bin/mysql -u$user $dbname -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'CU')\"");
1633
1634                 my $printername='Library Printer';
1635                 $printername=showmessage(getmessage('PrinterName', [$printername]), 'free', $printername, 1);
1636                 $printername=~s/[^A-Za-z0-9\s]//g;
1637
1638                 my $printerqueue='lp';
1639                 $printerqueue=showmessage(getmessage('PrinterQueue', [$printerqueue]), 'free', $printerqueue, 1);
1640                 $printerqueue=~s/[^A-Za-z0-9]//g;
1641                 system("$mysqldir/bin/mysql -u$user $dbname -e \"insert into printers (printername,printqueue,printtype) values ('$printername', '$printerqueue', '')\"");
1642 #               }
1643         my $language=showmessage(getmessage('Language'), 'free', 'en');
1644         system("$mysqldir/bin/mysql -u$user $dbname -e \"update systempreferences set value='$language' where variable='opaclanguages'\"");
1645         }
1646 }
1647
1648
1649 =item restartapache
1650
1651     restartapache;
1652
1653 Asks the user whether to restart Apache, and restart it if the user
1654 wants so.
1655
1656 FIXME: If the installer does not know how to restart the Apache
1657 server (e.g., if the user is not actually using Apache), it still
1658 asks the question.
1659
1660 =cut
1661
1662 $messages->{'RestartApache'}->{en} = heading('RESTART APACHE') . qq|
1663 Apache needs to be restarted to load the new configuration for Koha.
1664 This requires the root password.
1665
1666 Would you like to try to restart Apache now?  [Y]/N: |;
1667
1668 sub restartapache {
1669
1670     my $response=showmessage(getmessage('RestartApache'), 'yn', 'y');
1671
1672
1673
1674     unless ($response=~/^n/i) {
1675         # Need to support other init structures here?
1676         if (-e "/etc/rc.d/init.d/httpd") {
1677             system('su root -c /etc/rc.d/init.d/httpd restart');
1678         } elsif (-e "/etc/init.d/apache") {
1679             system('su root -c /etc//init.d/apache restart');
1680         } elsif (-e "/etc/init.d/apache-ssl") {
1681             system('su root -c /etc/init.d/apache-ssl restart');
1682         }
1683     }
1684
1685 }
1686
1687
1688 =item finalizeconfigfile
1689
1690    finalizeconfigfile;
1691
1692 This function must be called when the installation is complete,
1693 to rename the koha.conf.tmp file to koha.conf.
1694
1695 Currently, failure to rename the file results only in a warning.
1696
1697 =cut
1698
1699 sub finalizeconfigfile {
1700         restoremycnf();
1701    rename "$etcdir/koha.conf.tmp", "$etcdir/koha.conf"
1702       || showmessage(<<EOF, 'PressEnter', undef, 1);
1703 An unexpected error, $!, occurred
1704 while the Koha config file is being saved to its final location,
1705 $etcdir/koha.conf.
1706
1707 Couldn't rename file at $etcdir. Must have write capability.
1708
1709 Press Enter to continue.
1710 EOF
1711 #'
1712 }
1713
1714
1715 =item loadconfigfile
1716
1717    loadconfigfile
1718
1719 Open the existing koha.conf file and get its values,
1720 saving the values to some global variables.
1721
1722 If the existing koha.conf file cannot be opened for any reason,
1723 the file is silently ignored.
1724
1725 =cut
1726
1727 sub loadconfigfile {
1728     my %configfile;
1729
1730     open (KC, "<$etcdir/koha.conf");
1731     while (<KC>) {
1732      chomp;
1733      (next) if (/^\s*#/);
1734      if (/(.*)\s*=\s*(.*)/) {
1735        my $variable=$1;
1736        my $value=$2;
1737        # Clean up white space at beginning and end
1738        $variable=~s/^\s*//g;
1739        $variable=~s/\s*$//g;
1740        $value=~s/^\s*//g;
1741        $value=~s/\s*$//g;
1742        $configfile{$variable}=$value;
1743      }
1744     }
1745
1746     $intranetdir=$configfile{'intranetdir'};
1747     $opacdir=$configfile{'opacdir'};
1748     $kohaversion=$configfile{'kohaversion'};
1749     $kohalogdir=$configfile{'kohalogdir'};
1750     $database=$configfile{'database'};
1751     $hostname=$configfile{'hostname'};
1752     $user=$configfile{'user'};
1753     $pass=$configfile{'pass'};
1754 }
1755
1756 END { }       # module clean-up code here (global destructor)
1757
1758 ### These things may move
1759
1760 sub setecho {
1761 my $state=shift;
1762 my $t = POSIX::Termios->new;
1763
1764 $t->getattr();
1765 if ($state) {
1766   $t->setlflag(($t->getlflag) | &POSIX::ECHO);
1767   }
1768 else {
1769   $t->setlflag(($t->getlflag) & !(&POSIX::ECHO));
1770   }
1771 $t->setattr();
1772 }
1773
1774 sub setmysqlclipass {
1775         my $pass = shift;
1776         open(MYCNF,">$mycnf");
1777         chmod(0600,$mycnf);
1778         print MYCNF "[client]\npassword=$pass\n";
1779         close(MYCNF);
1780 }
1781
1782 sub backupmycnf {
1783         if (-e $mycnf) {
1784                 rename $mycnf,$mytmpcnf;
1785         }
1786 }
1787
1788 sub restoremycnf {
1789         if (-e $mycnf) {
1790                 unlink($mycnf);
1791         }
1792         if (-e $mytmpcnf) {
1793                 rename $mytmpcnf,$mycnf;
1794         }
1795 }
1796
1797 =back
1798
1799 =head1 SEE ALSO
1800
1801 buildrelease.pl,
1802 installer.pl
1803
1804 =cut
1805
1806 1;