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