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