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