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