Initial fix to bug 417: non-root installer
[koha_fer] / 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 setup your 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 httpd.conf detailing
1024 what these other options are.
1025
1026
1027 Press <ENTER> to continue: |;
1028
1029 $messages->{'GetVirtualHostEmail'}->{en} =
1030    heading('WEB SERVER E-MAIL CONTACT') . qq|
1031 Enter the e-mail address to be used as a contact for the virtual hosts (this
1032 address is displayed if any errors are encountered).
1033
1034 E-mail contact [%s]: |;
1035
1036 $messages->{'GetServerName'}->{en} =
1037    heading('WEB SERVER HOST NAME OR IP ADDRESS') . qq|
1038 Please enter the host name or IP address that you wish to use for koha.
1039 Normally, this should be a name or IP that belongs to this machine.
1040
1041 Host name or IP Address [%s]: |;
1042
1043 $messages->{'GetOpacPort'}->{en} = heading('OPAC VIRTUAL HOST PORT') . qq|
1044 Please enter the port for your OPAC interface.  This defaults to port 80, but
1045 if you are already serving web content from this host, you should change it
1046 to a different port (8000 might be a good choice).
1047
1048 Enter the OPAC Port [%s]: |;
1049
1050 $messages->{'GetIntranetPort'}->{en} =
1051    heading('INTRANET VIRTUAL HOST PORT') . qq|
1052 Please enter the port for your Intranet interface.  This must be different from
1053 the OPAC port (%s).
1054
1055 Enter the Intranet Port [%s]: |;
1056
1057
1058 sub getapachevhostinfo {
1059
1060     $svr_admin = "webmaster\@$domainname";
1061     $servername=`hostname`;
1062     chomp $servername;
1063     $opacport=80;
1064     $intranetport=8080;
1065
1066     showmessage(getmessage('ApacheConfigIntroduction'), 'PressEnter');
1067
1068     $svr_admin=showmessage(getmessage('GetVirtualHostEmail', [$svr_admin]), 'email', $svr_admin);
1069     $servername=showmessage(getmessage('GetServerName', [$servername]), 'free', $servername);
1070
1071
1072     $opacport=showmessage(getmessage('GetOpacPort', [$opacport]), 'numerical', $opacport);
1073     $intranetport=showmessage(getmessage('GetIntranetPort', [$opacport, $intranetport]), 'numerical', $intranetport);
1074
1075 }
1076
1077
1078 =item updateapacheconf
1079
1080     updateapacheconf;
1081
1082 Updates the Apache config file according to parameters previously
1083 specified by the user.
1084
1085 It will append fully-commented directives at the end of the original
1086 Apache config file.  The old config file is renamed with an extension
1087 of .prekoha.
1088
1089 If you need to uninstall Koha for any reason, the lines between
1090
1091     # Ports to listen to for Koha
1092
1093 and the block of comments beginning with
1094
1095     # If you want to use name based Virtual Hosting:
1096
1097 must be removed.
1098
1099 =cut
1100
1101 $messages->{'StartUpdateApache'}->{en} =
1102    heading('UPDATING APACHE CONFIGURATION') . qq|
1103 Checking for modules that need to be loaded...
1104 |;
1105
1106 $messages->{'ApacheConfigMissingModules'}->{en} =
1107    heading('APACHE CONFIGURATION NEEDS UPDATE') . qq|
1108 Koha uses the mod_env and mod_include apache features, but the
1109 installer did not find statements for them in your config.  Please
1110 make sure that they are enabled for your Koha host.
1111
1112 Press <ENTER> to continue: |;
1113
1114
1115 $messages->{'ApacheAlreadyConfigured'}->{en} =
1116    heading('APACHE ALREADY CONFIGURED') . qq|
1117 %s appears to already have an entry for Koha
1118 Virtual Hosts.  You may need to edit %s
1119 if anything has changed since it was last set up.  This
1120 script will not attempt to modify an existing Koha apache
1121 configuration.
1122
1123 Press <ENTER> to continue: |;
1124
1125 sub updateapacheconf {
1126     my $logfiledir=`grep ^ErrorLog "$realhttpdconf"`;
1127     chomp $logfiledir;
1128     
1129     my $httpdconf = $etcdir."/httpd.conf";
1130
1131     if ($logfiledir) {
1132         $logfiledir=~m#ErrorLog (.*)/[^/]*$#
1133             or die "Can't parse ErrorLog directive\n";
1134         $logfiledir=$1;
1135     }
1136
1137     unless ($logfiledir) {
1138         $logfiledir='logs';
1139     }
1140
1141     showmessage(getmessage('StartUpdateApache'), 'none');
1142         # to be polite about it: I don't think this should touch the main httpd.conf
1143
1144         # QUESTION: Should we warn for includes_module too?
1145     my $envmodule=0;
1146     my $includesmodule=0;
1147     open HC, "<$realhttpdconf";
1148     while (<HC>) {
1149         if (/^\s*#\s*LoadModule env_module /) {
1150             showmessage(getmessage('ApacheConfigMissingModules'));
1151             $envmodule=1;
1152         }
1153         if (/\s*LoadModule includes_module / ) {
1154             $includesmodule=1;
1155         }
1156     }
1157
1158     if (`grep 'VirtualHost $servername' "$httpdconf"`) {
1159         showmessage(getmessage('ApacheAlreadyConfigured', [$httpdconf, $httpdconf]), 'PressEnter');
1160         return;
1161     } else {
1162         my $includesdirectives='';
1163         if ($includesmodule) {
1164             $includesdirectives.="Options +Includes\n";
1165             $includesdirectives.="   AddHandler server-parsed .html\n";
1166         }
1167         open(SITE,">$httpdconf") or warn "Insufficient priveleges to open $httpdconf for writing.\n";
1168         my $opaclisten = '';
1169         if ($opacport != 80) {
1170             $opaclisten="Listen $opacport";
1171         }
1172         my $intranetlisten = '';
1173         if ($intranetport != 80) {
1174             $intranetlisten="Listen $intranetport";
1175         }
1176         print SITE <<EOP
1177
1178 # Ports to listen to for Koha
1179 $opaclisten
1180 $intranetlisten
1181
1182 # NameVirtualHost is used by one of the optional configurations detailed below
1183
1184 #NameVirtualHost 11.22.33.44
1185
1186 # KOHA's OPAC Configuration
1187 <VirtualHost $servername\:$opacport>
1188    ServerAdmin $svr_admin
1189    DocumentRoot $opacdir/htdocs
1190    ServerName $servername
1191    ScriptAlias /cgi-bin/koha/ $opacdir/cgi-bin/
1192    ErrorLog $logfiledir/opac-error_log
1193    TransferLog $logfiledir/opac-access_log
1194    SetEnv PERL5LIB "$intranetdir/modules"
1195    $includesdirectives
1196 </VirtualHost>
1197
1198 # KOHA's INTRANET Configuration
1199 <VirtualHost $servername\:$intranetport>
1200    ServerAdmin $svr_admin
1201    DocumentRoot $intranetdir/htdocs
1202    ServerName $servername
1203    ScriptAlias /cgi-bin/koha/ "$intranetdir/cgi-bin/"
1204    ErrorLog $logfiledir/koha-error_log
1205    TransferLog $logfiledir/koha-access_log
1206    SetEnv PERL5LIB "$intranetdir/modules"
1207    $includesdirectives
1208 </VirtualHost>
1209
1210 # If you want to use name based Virtual Hosting:
1211 #   1. remove the two Listen lines
1212 #   2. replace $servername\:$opacport wih your.opac.domain.name
1213 #   3. replace ServerName $servername wih ServerName your.opac.domain.name
1214 #   4. replace $servername\:$intranetport wih your intranet domain name
1215 #   5. replace ServerName $servername wih ServerName your.intranet.domain.name
1216 #
1217 # If you want to use NameVirtualHost'ing (using two names on one ip address):
1218 #   1.  Follow steps 1-5 above
1219 #   2.  Uncomment the NameVirtualHost line and set the correct ip address
1220
1221 EOP
1222
1223
1224     }
1225 }
1226
1227
1228 =item basicauthentication
1229
1230     basicauthentication;
1231
1232 Asks the user whether HTTP basic authentication is wanted, and,
1233 if so, the user name and password for the basic authentication.
1234
1235 These pieces of information are saved to global variables; the
1236 function does not return any values.
1237
1238 =cut
1239
1240 $messages->{'IntranetAuthenticationQuestion'}->{en} =
1241    heading('INTRANET AUTHENTICATION') . qq|
1242 I can set it up so that the Intranet/Librarian site is password protected using
1243 Apache's Basic Authorization.
1244
1245 This is going to be phased out very soon. However, setting this up can provide
1246 an extra layer of security before the new authentication system is completely
1247 in place.
1248
1249 Would you like to do this ([Y]/N): |;   #'
1250
1251 $messages->{'BasicAuthUsername'}->{en}="Please enter a userid for intranet access [%s]: ";
1252 $messages->{'BasicAuthPassword'}->{en}="Please enter a password for %s: ";
1253 $messages->{'BasicAuthPasswordWasBlank'}->{en}="\nYou cannot use a blank password!\n\n";
1254
1255 sub basicauthentication {
1256     my $message=getmessage('IntranetAuthenticationQuestion');
1257     my $answer=showmessage($message, 'yn', 'y');
1258
1259     my $apacheauthusername='librarian';
1260     my $apacheauthpassword='';
1261     if ($answer=~/^y/i) {
1262         ($apacheauthusername) = showmessage(getmessage('BasicAuthUsername', [ $apacheauthusername]), 'free', $apacheauthusername, 1);
1263         $apacheauthusername=~s/[^a-zA-Z0-9]//g;
1264         while (! $apacheauthpassword) {
1265             ($apacheauthpassword) = showmessage(getmessage('BasicAuthPassword', [ $apacheauthusername]), 'free', 1);
1266             if (!$apacheauthpassword) {
1267                 ($apacheauthpassword) = showmessage(getmessage('BasicAuthPasswordWasBlank'), 'none', '', 1);
1268             }
1269         }
1270         open AUTH, ">$etcdir/kohaintranet.pass";
1271         my $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
1272         my $salt=substr($chars, int(rand(length($chars))),1);
1273         $salt.=substr($chars, int(rand(length($chars))),1);
1274         print AUTH $apacheauthusername.":".crypt($apacheauthpassword, $salt)."\n";
1275         close AUTH;
1276         open(SITE,">>$realhttpdconf") or warn "Insufficient priveleges to open $realhttpdconf for writing.\n";
1277         print SITE <<EOP
1278
1279 <Directory $intranetdir>
1280     AuthUserFile $etcdir/kohaintranet.pass
1281     AuthType Basic
1282     AuthName "Koha Intranet (for librarians only)"
1283     Require  valid-user
1284 </Directory>
1285 EOP
1286     }
1287     close(SITE);
1288 }
1289
1290
1291 =item installfiles
1292
1293     installfiles
1294
1295 Install the Koha files to the specified OPAC and INTRANET
1296 directories (usually in /usr/local/koha).
1297
1298 The koha.conf file is created, but as koha.conf.tmp. The
1299 caller is responsible for calling finalizeconfigfile when
1300 installation is completed, to rename it back to koha.conf.
1301
1302 =cut
1303
1304 $messages->{'InstallFiles'}->{en} = heading('INSTALLING FILES') . qq|
1305 Copying files to installation directories:
1306
1307 |;
1308
1309
1310 $messages->{'CopyingFiles'}->{en}="Copying %s to %s.\n";
1311
1312
1313
1314 sub installfiles {
1315
1316
1317     showmessage(getmessage('InstallFiles'),'none');
1318     print getmessage('CopyingFiles', ['intranet-html', "$intranetdir/htdocs" ]);
1319     system("cp -R intranet-html/* $intranetdir/htdocs/");
1320     print getmessage('CopyingFiles', ['intranet-cgi', "$intranetdir/cgi-bin" ]);
1321     system("cp -R intranet-cgi/* $intranetdir/cgi-bin/");
1322     print getmessage('CopyingFiles', ['stand-alone scripts', "$intranetdir/scripts" ]);
1323     system("cp -R scripts/* $intranetdir/scripts/");
1324     print getmessage('CopyingFiles', ['perl modules', "$intranetdir/modules" ]);
1325     system("cp -R modules/* $intranetdir/modules/");
1326     print getmessage('CopyingFiles', ['opac-html', "$opacdir/htdocs" ]);
1327     system("cp -R opac-html/* $opacdir/htdocs/");
1328     print getmessage('CopyingFiles', ['opac-cgi', "$opacdir/cgi-bin" ]);
1329     system("cp -R opac-cgi/* $opacdir/cgi-bin/");
1330     system("touch $opacdir/cgi-bin/opac");
1331
1332     system("chown -R $httpduser:$httpduser $opacdir");
1333     system("chown -R $httpduser:$httpduser $intranetdir");
1334
1335     # Create /etc/koha.conf
1336
1337     my $old_umask = umask(027); # make sure koha.conf is never world-readable
1338     open(SITES,">$etcdir/koha.conf.tmp") or warn "Couldn't create file at $etcdir. Must have write capability.\n";
1339     print SITES qq|
1340 database=$dbname
1341 hostname=$hostname
1342 user=$user
1343 pass=$pass
1344 includes=$opacdir/htdocs/includes
1345 intranetdir=$intranetdir
1346 opacdir=$opacdir
1347 kohalogdir=$kohalogdir
1348 kohaversion=$kohaversion
1349 httpduser=$httpduser
1350 intrahtdocs=$intranetdir/htdocs/intranet-tmpl
1351 opachtdocs=$opacdir/htdocs/opac-tmpl
1352 |;
1353     close(SITES);
1354     umask($old_umask);
1355
1356     chown((getpwnam($httpduser)) [2,3], "$etcdir/koha.conf.tmp") or warn "can't chown koha.conf: $!";
1357     chmod 0440, "$etcdir/koha.conf.tmp";
1358
1359     chmod 0750, "$intranetdir/scripts/z3950daemon/z3950-daemon-launch.sh";
1360     chmod 0750, "$intranetdir/scripts/z3950daemon/z3950-daemon-shell.sh";
1361     chmod 0750, "$intranetdir/scripts/z3950daemon/processz3950queue";
1362     chown(0, (getpwnam($httpduser)) [3], "$intranetdir/scripts/z3950daemon/z3950-daemon-shell.sh") or warn "can't chown $intranetdir/scripts/z3950daemon/z3950-daemon-shell.sh: $!";
1363     chown(0, (getpwnam($httpduser)) [3], "$intranetdir/scripts/z3950daemon/processz3950queue") or warn "can't chown $intranetdir/scripts/z3950daemon/processz3950queue: $!";
1364
1365 }
1366
1367
1368 =item databasesetup
1369
1370     databasesetup;
1371
1372 Finds out where the MySQL utitlities are located in the system,
1373 then create the Koha database structure and MySQL permissions.
1374
1375 =cut
1376
1377 $messages->{'MysqlRootPassword'}->{en} =
1378    heading('MYSQL ROOT USER PASSWORD') . qq|
1379 To allow us to create the koha database please enter your
1380 mysql server's root user password:
1381
1382 Password: |;    #'
1383
1384 $messages->{'CreatingDatabase'}->{en} = heading('CREATING DATABASE') . qq|
1385 Creating the MySQL database for Koha...
1386
1387 |;
1388
1389 $messages->{'CreatingDatabaseError'}->{en} =
1390    heading('ERROR CREATING DATABASE') . qq|
1391 Couldn't connect to the MySQL server for the reason given above.
1392 This is a serious problem, the database will not get installed.\a
1393
1394 Press <ENTER> to continue: |;   #'
1395
1396 $messages->{'SampleData'}->{en} = heading('SAMPLE DATA') . qq|
1397 If you are installing Koha for evaluation purposes,  I have a batch of sample
1398 data that you can install now.
1399
1400 If you are installing Koha with the intention of populating it with your own
1401 data, you probably don't want this sample data installed.
1402
1403 Would you like to install the sample data? Y/[N]: |;    #'
1404
1405 $messages->{'SampleDataInstalled'}->{en} =
1406    heading('SAMPLE DATA INSTALLED') . qq|
1407 Sample data has been installed.  For some suggestions on testing Koha, please
1408 read the file doc/HOWTO-Testing.  If you find any bugs, please submit them at
1409 http://bugs.koha.org/.  If you need help with testing Koha, you can post a
1410 question through the koha-devel mailing list, or you can check for a developer
1411 online at +irc.katipo.co.nz:6667 channel #koha.
1412
1413 You can find instructions for subscribing to the Koha mailing lists at:
1414
1415     http://www.koha.org
1416
1417
1418 Press <ENTER> to continue: |;
1419
1420 $messages->{'AddBranchPrinter'}->{en} = heading('Add Branch and Printer') . qq|
1421 Would you like to install an initial branch and printer? [Y]/N: |;
1422
1423 $messages->{'BranchName'}->{en}="Branch Name [%s]: ";
1424 $messages->{'BranchCode'}->{en}="Branch Code (4 letters or numbers) [%s]: ";
1425 $messages->{'PrinterQueue'}->{en}="Printer Queue [%s]: ";
1426 $messages->{'PrinterName'}->{en}="Printer Name [%s]: ";
1427
1428 sub databasesetup {
1429     $mysqluser = 'root';
1430     $mysqlpass = '';
1431
1432     foreach my $mysql (qw(/usr/local/mysql
1433                           /opt/mysql
1434                           /usr
1435                           )) {
1436        if ( -d $mysql  && -f "$mysql/bin/mysqladmin") {
1437             $mysqldir=$mysql;
1438        }
1439     }
1440     if (!$mysqldir){
1441         print "I don't see mysql in the usual places.\n";
1442         for (;;) {
1443             print "Where have you installed mysql? ";
1444             chomp($mysqldir = <STDIN>);
1445             last if -f "$mysqldir/bin/mysqladmin";
1446         print <<EOP;
1447
1448 I can't find it there either. If you compiled mysql yourself,
1449 please give the value of --prefix when you ran configure.
1450
1451 The file mysqladmin should be in bin/mysqladmin under the directory that you
1452 provide here.
1453
1454 EOP
1455 #'
1456         }
1457     }
1458     # we must not put the mysql root password on the command line
1459         $mysqlpass=     showmessage(getmessage('MysqlRootPassword'),'free');
1460         
1461         showmessage(getmessage('CreatingDatabase'),'none');
1462         # set the login up
1463         setmysqlclipass($mysqlpass);
1464         # Set up permissions
1465         print system("$mysqldir/bin/mysql -u$mysqluser mysql -e \"insert into user (Host,User,Password) values ('$hostname','$user',password('$pass'))\"\;");
1466         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')\"");
1467         system("$mysqldir/bin/mysqladmin -u$mysqluser reload");
1468         # Change to admin user login
1469         setmysqlclipass($pass);
1470         my $result=system("$mysqldir/bin/mysqladmin", "-u$user", "create", "$dbname");
1471         if ($result) {
1472                 showmessage(getmessage('CreatingDatabaseError'),'PressEnter', '', 1);
1473         } else {
1474                 # Create the database structure
1475                 system("$mysqldir/bin/mysql -u$user $dbname < koha.mysql");
1476         }
1477
1478 }
1479
1480
1481 =item updatedatabase
1482
1483     updatedatabase;
1484
1485 Updates the Koha database structure, including the addition of
1486 MARC tables.
1487
1488 The MARC tables are also populated in addition to being created.
1489
1490 Because updatedatabase calls scripts/updater/updatedatabase to
1491 do the actual update, and that script uses C4::Context,
1492 $etcdir/koha.conf must exist at this point. We use the KOHA_CONF
1493 environment variable to do this.
1494
1495 FIXME: (See checkabortedinstall as it depends on old symlink way.)
1496
1497 =cut
1498
1499 $messages->{'UpdateMarcTables'}->{en} =
1500    heading('UPDATING MARC FIELD DEFINITION TABLES') . qq|
1501 You can import marc parameters for :
1502
1503   1 MARC21
1504   2 UNIMARC
1505   N none
1506
1507 Please choose which parameter you want to install. Note if you choose N,
1508 nothing will be added, and it can be a BIG job to manually create those tables
1509
1510 Choose MARC definition [1]: |;
1511
1512 $messages->{'Language'}->{en} = heading('CHOOSE LANGUAGES') . qq|
1513 This version of koha supports a few languages.
1514 Enter your language preference : either en, fr, es, pl or zh_TW
1515
1516 Note that the en is always choosen when the system does not finds the
1517 language you choose in a specific screen.
1518
1519 fr : all is translated (except pictures)
1520 es : a few intranet is translated (including pictures)
1521 pl : OPAC and a few intranet is translated
1522 zh_TW : partial translation
1523
1524 Whether you specify a language here, you can always go to the
1525 intranet interface and change it from the system preferences.
1526
1527 Which language do you choose? |;
1528
1529 sub updatedatabase {
1530     # At this point, $etcdir/koha.conf must exist, for C4::Context
1531     $ENV{"KOHA_CONF"}=$etcdir.'/koha.conf.tmp';
1532         my $result=system ("perl -I $intranetdir/modules scripts/updater/updatedatabase");
1533         if ($result) {
1534                 restoremycnf();
1535                 print "Problem updating database...\n";
1536                 exit;
1537         }
1538
1539         my $response=showmessage(getmessage('UpdateMarcTables'), 'restrictchar 12N', '1');
1540
1541         if ($response eq '1') {
1542                 system("cat scripts/misc/marc_datas/marc21_en/structure_def.sql | $mysqldir/bin/mysql -u$user $dbname");
1543         }
1544         if ($response eq '2') {
1545                 system("cat scripts/misc/marc_datas/unimarc_fr/structure_def.sql | $mysqldir/bin/mysql -u$user $dbname");
1546                 system("cat scripts/misc/lang-datas/fr/stopwords.sql | $mysqldir/bin/mysql -u$user $dbname");
1547         }
1548
1549         $result = system ("perl -I $intranetdir/modules scripts/marc/updatedb2marc.pl");
1550         if ($result) {
1551                 print "Problem updating database to MARC...\n";
1552                 restoremycnf();
1553                 exit;
1554         }
1555         delete($ENV{"KOHA_CONF"});
1556
1557         print "\n\nFinished updating of database. Press <ENTER> to continue...";
1558         <STDIN>;
1559 }
1560
1561
1562 =item populatedatabase
1563
1564     populatedatabase;
1565
1566 Populate the non-MARC tables. If the user wants to install the
1567 sample data, install them.
1568
1569 =cut
1570
1571 sub populatedatabase {
1572 #       my $response=showmessage(getmessage('SampleData'), 'yn', 'n');
1573 #       if ($response =~/^y/i) {
1574 #
1575 # FIXME: These calls are now unsafe and should either be removed
1576 # or updated to use -u$user and no mysqlpass_quoted
1577 #
1578 #               system("gunzip -d < sampledata-1.2.gz | $mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname");
1579 #               system("$mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname -e \"insert into branches (branchcode,branchname,issuing) values ('MAIN', 'Main Library', 1)\"");
1580 #               system("$mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'IS')\"");
1581 #               system("$mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'CU')\"");
1582 #               system("$mysqldir/bin/mysql -u$mysqluser $mysqlpass_quoted $dbname -e \"insert into printers (printername,printqueue,printtype) values ('Circulation Desk Printer', 'lp', 'hp')\"");
1583 #               showmessage(getmessage('SampleDataInstalled'), 'PressEnter','',1);
1584 #       } else {
1585                 my $input;
1586                 my $response=showmessage(getmessage('AddBranchPrinter'), 'yn', 'y');
1587
1588                 unless ($response =~/^n/i) {
1589                 my $branch='Main Library';
1590                 $branch=showmessage(getmessage('BranchName', [$branch]), 'free', $branch, 1);
1591                 $branch=~s/[^A-Za-z0-9\s]//g;
1592
1593                 my $branchcode=$branch;
1594                 $branchcode=~s/[^A-Za-z0-9]//g;
1595                 $branchcode=uc($branchcode);
1596                 $branchcode=substr($branchcode,0,4);
1597                 $branchcode=showmessage(getmessage('BranchCode', [$branchcode]), 'free', $branchcode, 1);
1598                 $branchcode=~s/[^A-Za-z0-9]//g;
1599                 $branchcode=uc($branchcode);
1600                 $branchcode=substr($branchcode,0,4);
1601                 $branchcode or $branchcode='DEF';
1602
1603                 system("$mysqldir/bin/mysql -u$user $dbname -e \"insert into branches (branchcode,branchname,issuing) values ('$branchcode', '$branch', 1)\"");
1604                 system("$mysqldir/bin/mysql -u$user $dbname -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'IS')\"");
1605                 system("$mysqldir/bin/mysql -u$user $dbname -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'CU')\"");
1606
1607                 my $printername='Library Printer';
1608                 $printername=showmessage(getmessage('PrinterName', [$printername]), 'free', $printername, 1);
1609                 $printername=~s/[^A-Za-z0-9\s]//g;
1610
1611                 my $printerqueue='lp';
1612                 $printerqueue=showmessage(getmessage('PrinterQueue', [$printerqueue]), 'free', $printerqueue, 1);
1613                 $printerqueue=~s/[^A-Za-z0-9]//g;
1614                 system("$mysqldir/bin/mysql -u$user $dbname -e \"insert into printers (printername,printqueue,printtype) values ('$printername', '$printerqueue', '')\"");
1615 #               }
1616         my $language=showmessage(getmessage('Language'), 'free', 'en');
1617         system("$mysqldir/bin/mysql -u$user $dbname -e \"update systempreferences set value='$language' where variable='opaclanguages'\"");
1618         }
1619 }
1620
1621
1622 =item restartapache
1623
1624     restartapache;
1625
1626 Asks the user whether to restart Apache, and restart it if the user
1627 wants so.
1628
1629 FIXME: If the installer does not know how to restart the Apache
1630 server (e.g., if the user is not actually using Apache), it still
1631 asks the question.
1632
1633 =cut
1634
1635 $messages->{'RestartApache'}->{en} = heading('RESTART APACHE') . qq|
1636 Apache needs to be restarted to load the new configuration for Koha.
1637 This requires the root password.
1638
1639 Would you like to try to restart Apache now?  [Y]/N: |;
1640
1641 sub restartapache {
1642
1643     my $response=showmessage(getmessage('RestartApache'), 'yn', 'y');
1644
1645
1646
1647     unless ($response=~/^n/i) {
1648         # Need to support other init structures here?
1649         if (-e "/etc/rc.d/init.d/httpd") {
1650             system('su root -c /etc/rc.d/init.d/httpd restart');
1651         } elsif (-e "/etc/init.d/apache") {
1652             system('su root -c /etc//init.d/apache restart');
1653         } elsif (-e "/etc/init.d/apache-ssl") {
1654             system('su root -c /etc/init.d/apache-ssl restart');
1655         }
1656     }
1657
1658 }
1659
1660
1661 =item finalizeconfigfile
1662
1663    finalizeconfigfile;
1664
1665 This function must be called when the installation is complete,
1666 to rename the koha.conf.tmp file to koha.conf.
1667
1668 Currently, failure to rename the file results only in a warning.
1669
1670 =cut
1671
1672 sub finalizeconfigfile {
1673         restoremycnf();
1674    rename "$etcdir/koha.conf.tmp", "$etcdir/koha.conf"
1675       || showmessage(<<EOF, 'PressEnter', undef, 1);
1676 An unexpected error, $!, occurred
1677 while the Koha config file is being saved to its final location,
1678 $etcdir/koha.conf.
1679
1680 Couldn't rename file at $etcdir. Must have write capability.
1681
1682 Press Enter to continue.
1683 EOF
1684 #'
1685 }
1686
1687
1688 =item loadconfigfile
1689
1690    loadconfigfile
1691
1692 Open the existing koha.conf file and get its values,
1693 saving the values to some global variables.
1694
1695 If the existing koha.conf file cannot be opened for any reason,
1696 the file is silently ignored.
1697
1698 =cut
1699
1700 sub loadconfigfile {
1701     my %configfile;
1702
1703     open (KC, "<$etcdir/koha.conf");
1704     while (<KC>) {
1705      chomp;
1706      (next) if (/^\s*#/);
1707      if (/(.*)\s*=\s*(.*)/) {
1708        my $variable=$1;
1709        my $value=$2;
1710        # Clean up white space at beginning and end
1711        $variable=~s/^\s*//g;
1712        $variable=~s/\s*$//g;
1713        $value=~s/^\s*//g;
1714        $value=~s/\s*$//g;
1715        $configfile{$variable}=$value;
1716      }
1717     }
1718
1719     $intranetdir=$configfile{'intranetdir'};
1720     $opacdir=$configfile{'opacdir'};
1721     $kohaversion=$configfile{'kohaversion'};
1722     $kohalogdir=$configfile{'kohalogdir'};
1723     $database=$configfile{'database'};
1724     $hostname=$configfile{'hostname'};
1725     $user=$configfile{'user'};
1726     $pass=$configfile{'pass'};
1727 }
1728
1729 END { }       # module clean-up code here (global destructor)
1730
1731 sub setmysqlclipass {
1732         my $pass = shift;
1733         open(MYCNF,">$mycnf");
1734         chmod(0600,$mycnf);
1735         print MYCNF "[client]\npassword=$pass\n";
1736         close(MYCNF);
1737 }
1738
1739 sub backupmycnf {
1740         if (-e $mycnf) {
1741                 rename $mycnf,$mytmpcnf;
1742         }
1743 }
1744
1745 sub restoremycnf {
1746         if (-e $mycnf) {
1747                 unlink($mycnf);
1748         }
1749         if (-e $mytmpcnf) {
1750                 rename $mytmpcnf,$mycnf;
1751         }
1752 }
1753
1754 =back
1755
1756 =head1 SEE ALSO
1757
1758 buildrelease.pl,
1759 installer.pl
1760
1761 =cut
1762
1763 1;