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