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