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