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