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