testing PDF::API2 and removing mandatory test of Net::LDAP
[koha_fer] / misc / Install.pm
1 package Install; #assumes Install.pm
2
3
4 # Copyright 2000-2002 Katipo Communications
5 # Contains parts Copyright 2003 MJ Ray
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21 #
22 # Recent Authors
23 # MJR: my.cnf, etcdir, prefix, new display, apache conf, copying fixups
24
25 use strict;
26 use POSIX;
27 #MJR: everyone will have these modules, right?
28 # They look like part of perl core to me
29 use Term::Cap;
30 use Term::ANSIColor qw(:constants);
31 use Text::Wrap;
32 require Exporter;
33
34 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
35
36 =head1 NAME
37
38 Install.pm - Perl module containing the bulk of the installation logic
39
40 =head1 DESCRIPTION
41
42 The Install.pm module contains the bulk
43 of the code to do installation;
44 this code is used by installer.pl
45 to perform an actual installation.
46
47 =head2 Internal functions (not meant to be used outside of Install.pm)
48
49 =over 4
50
51 =cut
52
53 # set the version for version checking
54 $VERSION = 0.01;
55
56 @ISA = qw(Exporter);
57 @EXPORT = qw(
58                 &read_autoinstall_file
59                 &checkperlmodules
60                 &checkabortedinstall
61                 &getmessage
62                 &showmessage
63                 &releasecandidatewarning
64                 &getinstallationdirectories
65                 &getdatabaseinfo
66                 &getapacheinfo
67                 &getapachevhostinfo
68                 &updateapacheconf
69                 &basicauthentication
70                 &installfiles
71                 &databasesetup
72                 &updatedatabase
73                 &populatedatabase
74                 &restartapache
75                 &backupkoha
76                 &finalizeconfigfile
77                 &loadconfigfile
78                 &backupmycnf
79                 &restoremycnf
80                 );
81
82 use vars qw( $kohaversion $newversion );                        # set in loadconfigfile and installer.pl
83 use vars qw( $language );                       # set in installer.pl
84 use vars qw( $domainname );                     # set in installer.pl
85
86 use vars qw( $etcdir );                         # set in installer.pl, usu. /etc
87 use vars qw( $intranetdir $opacdir $kohalogdir );
88 use vars qw( $realhttpdconf $httpduser );
89 use vars qw( $servername $svr_admin $opacport $intranetport );
90 use vars qw( $mysqldir );
91 use vars qw( $database $mysqluser );
92 use vars qw( $mysqlpass );                      # normally should not be used
93 use vars qw( $hostname $user $pass );   # virtual hosting
94
95 =item heading
96
97     $messages->{'WelcomeToKohaInstaller'
98         = heading('Welcome to the Koha Installer') . qq|...|;
99
100 The heading function takes one string, the text to be displayed as
101 the heading, and returns a formatted heading (currently formatted
102 with ANSI colours).
103
104 This reduces the likelihood of pod2man(1) etc. misinterpreting
105 a line of equal signs as illegal POD directives.
106
107 =cut
108
109 my $termios = POSIX::Termios->new();
110 $termios->getattr();
111 my $terminal = Term::Cap->Tgetent({OSPEED=>$termios->getospeed()});
112 my $clear_string = "\n";
113
114 sub heading ($) {
115   my $title = shift;
116   my $bal = 5;
117   return($clear_string.ON_BLUE.WHITE.BOLD." "x$bal.uc($title)." "x$bal.RESET."\n\n");
118 }
119
120 my $mycnf = $ENV{HOME}."/.my.cnf";
121 my $mytmpcnf = `mktemp my.cnf.koha.XXXXXX`;
122 chomp($mytmpcnf);
123
124 my $messages;
125 $messages->{'continuing'}->{en}="Great!  Continuing...\n\n";
126 $messages->{'WelcomeToKohaInstaller'}->{en} =
127    heading('Welcome to the Koha Installer') . qq|
128 This program will ask some questions and try to install koha for you.
129 You need to know: where most koha files should be stored (you can set
130 the prefix environment variable for this); the username and password of
131 a mysql superuser; and details of your library setup.  You may also need
132 to know details of your Apache setup.
133
134 If you want to install the Koha configuration files somewhere other than
135 /etc (for multiple Koha versions on one system, for example), you should
136 set the etcdir environment variable.  Please look at your manuals for
137 details of how to set that.
138
139 Recommended answers are given in brackets after each question.  To accept
140 the default value for any question (indicated by []), simply hit Enter
141 at the prompt.
142
143 You also can define an auto_install_file, that will answer every question automatically.
144 To use this feature, run ./installer.pl -i /path/to/auto_install_file 
145
146 Are you ready to begin the installation? ([Y]/N): |;
147
148 $messages->{'WelcomeToUpgrader'}->{en} =
149    heading('Welcome to the Koha Upgrader') . qq|
150 You are attempting to upgrade from Koha %s to %s.
151
152 We recommend that you do a complete backup of all your files before upgrading.
153 This upgrade script will make a backup copy of your files for you.
154
155 Would you like to proceed?  (Y/[N]):|;
156
157 $messages->{'AbortingInstall'}->{en} =
158    heading('ABORTING') . qq|
159 Aborting as requested.  Please rerun when you are ready.
160 |;
161
162 $messages->{'ReleaseCandidateWarning'}->{en} =
163    heading('RELEASE CANDIDATE') . qq|
164 WARNING: You are about to install Koha version %s.  This is a
165 release candidate, It is NOT bugfree.
166 However, it works, and has been declared stable enough to
167 be released.
168
169 Most people should answer Yes here.
170
171 Are you sure you want to install Koha %s? (Y/[N]): |;
172 $messages->{'WatchForReleaseAnnouncements'}->{en}=qq|
173
174 Watch for announcements of Koha releases on the Koha mailing list or the Koha
175 web site (http://www.koha.org/).
176
177 |;
178
179 $messages->{'NETZ3950Missing'}->{en}=qq|
180
181 The Net::Z3950 module is missing.  This module is necessary if you want to use
182 Koha's Z39.50 client to download bibliographic records from other libraries.
183
184 To install this module, you will need the yaz client installed from
185 http://www.indexdata.dk/yaz/ and then you can install the perl module with the
186 command:
187
188 perl -MCPAN -e 'install Net::Z3950'
189
190 ...or by installing packages for your distribution, if available.
191
192 IMPORTANT NOTE : If you use Perl 5.8.0, you might need to 
193 edit NET::Z3950's Makefile.PL and yazwrap/Makefile.PL to include:
194
195     'DEFINE' => '-D_GNU_SOURCE',
196
197 Also note that some installations of Perl on Red Hat will generate a lot of
198 "'my_perl' undeclared" errors when running make in Net-Z3950.  This is fixed by
199 inserting in yazwrap/ywpriv.h a line saying #include "XSUB.h"
200
201 Press the <ENTER> key to continue: |;   #'
202
203 $messages->{'CheckingPerlModules'}->{en} = heading('PERL MODULES') . qq|
204 Checking perl modules ...
205 |;
206
207 $messages->{'PerlVersionFailure'}->{en}="Sorry, you need at least Perl %s\n";
208
209 $messages->{'MissingPerlModules'}->{en} = heading('MISSING PERL MODULES') . qq|
210 You are missing some Perl modules required by Koha.
211 Please run this again after installing them.
212 They may be installed by finding packages from your operating system supplier, or running (as root) the following commands:
213
214 %s
215 |;
216
217 $messages->{'AllPerlModulesInstalled'}->{en} =
218    heading('PERL MODULES AVAILABLE') . qq|
219 All required perl modules are installed.
220
221 Press <ENTER> to continue: |;
222 $messages->{'KohaVersionInstalled'}->{en}="You currently have Koha %s on your system.";
223 $messages->{'KohaUnknownVersionInstalled'}->{en}="I am not able to determine what version of Koha is installed now.";
224 $messages->{'KohaAlreadyInstalled'}->{en} =
225    heading('Koha already installed') . qq|
226 It looks like Koha is already installed on your system (%s/koha.conf exists).
227 If you would like to upgrade your system to %s, please use
228 the koha.upgrade script in this directory.
229
230 %s
231
232 |;
233 $messages->{'GetOpacDir'}->{en} = heading('OPAC DIRECTORY') . qq|
234 Please supply the directory you want Koha to store its OPAC files in.  This
235 directory will be auto-created for you if it doesn't exist.
236
237 OPAC Directory [%s]: |; #'
238
239 $messages->{'GetIntranetDir'}->{en} =
240    heading('LIBRARIAN DIRECTORY') . qq|
241 Please supply the directory you want Koha to store its Librarian interface
242 files in.  This directory will be auto-created for you if it doesn't exist.
243
244 Intranet Directory [%s]: |;     #'
245
246 $messages->{'GetKohaLogDir'}->{en} = heading('LOG DIRECTORY') . qq|
247 Specify a directory where log files will be written.
248
249 Koha Log Directory [%s]: |;
250
251 $messages->{'AuthenticationWarning'}->{en} = heading('Authentication') . qq|
252 This release of Koha has a new authentication module.
253 You will be required to log in to
254 access some features.
255
256 IMPORTANT: You can log in using the userid and password from the %s/koha.conf configuration file at any time.
257 Use the "Members" screen to add passwords for other accounts and set their flags.
258
259 Press the <ENTER> key to continue: |;
260
261 $messages->{'Completed'}->{en} = heading('INSTALLATION COMPLETE') . qq|
262 Congratulations ... your Koha installation is complete!
263 You will be able to connect to your Librarian interface at:
264    http://%s\:%s/
265    use the koha admin mysql login and password to connect to this interface.
266 and the OPAC interface at:
267    http://%s\:%s/
268 Please read the Hints file and visit http://www.koha.org
269 Press <ENTER> to exit the installer: |;
270
271 $messages->{'UpgradeCompleted'}->{en} = heading('UPGRADE COMPLETE') . qq|
272 Congratulations ... your Koha upgrade is finished!
273
274 Please report any problems you encounter through http://bugs.koha.org/
275
276 Press <ENTER> to exit the installer: |;
277
278 #'
279 sub releasecandidatewarning {
280     my $message=getmessage('ReleaseCandidateWarning', [$newversion, $newversion]);
281     my $answer=showmessage($message, 'yn', 'n');
282
283     if ($answer =~ /y/i) {
284         print getmessage('continuing');
285     } else {
286         my $message=getmessage('WatchForReleaseAnnouncements');
287         print $message."\n";
288         exit;
289     };
290 }
291
292 sub read_autoinstall_file
293 {
294         my $fname = shift;      # Config file to read
295         my $retval = {};        # Return value: ref-to-hash holding the
296                                 # configuration
297
298         open (CONF, $fname) or return undef;
299
300         while (<CONF>)
301         {
302                 my $var;                # Variable name
303                 my $value;              # Variable value
304
305                 chomp;
306                 s/#.*//;                # Strip comments
307                 next if /^\s*$/;        # Ignore blank lines
308
309                 # Look for a line of the form
310                 #       var = value
311                 if (!/^\s*(\w+)\s*=\s*(.*?)\s*$/)
312                 {
313                         next;
314                 }
315
316                 # Found a variable assignment
317                 # variable that was already set.
318                 $var = $1;
319                 $value = $2;
320                 $retval->{$var} = $value;
321         }
322         close CONF;
323         if ($retval->{MysqlRootPassword} eq "XXX") {
324                 print "ERROR : the root password is XXX. It is NOT valid. Edit your auto_install_file\n";
325         }
326         return $retval;
327 }
328
329 =back
330
331 =head2 Accessor functions (for installer.pl)
332
333 =over 4
334
335 =cut
336
337 =item setlanguage
338
339     setlanguage('en');
340
341 Sets the installation language, normally "en" (English).
342 In fact, only "en" is supported.
343
344 =cut
345
346 sub setlanguage ($) {
347     ($language) = @_;
348 }
349
350 =item setdomainname
351
352     setdomainname('example.org');
353
354 Sets the domain name of the host.
355
356 The domain name should not contain a leading dot;
357 otherwise, the results are undefined.
358
359 =cut
360
361 sub setdomainname ($) {
362     ($domainname) = @_;
363 }
364
365 =item setetcdir
366
367     setetcdir('/etc');
368
369 Sets the sysconfdir, normally /etc.
370 This should be an absolute path; a trailing / is not required.
371
372 =cut
373
374 sub setetcdir ($) {
375     ($etcdir) = @_;
376 }
377
378 =item getkohaversion
379
380     getkohaversion();
381
382 Gets the Koha version as known by the previous config file.
383
384 =cut
385
386 sub getkohaversion () {
387     return($kohaversion);
388 }
389
390 =item setkohaversion
391
392     setkohaversion('1.3.3RC26');
393
394 Sets the Koha version as known by the installer.
395
396 =cut
397
398 sub setkohaversion ($) {
399     ($newversion) = @_;
400 }
401
402 =item getservername
403
404     my $servername = getservername;
405
406 Gets the name of the Koha virtual server as specified by the user.
407
408 =cut
409
410 sub getservername () {
411     $servername;
412 }
413
414 =item getopacport
415
416     $port = getopacport;
417
418 Gets the port that will run the Koha OPAC virtual server,
419 as specified by the user.
420
421 =cut
422
423 sub getopacport () {
424     $opacport;
425 }
426
427 =item getintranetport
428
429     $port = getintranetport;
430
431 Gets the port that will run the Koha INTRANET virtual server,
432 as specified by the user.
433
434 =cut
435
436 sub getintranetport () {
437     $intranetport;
438 }
439
440 =back
441
442 =head2 Miscellaneous utility functions
443
444 =over 4
445
446 =cut
447
448 =item dirname
449
450     dirname $path;
451
452 Does the equivalent of dirname(1). Given a path $path, return the
453 parent directory of $path (best guess), except when $path seems to
454 be the same as /, in which case $path itself is returned unchanged.
455
456 =cut
457
458 sub dirname ($;$) {
459     my($path) = @_;
460     if ($path =~ /[^\/]/s) {
461         if ($path =~ /\//) {
462             $path =~ s/\/+[^\/]+\/*$//s;
463         } else {
464             $path = '.';
465         }
466     }
467     return $path;
468 }
469
470 =item mkdir_parents
471
472     mkdir_parents $path;
473     mkdir_parents $path, $mode;
474
475 Does the equivalent of mkdir -p, or mkdir --parents. Given a path $path,
476 create the directory $path, recursively creating any intermediate
477 directories. If $mode is given, the directory will be created with
478 mode $mode.
479
480 WARNING: If $path already exists, mkdir_parents will just return
481 successfully (just like mkdir -p), whether the mode of $path conforms
482 to $mode or not. (This is the behaviour of the mkdir -p command.)
483
484 =cut
485
486 sub mkdir_parents {
487     my($path, $mode) = @_;
488     my $ok = -d($path)? 1: defined $mode? mkdir($path, $mode): mkdir($path);
489
490     if (!$ok && $! == ENOENT) {
491         my $parent = dirname($path);
492         $ok = mkdir_parents($parent, $mode);
493
494         # retry and at the same time make sure that $! is set correctly
495         $ok = defined $mode? mkdir($path, $mode): mkdir($path);
496     }
497     return $ok;
498 }
499
500
501 =item getmessage
502
503     getmessage($msgid);
504     getmessage($msgid, $variables);
505
506 Gets a localized message (format string) with message id $msgid,
507 and, if an array reference of variables $variables is given,
508 substitutes variables in the format string with @$variables.
509 Returns the found message string, with variable substitutions
510 if specified.
511
512 $msgid must be the message identifier corresponding to a defined
513 message string (a valid key to the $messages hash in the Installer
514 package). getmessage throws an exception if the message cannot be
515 found.
516
517 =cut
518
519 sub getmessage {
520     my $messagename=shift;
521     my $variables=shift;
522     my $message=$messages->{$messagename}->{$language} || $messages->{$messagename}->{en} || RED.BOLD."Error: No message named $messagename in Install.pm\n";
523     if (defined($variables)) {
524         $message=sprintf $message, @$variables;
525     }
526     return $message;
527 }
528
529
530 =item showmessage
531
532     showmessage($message, 'none');
533     showmessage($message, 'none', undef, $noclear);
534
535     $result = showmessage($message, 'yn');
536     $result = showmessage($message, 'yn', $defaultresponse);
537     $result = showmessage($message, 'yn', $defaultresponse, $noclear);
538
539     $result = showmessage($message, 'restrictchar CHARS');
540     $result = showmessage($message, 'free');
541     $result = showmessage($message, 'silentfree');
542     $result = showmessage($message, 'numerical');
543     $result = showmessage($message, 'email');
544     $result = showmessage($message, 'PressEnter');
545
546 Shows a message and optionally gets a response from the user.
547
548 The first two arguments, the message and the response type,
549 are mandatory.  The message must be the actual string to
550 display; the caller is responsible for calling getmessage if
551 required.
552
553 The response type must be one of "none", "yn", "free", "silentfree"
554 "numerical", "email", "PressEnter", or a string consisting
555 of "restrictchar " followed by a list of allowed characters
556 (space can be specified). (Case is not significant, but case is
557 significant in the list of allowed characters.) If a response
558 type other than the above-listed is specified, the result is
559 undefined.
560
561 Note that the response type "yn" is equivalent to "restrictchar yn".
562 Because "restrictchar" is case-sensitive, the user is expected
563 to enter "y" or "n" in lowercase only.
564
565 Note that the response type of "email" does not actually
566 guarantee that the returned value is a well-formed RFC-822
567 email address, nor does it accept all well-formed RFC-822 email
568 addresses. What it does is to restrict the returned value to a
569 string that is looks reasonably likely to be an email address
570 in the "real world", given the premise that the user is trying
571 to enter a real email address.
572
573 If a response type other than "none" or "PressEnter" is
574 specified, a third argument, specifying the default value, can
575 be specified:  If this default response is not specified, the
576 default response is the first allowed character if the response
577 type is "restrictchar", otherwise the default response is the
578 empty string. This default response is used when the user does
579 not specify a value (i.e., presses Enter without typing in
580 anything), showmessage will assume that the default response is
581 the user's response.
582
583 Note that because the response type "yn" is equivalent to
584 "restrictchar yn", the default value for response type "yn",
585 if unspecified, is "y".
586
587 The screen is normally cleared before the message is displayed;
588 if a fourth argument is specified and is nonzero, this
589 screen-clearing is not done.
590
591 =cut
592 #'
593
594 sub showmessage {
595     #MJR: Maybe refactor to use anonymous functions that
596     # check the responses instead of RnP branching.
597     my $message=join('',fill('','',(shift)));
598     my $responsetype=shift;
599     my $defaultresponse=shift;
600     my $noclear=shift;
601     $noclear = 0 unless defined $noclear; # defaults to "clear"
602     ($noclear) || (print $clear_string);
603     if ($responsetype =~ /^yn$/) {
604         $responsetype='restrictchar ynYN';
605     }
606     print RESET.$message;
607     if ($responsetype =~/^restrictchar (.*)/i) {
608         my $response='\0';
609         my $options=$1;
610         until ($options=~/$response/) {
611             (defined($defaultresponse)) || ($defaultresponse=substr($options,0,1));
612             $response=<STDIN>;
613             chomp $response;
614             (length($response)) || ($response=$defaultresponse);
615             if ( $response=~/.*[\:\(\)\^\$\*\!\\].*/ ) {
616                 ($noclear) || (print $clear_string);
617                 print RED."Response contains invalid characters.  Choose from [$options].\n\n";
618                 print RESET.$message;
619                 $response='\0';
620             } else {
621                 unless ($options=~/$response/) {
622                     ($noclear) || (print $clear_string);
623                     print RED."Invalid Response.  Choose from [$options].\n\n";
624                     print RESET.$message;
625                 }
626             }
627         }
628         return $response;
629     } elsif ($responsetype =~/^(silent)?free$/i) {
630         (defined($defaultresponse)) || ($defaultresponse='');
631         if ($responsetype =~/^(silent)/i) { setecho(0) }; 
632         my $response=<STDIN>;
633         if ($responsetype =~/^(silent)/i) { setecho(1) }; 
634         chomp $response;
635         ($response) || ($response=$defaultresponse);
636         return $response;
637     } elsif ($responsetype =~/^numerical$/i) {
638         (defined($defaultresponse)) || ($defaultresponse='');
639         my $response='';
640         until ($response=~/^\d+$/) {
641             $response=<STDIN>;
642             chomp $response;
643             ($response) || ($response=$defaultresponse);
644             unless ($response=~/^\d+$/) {
645                 ($noclear) || (print $clear_string);
646                 print RED."Invalid Response ($response).  Response must be a number.\n\n";
647                 print RESET.$message;
648             }
649         }
650         return $response;
651     } elsif ($responsetype =~/^email$/i) {
652         (defined($defaultresponse)) || ($defaultresponse='');
653         my $response='';
654         until ($response=~/.*\@.*\..*/) {
655             $response=<STDIN>;
656             chomp $response;
657             ($response) || ($response=$defaultresponse);
658             if ($response!~/.*\@.*\..*/) {
659                         ($noclear) || (print $clear_string);
660                         print RED."Invalid Response ($response).  Response must be a valid email address.\n\n";
661                         print RESET.$message;
662             }
663         }
664         return $response;
665     } elsif ($responsetype =~/^PressEnter$/i) {
666         <STDIN>;
667         return;
668     } elsif ($responsetype =~/^none$/i) {
669         return;
670     } else {
671         # FIXME: There are a few places where we will get an undef as the
672         # response type. Should we thrown an exception here, or should we
673         # legitimize this usage and say "none" is the default if not specified?
674         #die "Illegal response type \"$responsetype\"";
675     }
676 }
677
678
679 =back
680
681 =item startsysout
682
683         startsysout;
684
685 Changes the display to show system output until the next showmessage call.
686 At the time of writing, this means using red text.
687
688 =cut
689
690 sub startsysout {
691         print RED."\n";
692 }
693
694
695 =back
696
697 =head2 Subtasks of doing an installation
698
699 =over 4
700
701 =cut
702
703 =item checkabortedinstall
704
705     checkabortedinstall;
706
707 Checks whether a previous installation process has been abnormally
708 aborted, by checking whether $etcidr/koha.conf is a symlink matching
709 a particular pattern.  If an aborted installation is detected, give
710 the user a chance to abort, before trying to recover the aborted
711 installation.
712
713 FIXME: The recovery is not complete; it only partially rolls back
714 some changes.
715
716 =cut
717
718 sub checkabortedinstall () {
719     if (-l("$etcdir/koha.conf")
720         && readlink("$etcdir/koha.conf") =~ /\.tmp$/
721     ) {
722         print qq|
723 I have detected that you tried to install Koha before, but the installation
724 was aborted.  I will try to continue, but there might be problems if the
725 database is already created.
726
727 |;
728         print "Please press <ENTER> to continue: ";
729         <STDIN>;
730
731         # Remove the symlink after the <STDIN>, so the user can back out
732         unlink "$etcdir/koha.conf"
733             || die "Failed to remove incomplete $etcdir/koha.conf: $!\n";
734     }
735 }
736
737 =item checkpaths
738
739         checkpaths;
740
741 Make sure that we loaded the right dirs from an old koha.conf
742
743 =cut
744
745 #FIXME: update to use Install.pm
746 sub checkpaths {
747 if ($opacdir && $intranetdir) {
748     print qq|
749
750 I believe that your old files are located in:
751
752   OPAC:      $opacdir
753   LIBRARIAN: $intranetdir
754
755
756 Does this look right?  ([Y]/N):
757 |;
758     my $answer = <STDIN>;
759     chomp $answer;
760
761     if ($answer =~/n/i) {
762         $intranetdir='';
763         $opacdir='';
764     } else {
765         print "Great! continuing upgrade... \n";
766     }
767 }
768
769 if (!$opacdir || !$intranetdir) {
770     $intranetdir='';
771     $opacdir='';
772     while (!$intranetdir) {
773         print "Please specify the location of your LIBRARIAN files: ";
774
775         my $answer = <STDIN>;
776         chomp $answer;
777
778         if ($answer) {
779             $intranetdir=$answer;
780         }
781         if (! -e "$intranetdir/htdocs") {
782             print "\nCouldn't find the htdocs directory here.  That doesn't look right.\nPlease enter another location.\n\n";
783             $intranetdir='';
784         }
785     }
786     while (!$opacdir) {
787         print "Please specify the location of your OPAC files: ";  
788
789         my $answer = <STDIN>;
790         chomp $answer;
791
792         if ($answer) {
793             $opacdir=$answer;
794         }
795         if (! -e "$opacdir/htdocs") {
796             print "\nCouldn't find the htdocs directory here.  That doesn't look right.\nPlease enter another location.\n\n";
797             $opacdir='';
798         }
799     }
800 }
801
802 }
803
804 =item checkperlmodules
805
806     checkperlmodules;
807
808 Test whether the version of Perl is new enough, whether Perl is
809 found at the expected location, and whether all required modules
810 have been installed.
811
812 =cut
813
814 sub checkperlmodules {
815 #
816 # Test for Perl and Modules
817 #
818         my ($auto_install) = @_;
819         my $message = getmessage('CheckingPerlModules');
820         showmessage($message, 'none');
821
822         unless ($] >= 5.006001) {                       # Bug 179
823                 die getmessage('PerlVersionFailure', ['5.6.1']);
824         }
825         startsysout();
826
827         my @missing = ();
828         unless (eval {require DBI})              { push @missing,"DBI" };
829         unless (eval {require Date::Manip})      { push @missing,"Date::Manip" };
830         unless (eval {require DBD::mysql})       { push @missing,"DBD::mysql" };
831         unless (eval {require HTML::Template})   { push @missing,"HTML::Template" };
832         unless (eval {require Digest::MD5})      { push @missing,"Digest::MD5" };
833         unless (eval {require MARC::Record})     { push @missing,"MARC::Record" };
834         unless (eval {require Mail::Sendmail})   { push @missing,"Mail::Sendmail" };
835         unless (eval {require PDF::API2})   { push @missing,"PDF::API2" };
836 # The following modules are not mandatory, depends on how the library want to use Koha
837         unless (eval {require Net::LDAP})       {
838                 if ($#missing>=0) { # only when $#missing >= 0 so this isn't fatal
839                                 push @missing, "Net::LDAP";
840                         }
841     }
842         unless (eval {require Event})       {
843                 if ($#missing>=0) { # only when $#missing >= 0 so this isn't fatal
844                                 push @missing, "Event";
845                         }
846     }
847     unless (eval {require Net::Z3950})       {
848                 showmessage(getmessage('NETZ3950Missing'), 'PressEnter', '', 1);
849                 if ($#missing>=0) { # see above note
850                         push @missing, "Net::Z3950";
851                 }
852     }
853
854 #
855 # Print out a list of any missing modules
856 #
857
858     if (@missing > 0) {
859         my $missing='';
860         if (POSIX::setlocale(LC_ALL) ne "C") {
861                 $missing.="   export LC_ALL=C\n";  
862         }
863         foreach my $module (@missing) {
864             $missing.="   perl -MCPAN -e 'install \"$module\"'\n";
865         }
866         my $message=getmessage('MissingPerlModules', [$missing]);
867         showmessage($message, 'none');
868         print "\n";
869         exit;
870     } else {
871         showmessage(getmessage('AllPerlModulesInstalled'), 'PressEnter', '', 1) unless $auto_install->{NoPressEnter};
872     }
873
874
875         startsysout();
876     unless (-x "/usr/bin/perl") {
877         my $realperl=`which perl`;
878         chomp $realperl;
879         $realperl = showmessage(getmessage('NoUsrBinPerl'), 'none');
880         until (-x $realperl) {
881             $realperl=showmessage(getmessage('AskLocationOfPerlExecutable', $realperl), 'free', $realperl, 1);
882         }
883         my $response=showmessage(getmessage('ConfirmPerlExecutableSymlink', $realperl), 'yn', 'y', 1);
884         unless ($response eq 'n') {
885                 startsysout();
886             system("ln -s $realperl /usr/bin/perl");
887         }
888     }
889
890
891 }
892
893 $messages->{'NoUsrBinPerl'}->{en} =
894    heading('No /usr/bin/perl') . qq|
895 Koha expects to find the perl executable in the /usr/bin
896 directory.  It is not there on your system.
897
898 |;
899
900 $messages->{'AskLocationOfPerlExecutable'}->{en}=qq|Location of Perl Executable [%s]: |;
901 $messages->{'ConfirmPerlExecutableSymlink'}->{en}=qq|
902 Some Koha scripts will _not_ work without a symlink from %s to /usr/bin/perl
903
904 Most users should answer Y here.
905
906 May I try to create this symlink? ([Y]/N):|;
907
908 $messages->{'DirFailed'}->{en} = RED.qq|
909 We could not create %s, but continuing anyway...
910
911 |;
912
913
914
915 =item getinstallationdirectories
916
917     getinstallationdirectories;
918
919 Get the various installation directories from the user, and then
920 create those directories (if they do not already exist).
921
922 These pieces of information are saved to global variables; the
923 function does not return any values.
924
925 =cut
926
927 sub getinstallationdirectories {
928         my ($auto_install) = @_;
929         if (!$ENV{prefix}) { $ENV{prefix} = "/usr/local"; } #"
930     $opacdir = $ENV{prefix}.'/koha/opac';
931     $intranetdir = $ENV{prefix}.'/koha/intranet';
932     my $getdirinfo=1;
933     while ($getdirinfo) {
934         # Loop until opac directory and koha directory are different
935         my $message;
936         if ($auto_install->{GetOpacDir}) {
937                 $opacdir=$auto_install->{GetOpacDir};
938                 print ON_YELLOW.BLACK."auto-setting OpacDir to : $opacdir".RESET."\n";
939         } else {
940                 $message=getmessage('GetOpacDir', [$opacdir]);
941                 $opacdir=showmessage($message, 'free', $opacdir);
942         }
943         if ($auto_install->{GetIntranetDir}) {
944                 $intranetdir=$auto_install->{GetIntranetDir};
945                 print ON_YELLOW.BLACK."auto-setting IntranetDir to : $intranetdir".RESET."\n";
946         } else {
947                 $message=getmessage('GetIntranetDir', [$intranetdir]);
948                 $intranetdir=showmessage($message, 'free', $intranetdir);
949         }
950         if ($intranetdir eq $opacdir) {
951             print qq|
952
953 You must specify different directories for the OPAC and INTRANET files!
954  :: $intranetdir :: $opacdir ::
955 |;
956 <STDIN>
957         } else {
958             $getdirinfo=0;
959         }
960     }
961     $kohalogdir=$ENV{prefix}.'/koha/log';
962         if ($auto_install->{GetOpacDir}) {
963                 $kohalogdir=$auto_install->{KohaLogDir};
964                 print ON_YELLOW.BLACK."auto-setting log dir to : $kohalogdir".RESET."\n";
965         } else {
966             my $message=getmessage('GetKohaLogDir', [$kohalogdir]);
967         $kohalogdir=showmessage($message, 'free', $kohalogdir);
968         }
969
970
971     # FIXME: Need better error handling for all mkdir calls here
972     unless ( -d $intranetdir ) {
973        mkdir_parents (dirname($intranetdir), 0775) || print getmessage('DirFailed',['parents of '.$intranetdir]);
974        mkdir ($intranetdir,                  0770) || print getmessage('DirFailed',[$intranetdir]);
975        if ($>==0) { chown (oct(0), (getgrnam($httpduser))[2], "$intranetdir"); }
976        chmod 0770, "$intranetdir";
977     }
978     mkdir_parents ("$intranetdir/htdocs",    0750);
979     mkdir_parents ("$intranetdir/cgi-bin",   0750);
980     mkdir_parents ("$intranetdir/modules",   0750);
981     mkdir_parents ("$intranetdir/scripts",   0750);
982     unless ( -d $opacdir ) {
983        mkdir_parents (dirname($opacdir),     0775) || print getmessage('DirFailed',['parents of '.$opacdir]);
984        mkdir ($opacdir,                      0770) || print getmessage('DirFailed',[$opacdir]);
985        if ($>==0) { chown (oct(0), (getgrnam($httpduser))[2], "$opacdir"); }
986        chmod (oct(770), "$opacdir");
987     }
988     mkdir_parents ("$opacdir/htdocs",        0750);
989     mkdir_parents ("$opacdir/cgi-bin",       0750);
990
991
992     unless ( -d $kohalogdir ) {
993        mkdir_parents (dirname($kohalogdir),  0775) || print getmessage('DirFailed',['parents of '.$kohalogdir]);
994        mkdir ($kohalogdir,                   0770) || print getmessage('DirFailed',[$kohalogdir]);
995        if ($>==0) { chown (oct(0), (getgrnam($httpduser))[2,3], "$kohalogdir"); }
996        chmod (oct(770), "$kohalogdir");
997     }
998 }
999
1000 =item getmysqldir
1001
1002         getmysqldir;
1003
1004 Get the MySQL database server installation directory, automatically if possible.
1005
1006 =cut
1007
1008 $messages->{'WhereIsMySQL'}->{en} = heading('MYSQL LOCATION').qq|
1009 Koha can't find the MySQL command-line tools. If you installed a MySQL package, you may need to install an additional package containing mysqladmin.
1010 If you compiled mysql yourself,
1011 please give the value of --prefix when you ran configure.
1012 The file mysqladmin should be in bin/mysqladmin under the directory that you give here.
1013
1014 MySQL installation directory: |;
1015 #'
1016 sub getmysqldir {
1017     foreach my $mysql (qw(/usr/local/mysql
1018                           /opt/mysql
1019                           /usr/local
1020                           /usr
1021                           )) {
1022        if ( -d $mysql  && -f "$mysql/bin/mysqladmin") { #"
1023             $mysqldir=$mysql;
1024        }
1025     }
1026     if (!$mysqldir){
1027         for (;;) {
1028             $mysqldir = showmessage(getmessage('WhereIsMySQL'),'free');
1029             last if -f "$mysqldir/bin/mysqladmin";
1030         }
1031     }
1032     return($mysqldir);
1033 }
1034
1035 =item getdatabaseinfo
1036
1037     getdatabaseinfo;
1038
1039 Get various pieces of information related to the Koha database:
1040 the name of the database, the host on which the SQL server is
1041 running, and the database user name.
1042
1043 These pieces of information are saved to global variables; the
1044 function does not return any values.
1045
1046 =cut
1047
1048 $messages->{'DatabaseName'}->{en} = heading('Database Name') . qq|
1049 Please provide the name that you wish to give your koha database.
1050 It must not exist already on the database server.
1051
1052 Most users give a short single-word name for their library here.
1053
1054 Database name [%s]: |;
1055
1056 $messages->{'DatabaseHost'}->{en} = heading('Database Host') . qq|
1057 Please provide the mysql server name.  Unless the database is stored on
1058 another machine, this should be "localhost".
1059
1060 Database host [%s]: |;
1061
1062 $messages->{'DatabaseUser'}->{en} = heading('Database User') . qq|
1063 We are going to create a new mysql user for Koha. This user will have full administrative rights
1064 to the database called %s when they connect from %s.
1065 This is also the name of the Koha librarian superuser.
1066
1067 Most users give a single-word name here.
1068
1069 Database user [%s]: |;
1070
1071 $messages->{'DatabasePassword'}->{en} = heading('Database Password') . qq|
1072 Please provide a good password for the user %s.
1073
1074 IMPORTANT: You can log in using this user and password at any time.
1075
1076 Password for database user %s: |;
1077
1078 $messages->{'BlankPassword'}->{en} = heading('BLANK PASSWORD') . qq|
1079 You must not use a blank password for your MySQL user.
1080
1081 Press <ENTER> to try again: 
1082 |;
1083
1084 sub getdatabaseinfo {
1085         my ($auto_install) = @_;
1086     $database = 'Koha';
1087     $hostname = 'localhost';
1088     $user = 'kohaadmin';
1089     $pass = '';
1090
1091 #Get the database name
1092         my $message;
1093         
1094         if ($auto_install->{database}) {
1095                 $database=$auto_install->{database};
1096                 print ON_YELLOW.BLACK."auto-setting database to : $database".RESET."\n";
1097         } else {
1098                 $message=getmessage('DatabaseName', [$database]);
1099                 $database=showmessage($message, 'free', $database);
1100         }
1101 #Get the hostname for the database
1102     
1103         if ($auto_install->{DatabaseHost}) {
1104                 $hostname=$auto_install->{DatabaseHost};
1105                 print ON_YELLOW.BLACK."auto-setting database host to : $hostname".RESET."\n";
1106         } else {
1107                 $message=getmessage('DatabaseHost', [$hostname]);
1108                 $hostname=showmessage($message, 'free', $hostname);
1109         }
1110 #Get the username for the database
1111
1112         if ($auto_install->{DatabaseUser}) {
1113                 $user=$auto_install->{DatabaseUser};
1114                 print ON_YELLOW.BLACK."auto-setting DB user to : $user".RESET."\n";
1115         } else {
1116                 $message=getmessage('DatabaseUser', [$database, $hostname, $user]);
1117                 $user=showmessage($message, 'free', $user);
1118         }
1119 #Get the password for the database user
1120
1121     while ($pass eq '') {
1122                 my $message=getmessage('DatabasePassword', [$user, $user]);
1123                 if ($auto_install->{DatabasePassword}) {
1124                         $pass=$auto_install->{DatabasePassword};
1125                         print ON_YELLOW.BLACK."auto-setting database password to : $pass".RESET."\n";
1126                 } else {
1127                                 $pass=showmessage($message, 'free', $pass);
1128                 }
1129                 if ($pass eq '') {
1130                         my $message=getmessage('BlankPassword');
1131                         showmessage($message,'PressEnter');
1132                 }
1133     }
1134 }
1135
1136
1137
1138 =item getapacheinfo
1139
1140     getapacheinfo;
1141
1142 Get various pieces of information related to the Apache server:
1143 the location of the configuration file and, if needed, the Unix
1144 user that the Koha CGI will be run under.
1145
1146 These pieces of information are saved to global variables; the
1147 function does not return any values.
1148
1149 =cut
1150
1151 $messages->{'FoundMultipleApacheConfFiles'}->{en} = 
1152    heading('MULTIPLE APACHE CONFIG FILES FOUND') . qq|
1153 I found more than one possible Apache configuration file:
1154
1155 %s
1156
1157 Enter number of the file to read [1]: |;
1158
1159 $messages->{'NoApacheConfFiles'}->{en} =
1160    heading('NO APACHE CONFIG FILE FOUND') . qq|
1161 I was not able to find your Apache configuration file.
1162
1163 The file is usually called httpd.conf, apache.conf or similar.
1164
1165 Please enter the full name, starting with /: |;
1166
1167 $messages->{'NotAFile'}->{en} = heading('FILE DOES NOT EXIST') . qq|
1168 The file %s does not exist.
1169
1170 Please press <ENTER> to continue: |;
1171
1172 $messages->{'EnterApacheUser'}->{en} = heading('NEED APACHE USER') . qq\
1173 The installer could not find the User setting in the Apache configuration file.
1174 This is used to set up access permissions for
1175 %s/koha.conf.  This user should be set in one of the Apache configuration.
1176 Please try to find it and enter the user name below.  You might find
1177 that "ps u|grep apache" will tell you.  It probably is NOT "root".
1178
1179 Enter the Apache userid: \;
1180
1181 $messages->{'InvalidUserid'}->{en} = heading('INVALID USER') . qq|
1182 The userid %s is not a valid userid on this system.
1183
1184 Press <ENTER> to continue: |;
1185
1186 sub getapacheinfo {
1187         my ($auto_install) = @_;
1188     my @confpossibilities;
1189
1190     foreach my $httpdconf (qw(/usr/local/apache/conf/httpd.conf
1191                           /usr/local/etc/apache/httpd.conf
1192                           /usr/local/etc/apache/apache.conf
1193                           /var/www/conf/httpd.conf
1194                           /etc/apache2/httpd.conf
1195                           /etc/apache2/apache2.conf
1196                           /etc/apache/conf/httpd.conf
1197                           /etc/apache/conf/apache.conf
1198                           /etc/apache/httpd.conf
1199                           /etc/apache-ssl/conf/apache.conf
1200                           /etc/apache-ssl/httpd.conf
1201                           /etc/httpd/conf/httpd.conf
1202                           /etc/httpd/httpd.conf
1203                           /etc/httpd/2.0/conf/httpd2.conf
1204                           )) {
1205                 if ( -f $httpdconf ) {
1206                         push @confpossibilities, $httpdconf;
1207                 }
1208     }
1209
1210     if ($#confpossibilities==-1) {
1211                 my $message=getmessage('NoApacheConfFiles');
1212                 my $choice='';
1213                 $realhttpdconf='';
1214                 until (-f $realhttpdconf) {
1215                         $choice=showmessage($message, "free", 1);
1216                         if (-f $choice) {
1217                         $realhttpdconf=$choice;
1218                         } else {
1219                         showmessage(getmessage('NotAFile', [$choice]),'PressEnter', '', 1);
1220                         }
1221                 }
1222     } elsif ($#confpossibilities>0) {
1223                 my $conffiles='';
1224                 my $counter=1;
1225                 my $options='';
1226                 foreach (@confpossibilities) {
1227                         $conffiles.="   $counter: $_\n";
1228                         $options.="$counter";
1229                         $counter++;
1230                 }
1231                 my $message=getmessage('FoundMultipleApacheConfFiles', [$conffiles]);
1232                 my $choice=showmessage($message, "restrictchar $options", 1);
1233                 $realhttpdconf=$confpossibilities[$choice-1];
1234     } else {
1235                 $realhttpdconf=$confpossibilities[0];
1236     }
1237     unless (open (HTTPDCONF, "<$realhttpdconf")) {
1238         warn RED."Insufficient privileges to open $realhttpdconf for reading.\n";
1239         sleep 4;
1240     }
1241
1242     while (<HTTPDCONF>) {
1243                 if (/^\s*User\s+"?([-\w]+)"?\s*$/) {
1244                         $httpduser = $1;
1245                 }
1246     }
1247     close(HTTPDCONF);
1248
1249     unless (defined($httpduser)) {
1250                 my $message;
1251                 if ($auto_install->{EnterApacheUser}) {
1252                         $message = $auto_install->{EnterApacheUser};
1253                         print ON_YELLOW.BLACK."auto-setting Apache User to : $message".RESET."\n";
1254                 } else {
1255                         $message=getmessage('EnterApacheUser', [$etcdir]);
1256                 }
1257                 until (defined($httpduser) && length($httpduser) && getpwnam($httpduser)) {
1258                         if ($auto_install->{EnterApacheUser}) {
1259                                 $httpduser = $auto_install->{EnterApacheUser};
1260                         } else {
1261                                 $httpduser=showmessage($message, "free", '');
1262                         }
1263                         if (length($httpduser)>0) {
1264                                 unless (getpwnam($httpduser)) {
1265                                         my $message=getmessage('InvalidUserid', [$httpduser]);
1266                                         showmessage($message,'PressEnter');
1267                                 }
1268                         } else {
1269                         }
1270                 }
1271         }
1272 }
1273
1274
1275 =item getapachevhostinfo
1276
1277     getapachevhostinfo;
1278
1279 Gets various pieces of information related to virtual hosting:
1280 the webmaster email address, virtual hostname, and the ports
1281 that the OPAC and INTRANET modules run on.
1282
1283 These pieces of information are saved to global variables; the
1284 function does not return any values.
1285
1286 =cut
1287
1288 $messages->{'ApacheConfigIntroduction'}->{en} =
1289    heading('APACHE CONFIGURATION') . qq|
1290 Koha needs to write an Apache configuration file for the
1291 OPAC and Librarian sites.  By default this installer
1292 will do this by using one name and two different ports
1293 for the virtual hosts.  There are other ways to set this up,
1294 and the installer will leave comments in
1295 %s/koha-httpd.conf about them.
1296
1297 NOTE: You will need to add lines to your main httpd.conf to
1298 include %s/koha-httpd.conf
1299 and to make sure it is listening on the right ports
1300 (using the Listen directive).
1301
1302 Press <ENTER> to continue: |;
1303
1304 $messages->{'GetVirtualHostEmail'}->{en} =
1305    heading('WEB E-MAIL CONTACT') . qq|
1306 Enter the e-mail address to be used as a contact for Koha.  This
1307 address is displayed if fatal errors are encountered.
1308
1309 E-mail contact [%s]: |;
1310
1311 $messages->{'GetServerName'}->{en} =
1312    heading('WEB HOST NAME OR IP ADDRESS') . qq|
1313 Please enter the host name or IP address that you wish to use for koha.
1314 Normally, this should be a name or IP that belongs to this machine.
1315
1316 Host name or IP Address [%s]: |;
1317
1318 $messages->{'GetOpacPort'}->{en} = heading('OPAC PORT') . qq|
1319 Please enter the port for your OPAC interface.  This defaults to port 80, but
1320 if you are already serving web content with this hostname, you should change it
1321 to a different port (8000 might be a good choice, but check any firewalls).
1322
1323 Enter the OPAC Port [%s]: |;
1324
1325 $messages->{'GetIntranetPort'}->{en} =
1326    heading('LIBRARIAN PORT') . qq|
1327 Please enter the port for your Librarian interface.  This must be different from
1328 the OPAC port (%s).
1329
1330 Enter the Intranet Port [%s]: |;
1331
1332
1333 sub getapachevhostinfo {
1334         my ($auto_install) = @_;
1335     $svr_admin = "webmaster\@$domainname";
1336     $servername=`hostname`;
1337     chomp $servername;
1338     $opacport=80;
1339     $intranetport=8080;
1340
1341         if ($auto_install->{GetVirtualHostEmail}) {
1342                 $svr_admin=$auto_install->{GetVirtualHostEmail};
1343                 print ON_YELLOW.BLACK."auto-setting VirtualHostEmail to : $svr_admin".RESET."\n";
1344         } else {
1345                 showmessage(getmessage('ApacheConfigIntroduction',[$etcdir,$etcdir]), 'PressEnter');
1346                 $svr_admin=showmessage(getmessage('GetVirtualHostEmail', [$svr_admin]), 'email', $svr_admin);
1347         }
1348         if ($auto_install->{servername}) {
1349                 $servername=$auto_install->{servername};
1350                 print ON_YELLOW.BLACK."auto-setting server name to : $servername".RESET."\n";
1351         } else {
1352         $servername=showmessage(getmessage('GetServerName', [$servername]), 'free', $servername);
1353         }
1354         if ($auto_install->{opacport}) {
1355                 $opacport=$auto_install->{opacport};
1356                 print ON_YELLOW.BLACK."auto-setting opac port to : $opacport".RESET."\n";
1357         } else {
1358             $opacport=showmessage(getmessage('GetOpacPort', [$opacport]), 'numerical', $opacport);
1359         }
1360         if ($auto_install->{intranetport}) {
1361                 $intranetport=$auto_install->{intranetport};
1362                 print ON_YELLOW.BLACK."auto-setting intranet port to : $intranetport".RESET."\n";
1363         } else {
1364             $intranetport=showmessage(getmessage('GetIntranetPort', [$opacport, $intranetport]), 'numerical', $intranetport);
1365         }
1366
1367 }
1368
1369
1370 =item updateapacheconf
1371
1372     updateapacheconf;
1373
1374 Updates the Apache config file according to parameters previously
1375 specified by the user.
1376
1377 It will append fully-commented directives at the end of the original
1378 Apache config file.  The old config file is renamed with an extension
1379 of .prekoha.
1380
1381 If you need to uninstall Koha for any reason, the lines between
1382
1383     # Ports to listen to for Koha
1384
1385 and the block of comments beginning with
1386
1387     # If you want to use name based Virtual Hosting:
1388
1389 must be removed.
1390
1391 =cut
1392
1393 $messages->{'StartUpdateApache'}->{en} =
1394    heading('UPDATING APACHE CONFIGURATION') . qq|
1395 Checking for modules that need to be loaded...
1396 |;
1397
1398 $messages->{'ApacheConfigMissingModules'}->{en} =
1399    heading('APACHE CONFIGURATION NEEDS UPDATE') . qq|
1400 Koha uses the mod_env and mod_include apache features, but the
1401 installer did not find them in your config.  Please
1402 make sure that they are enabled for your Koha site.
1403
1404 Press <ENTER> to continue: |;
1405
1406
1407 $messages->{'ApacheAlreadyConfigured'}->{en} =
1408    heading('APACHE ALREADY CONFIGURED') . qq|
1409 %s appears to already have an entry for Koha.  You may need to edit %s
1410 if anything has changed since it was last set up.  This
1411 script will not attempt to modify an existing Koha apache
1412 configuration.
1413
1414 Press <ENTER> to continue: |;
1415
1416 sub updateapacheconf {
1417         my ($auto_install)=@_;
1418     my $logfiledir=$kohalogdir;
1419     my $httpdconf = $etcdir."/koha-httpd.conf";
1420    
1421     showmessage(getmessage('StartUpdateApache'), 'none') unless $auto_install->{NoPressEnter};
1422         # to be polite about it: I don't think this should touch the main httpd.conf
1423
1424         # QUESTION: Should we warn for includes_module too?
1425     my $envmodule=0;
1426     my $includesmodule=0;
1427     open HC, "<$realhttpdconf";
1428     while (<HC>) {
1429         if (/^\s*#\s*LoadModule env_module /) {
1430             showmessage(getmessage('ApacheConfigMissingModules'));
1431             $envmodule=1;
1432         }
1433         if (/\s*LoadModule includes_module / ) {
1434             $includesmodule=1;
1435         }
1436     }
1437
1438         startsysout;
1439     if (`grep -q 'VirtualHost $servername' "$httpdconf" 2>/dev/null`) {
1440         showmessage(getmessage('ApacheAlreadyConfigured', [$httpdconf, $httpdconf]), 'PressEnter');
1441         return;
1442     } else {
1443         my $includesdirectives='';
1444         if ($includesmodule) {
1445             $includesdirectives.="Options +Includes\n";
1446             $includesdirectives.="   AddHandler server-parsed .html\n";
1447         }
1448         open(SITE,">$httpdconf") or warn "Insufficient priveleges to open $httpdconf for writing.\n";
1449         my $opaclisten = '';
1450         if ($opacport != 80) {
1451             $opaclisten="Listen $opacport";
1452         }
1453         my $intranetlisten = '';
1454         if ($intranetport != 80) {
1455             $intranetlisten="Listen $intranetport";
1456         }
1457         print SITE <<EOP
1458
1459 # Ports to listen to for Koha
1460 # uncomment these if they aren't already in main httpd.conf
1461 #$opaclisten
1462 #$intranetlisten
1463
1464 # NameVirtualHost is used by one of the optional configurations detailed below
1465
1466 #NameVirtualHost 11.22.33.44
1467
1468 # KOHA's OPAC Configuration
1469 <VirtualHost $servername\:$opacport>
1470    ServerAdmin $svr_admin
1471    DocumentRoot $opacdir/htdocs
1472    ServerName $servername
1473    ScriptAlias /cgi-bin/koha/ $opacdir/cgi-bin/
1474    ErrorLog $logfiledir/opac-error_log
1475    TransferLog $logfiledir/opac-access_log
1476    SetEnv PERL5LIB "$intranetdir/modules"
1477    SetEnv KOHA_CONF "$etcdir/koha.conf"
1478    $includesdirectives
1479 </VirtualHost>
1480
1481 # KOHA's INTRANET Configuration
1482 <VirtualHost $servername\:$intranetport>
1483    ServerAdmin $svr_admin
1484    DocumentRoot $intranetdir/htdocs
1485    ServerName $servername
1486    ScriptAlias /cgi-bin/koha/ "$intranetdir/cgi-bin/"
1487    ErrorLog $logfiledir/koha-error_log
1488    TransferLog $logfiledir/koha-access_log
1489    SetEnv PERL5LIB "$intranetdir/modules"
1490    SetEnv KOHA_CONF "$etcdir/koha.conf"
1491    $includesdirectives
1492 </VirtualHost>
1493
1494 # If you want to use name based Virtual Hosting:
1495 #   1. remove the two Listen lines
1496 #   2. replace $servername\:$opacport wih your.opac.domain.name
1497 #   3. replace ServerName $servername wih ServerName your.opac.domain.name
1498 #   4. replace $servername\:$intranetport wih your intranet domain name
1499 #   5. replace ServerName $servername wih ServerName your.intranet.domain.name
1500 #
1501 # If you want to use NameVirtualHost'ing (using two names on one ip address):
1502 #   1.  Follow steps 1-5 above
1503 #   2.  Uncomment the NameVirtualHost line and set the correct ip address
1504
1505 EOP
1506
1507
1508     }
1509 }
1510
1511
1512 =item basicauthentication
1513
1514     basicauthentication;
1515
1516 Asks the user whether HTTP basic authentication is wanted, and,
1517 if so, the user name and password for the basic authentication.
1518
1519 These pieces of information are saved to global variables; the
1520 function does not return any values.
1521
1522 =cut
1523
1524 # $messages->{'IntranetAuthenticationQuestion'}->{en} =
1525 #    heading('LIBRARIAN AUTHENTICATION') . qq|
1526 # The Librarian site can be password protected using
1527 # Apache's Basic Authorization instead of Koha user details.
1528
1529 # This method going to be phased out very soon.  Most users should answer N here.
1530
1531 # Would you like to do this (Y/[N]): |; #'
1532
1533 # $messages->{'BasicAuthUsername'}->{en}="Please enter a username for librarian access [%s]: ";
1534 # $messages->{'BasicAuthPassword'}->{en}="Please enter a password for %s: ";
1535 # $messages->{'BasicAuthPasswordWasBlank'}->{en}="\nYou cannot use a blank password!\n\n";
1536
1537 # sub basicauthentication {
1538 #     my $message=getmessage('IntranetAuthenticationQuestion');
1539 #     my $answer=showmessage($message, 'yn', 'n');
1540 #     my $httpdconf = $etcdir."/koha-httpd.conf";
1541
1542 #     my $apacheauthusername='librarian';
1543 #     my $apacheauthpassword='';
1544 #     if ($answer=~/^y/i) {
1545 #       ($apacheauthusername) = showmessage(getmessage('BasicAuthUsername', [ $apacheauthusername]), 'free', $apacheauthusername, 1);
1546 #       $apacheauthusername=~s/[^a-zA-Z0-9]//g;
1547 #       while (! $apacheauthpassword) {
1548 #           ($apacheauthpassword) = showmessage(getmessage('BasicAuthPassword', [ $apacheauthusername]), 'free', 1);
1549 #           if (!$apacheauthpassword) {
1550 #               ($apacheauthpassword) = showmessage(getmessage('BasicAuthPasswordWasBlank'), 'none', '', 1);
1551 #           }
1552 #       }
1553 #       open AUTH, ">$etcdir/kohaintranet.pass";
1554 #       my $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
1555 #       my $salt=substr($chars, int(rand(length($chars))),1);
1556 #       $salt.=substr($chars, int(rand(length($chars))),1);
1557 #       print AUTH $apacheauthusername.":".crypt($apacheauthpassword, $salt)."\n";
1558 #       close AUTH;
1559 #       open(SITE,">>$httpdconf") or warn "Insufficient priveleges to open $realhttpdconf for writing.\n";
1560 #       print SITE <<EOP
1561
1562 # <Directory $intranetdir>
1563 #     AuthUserFile $etcdir/kohaintranet.pass
1564 #     AuthType Basic
1565 #     AuthName "Koha Intranet (for librarians only)"
1566 #     Require  valid-user
1567 # </Directory>
1568 # EOP
1569 #     }
1570 #     close(SITE);
1571 # }
1572
1573
1574 =item installfiles
1575
1576     installfiles
1577
1578 Install the Koha files to the specified OPAC and INTRANET
1579 directories (usually in /usr/local/koha).
1580
1581 The koha.conf file is created, but as koha.conf.tmp. The
1582 caller is responsible for calling finalizeconfigfile when
1583 installation is completed, to rename it back to koha.conf.
1584
1585 =cut
1586
1587 $messages->{'InstallFiles'}->{en} = heading('INSTALLING FILES') . qq|
1588 Copying files to installation directories:
1589
1590 |;
1591
1592 $messages->{'OldFiles'}->{en} = heading('OLD FILES') . qq|
1593 Any files from the previous edition of Koha have been
1594 copied to a dated backup directory alongside the new
1595 installation. You should move any custom files that you
1596 want to keep (such as your site templates) into the new
1597 directories and then move the backup off of the live
1598 server.
1599
1600 Press ENTER to continue:|;
1601
1602
1603 $messages->{'CopyingFiles'}->{en}="Copying %s to %s.\n";
1604
1605
1606
1607 sub installfiles {
1608
1609         my ($auto_install) = @_;
1610         #MJR: preserve old files, just in case
1611         sub neatcopy {
1612                 my $desc = shift;
1613                 my $src = shift;
1614                 my $tgt = shift;
1615                 if (-e $tgt) {
1616                 print getmessage('CopyingFiles', ["old ".$desc,$tgt.strftime("%Y%m%d%H%M",localtime())]) unless ($auto_install->{NoPressEnter});
1617                         startsysout();
1618                         system("mv ".$tgt." ".$tgt.strftime("%Y%m%d%H%M",localtime()));
1619                 }
1620                 print getmessage('CopyingFiles', [$desc,$tgt]) unless ($auto_install->{NoPressEnter});
1621                 startsysout;
1622                 system("cp -R ".$src." ".$tgt);
1623         }
1624
1625 #       my ($auto_install) = @_;
1626         showmessage(getmessage('InstallFiles'),'none') unless ($auto_install->{NoPressEnter});
1627
1628         neatcopy("admin templates", 'intranet-html', "$intranetdir/htdocs");
1629         neatcopy("admin interface", 'intranet-cgi', "$intranetdir/cgi-bin");
1630         neatcopy("main scripts", 'scripts', "$intranetdir/scripts");
1631         neatcopy("perl modules", 'modules', "$intranetdir/modules");
1632         neatcopy("OPAC templates", 'opac-html', "$opacdir/htdocs");
1633         neatcopy("OPAC interface", 'opac-cgi', "$opacdir/cgi-bin");
1634         startsysout();
1635         system("touch $opacdir/cgi-bin/opac");
1636
1637         #MJR: is this necessary?
1638         if ($> == 0) {
1639                 system("chown -R $httpduser:$httpduser $opacdir $intranetdir");
1640         }
1641         system("chmod -R a+rx $opacdir $intranetdir");
1642
1643         # Create /etc/koha.conf
1644
1645         my $old_umask = umask(027); # make sure koha.conf is never world-readable
1646         open(SITES,">$etcdir/koha.conf.tmp") or warn "Couldn't create file at $etcdir. Must have write capability.\n";
1647         print SITES qq|
1648 database=$database
1649 hostname=$hostname
1650 user=$user
1651 pass=$pass
1652 intranetdir=$intranetdir
1653 opacdir=$opacdir
1654 kohalogdir=$kohalogdir
1655 kohaversion=$newversion
1656 httpduser=$httpduser
1657 intrahtdocs=$intranetdir/htdocs/intranet-tmpl
1658 opachtdocs=$opacdir/htdocs/opac-tmpl
1659 |;
1660         close(SITES);
1661         umask($old_umask);
1662
1663         startsysout();
1664         #MJR: can't help but this be broken, can we?
1665         chmod 0440, "$etcdir/koha.conf.tmp";
1666         
1667         #MJR: does this contain any passwords?
1668         chmod 0755, "$intranetdir/scripts/z3950daemon/z3950-daemon-launch.sh", "$intranetdir/scripts/z3950daemon/z3950-daemon-shell.sh", "$intranetdir/scripts/z3950daemon/processz3950queue";
1669
1670         #MJR: generate our own settings, to remove the /home/paul hardwired links
1671         open(FILE,">$intranetdir/scripts/z3950daemon/z3950-daemon-options");
1672         print FILE "RunAsUser=$httpduser\nKohaZ3950Dir=$intranetdir/scripts/z3950daemon\nKohaModuleDir=$intranetdir/modules\nLogDir=$kohalogdir\nKohaConf=$etcdir/koha.conf";
1673         close(FILE);
1674
1675         if ($> == 0) {
1676             chown((getpwnam($httpduser)) [2,3], "$etcdir/koha.conf.tmp") or warn "can't chown koha.conf: $!";
1677                 chown(0, (getpwnam($httpduser)) [3], "$intranetdir/scripts/z3950daemon/z3950-daemon-shell.sh") or warn "can't chown $intranetdir/scripts/z3950daemon/z3950-daemon-shell.sh: $!";
1678                 chown(0, (getpwnam($httpduser)) [3], "$intranetdir/scripts/z3950daemon/processz3950queue") or warn "can't chown $intranetdir/scripts/z3950daemon/processz3950queue: $!";
1679         } #MJR: report that we haven't chown()d.
1680         else {
1681                 print "Please check permissions in $intranetdir/scripts/z3950daemon\n";
1682         }
1683         showmessage(getmessage('OldFiles'),'PressEnter') unless $auto_install->{NoPressEnter};
1684 }
1685
1686
1687 =item databasesetup
1688
1689     databasesetup;
1690
1691 Finds out where the MySQL utitlities are located in the system,
1692 then create the Koha database structure and MySQL permissions.
1693
1694 =cut
1695
1696 $messages->{'MysqlRootPassword'}->{en} =
1697    heading('MYSQL ROOT USER PASSWORD') . qq|
1698 To create the koha database, please enter your
1699 mysql server's root user password:
1700
1701 Password: |;    #'
1702
1703 $messages->{'CreatingDatabase'}->{en} = heading('CREATING DATABASE') . qq|
1704 Creating the MySQL database for Koha...
1705
1706 |;
1707
1708 $messages->{'CreatingDatabaseError'}->{en} =
1709    heading('ERROR CREATING DATABASE') . qq|
1710 Couldn't connect to the MySQL server for the reason given above.
1711 This is a serious problem, the database will not get installed.
1712
1713 Press <ENTER> to continue: |;   #'
1714
1715 $messages->{'SampleData'}->{en} = heading('SAMPLE DATA') . qq|
1716 If you are installing Koha for evaluation purposes,
1717 you can install some sample data now.
1718
1719 If you are installing Koha to use your own
1720 data, you probably don't want this sample data installed.
1721
1722 Would you like to install the sample data? Y/[N]: |;    #'
1723
1724 $messages->{'SampleDataInstalled'}->{en} =
1725    heading('SAMPLE DATA INSTALLED') . qq|
1726 Sample data has been installed.  For some suggestions on testing Koha, please
1727 read the file doc/HOWTO-Testing.  If you find any bugs, please submit them at
1728 http://bugs.koha.org/.  If you need help with testing Koha, you can post a
1729 question through the koha-devel mailing list, or you can check for a developer
1730 online at irc.katipo.co.nz:6667 channel #koha.
1731
1732 You can find instructions for subscribing to the Koha mailing lists at:
1733
1734     http://www.koha.org
1735
1736
1737 Press <ENTER> to continue: |;
1738
1739 $messages->{'AddBranchPrinter'}->{en} = heading('Add Branch and Printer') . qq|
1740 Would you like to describe an initial branch and printer? [Y]/N: |;
1741
1742 $messages->{'BranchName'}->{en}="Branch Name [%s]: ";
1743 $messages->{'BranchCode'}->{en}="Branch Code (4 letters or numbers) [%s]: ";
1744 $messages->{'PrinterQueue'}->{en}="Printer Queue [%s]: ";
1745 $messages->{'PrinterName'}->{en}="Printer Name [%s]: ";
1746
1747 sub databasesetup {
1748         my ($auto_install) = @_;
1749     $mysqluser = 'root';
1750     $mysqlpass = '';
1751         my $mysqldir = getmysqldir();
1752
1753         if ($auto_install->{MysqlRootPassword}) {
1754                 $mysqlpass=$auto_install->{MysqlRootPassword};
1755         } else {
1756         # we must not put the mysql root password on the command line
1757                 $mysqlpass=     showmessage(getmessage('MysqlRootPassword'),'silentfree');
1758         }
1759         
1760         showmessage(getmessage('CreatingDatabase'),'none') unless ($auto_install->{NoPressEnter});
1761         # set the login up
1762         setmysqlclipass($mysqlpass);
1763         # Set up permissions
1764         startsysout();
1765         print system("$mysqldir/bin/mysql -u$mysqluser mysql -e \"insert into user (Host,User,Password) values ('$hostname','$user',password('$pass'))\"\;");#"
1766         system("$mysqldir/bin/mysql -u$mysqluser 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 ('%','$database','$user','Y','Y','Y','Y','Y','Y','Y','Y')\"");
1767         system("$mysqldir/bin/mysqladmin -u$mysqluser reload");
1768         # Change to admin user login
1769         setmysqlclipass($pass);
1770         my $result=system("$mysqldir/bin/mysqladmin", "-u$user", "create", "$database");
1771         if ($result) {
1772                 showmessage(getmessage('CreatingDatabaseError'),'PressEnter', '', 1);
1773         } else {
1774                 # Create the database structure
1775                 startsysout();
1776                 system("$mysqldir/bin/mysql -u$user $database < koha.mysql");
1777         }
1778
1779 }
1780
1781
1782 =item updatedatabase
1783
1784     updatedatabase;
1785
1786 Updates the Koha database structure, including the addition of
1787 MARC tables.
1788
1789 The MARC tables are also populated in addition to being created.
1790
1791 Because updatedatabase calls scripts/updater/updatedatabase to
1792 do the actual update, and that script uses C4::Context,
1793 $etcdir/koha.conf must exist at this point. We use the KOHA_CONF
1794 environment variable to do this.
1795
1796 FIXME: (See checkabortedinstall as it depends on old symlink way.)
1797
1798 =cut
1799
1800 $messages->{'UpdateMarcTables'}->{en} =
1801    heading('MARC FIELD DEFINITIONS') . qq|
1802 You can import MARC settings for:
1803
1804   1 MARC21
1805   2 UNIMARC
1806   N none
1807
1808 NOTE: If you choose N,
1809 nothing will be added, and you must create them all yourself.
1810 Only choose N if you want to use a MARC format not listed here,
1811 such as DANMARC.  We would like to hear from you if you do.
1812
1813 UPDATE : If you UPDATE your version from a previous 2.x.x, the right choice here is N (None) to preserve your local MARC setup.
1814
1815 Choose MARC definition [1]: |;
1816
1817 $messages->{'Language'}->{en} = heading('CHOOSE LANGUAGE') . qq|
1818 This version of koha supports a few languages.
1819
1820   en : default language, all pages available
1821   fr : complete translation (except pictures)
1822   es : partial librarian site translation (including pictures)
1823   pl : complete OPAC and partial librarian translation
1824   zh_TW : partial translation
1825
1826 en is used when a screen is not available in your language
1827
1828 If you specify a language here, you can still
1829 change it from the system preferences screen in the librarian sit.
1830
1831 Which language do you choose? |;
1832
1833 sub updatedatabase {
1834         my ($auto_install) = @_;
1835     # At this point, $etcdir/koha.conf must exist, for C4::Context
1836     $ENV{"KOHA_CONF"}=$etcdir.'/koha.conf';
1837     if (! -e $ENV{"KOHA_CONF"}) { $ENV{"KOHA_CONF"}=$etcdir.'/koha.conf.tmp'; }
1838         startsysout();  
1839         my $result=system ("perl -I $intranetdir/modules scripts/updater/updatedatabase -s");
1840         if ($result) {
1841                 restoremycnf();
1842                 print "Problem updating database...\n";
1843                 exit;
1844         }
1845         my $response;
1846         if ($auto_install->{UpdateMarcTables}) {
1847                 $response=$auto_install->{UpdateMarcTables};
1848                 print ON_YELLOW.BLACK."auto-setting UpdateMarcTable to : $response".RESET."\n";
1849         } else {
1850                 $response=showmessage(getmessage('UpdateMarcTables'), 'restrictchar 12N', '1');
1851         }
1852         startsysout();
1853         if ($response eq '1') {
1854                 system("cat scripts/misc/marc_datas/marc21_en/structure_def.sql | $mysqldir/bin/mysql -u$user $database");
1855                 system("cat scripts/misc/lang-datas/en/stopwords.sql | $mysqldir/bin/mysql -u$user $database");
1856         }
1857         if ($response eq '2') {
1858                 system("cat scripts/misc/marc_datas/unimarc_fr/structure_def.sql | $mysqldir/bin/mysql -u$user $database");
1859                 system("cat scripts/misc/lang-datas/fr/stopwords.sql | $mysqldir/bin/mysql -u$user $database");
1860         }
1861         delete($ENV{"KOHA_CONF"});
1862
1863         print RESET."\nFinished updating of database. Press <ENTER> to continue..." unless ($auto_install->{NoPressEnter});
1864         <STDIN> unless ($auto_install->{NoPressEnter});
1865 }
1866
1867
1868 =item populatedatabase
1869
1870     populatedatabase;
1871
1872 Populate the non-MARC tables. If the user wants to install the
1873 sample data, install them.
1874
1875 =cut
1876
1877 $messages->{'ConfirmFileUpload'}->{en} = qq|
1878 Confirm loading of this file into Koha  [Y]/N: |;
1879
1880 sub populatedatabase {
1881         my ($auto_install) = @_;
1882         my $input;
1883         my $response;
1884         my $branch;
1885         if ($auto_install->{BranchName}) {
1886                 $branch=$auto_install->{BranchName};
1887                 print ON_YELLOW.BLACK."auto-setting a branch : $branch".RESET."\n";
1888         } else {
1889                 $response=showmessage(getmessage('AddBranchPrinter'), 'yn', 'y');
1890                 unless ($response =~/^n/i) {
1891                         $branch=showmessage(getmessage('BranchName', [$branch]), 'free', $branch, 1);
1892                         $branch=~s/[^A-Za-z0-9\s]//g;
1893                 }
1894         }
1895         if ($branch) {
1896                 my $branchcode=$branch;
1897                 $branchcode=~s/[^A-Za-z0-9]//g;
1898                 $branchcode=uc($branchcode);
1899                 $branchcode=substr($branchcode,0,4);
1900                 if ($auto_install->{BranchCode}) {
1901                         $branchcode=$auto_install->{BranchCode};
1902                         print ON_YELLOW.BLACK."auto-setting branch code : $branchcode".RESET."\n";
1903                 } else {
1904                         $branchcode=showmessage(getmessage('BranchCode', [$branchcode]), 'free', $branchcode, 1);
1905                 }
1906                 $branchcode=~s/[^A-Za-z0-9]//g;
1907                 $branchcode=uc($branchcode);
1908                 $branchcode=substr($branchcode,0,4);
1909                 $branchcode or $branchcode='DEF';
1910
1911                 startsysout();
1912                 system("$mysqldir/bin/mysql -u$user $database -e \"insert into branches (branchcode,branchname,issuing) values ('$branchcode', '$branch', 1)\"");
1913                 system("$mysqldir/bin/mysql -u$user $database -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'IS')\"");
1914                 system("$mysqldir/bin/mysql -u$user $database -e \"insert into branchrelations (branchcode,categorycode) values ('MAIN', 'CU')\"");
1915
1916                 my $printername;
1917                 my $printerqueue;
1918                 if ($auto_install->{PrinterName}) {
1919                         $printername=$auto_install->{PrinterName};
1920                         print ON_YELLOW.BLACK."auto-setting a printer : $printername".RESET."\n";
1921                 } else {
1922                         $printername=showmessage(getmessage('PrinterName', [$printername]), 'free', $printername, 1);
1923                         $printername=~s/[^A-Za-z0-9\s]//g;
1924                 }
1925                 if ($auto_install->{PrinterQueue}) {
1926                         $printerqueue=$auto_install->{PrinterQueue};
1927                         print ON_YELLOW.BLACK."auto-setting printer queue to : $printerqueue".RESET."\n";
1928                 } else {
1929                         $printerqueue=showmessage(getmessage('PrinterQueue', [$printerqueue]), 'free', $printerqueue, 1);
1930                         $printerqueue=~s/[^A-Za-z0-9]//g;
1931                 }
1932                 startsysout();  
1933                 system("$mysqldir/bin/mysql -u$user $database -e \"insert into printers (printername,printqueue,printtype) values ('$printername', '$printerqueue', '')\"");
1934         }
1935         my $language;
1936         if ($auto_install->{Language}) {
1937                 $language=$auto_install->{Language};
1938                 print ON_YELLOW.BLACK."auto-setting language to : $language".RESET."\n";
1939         } else {
1940                 $language=showmessage(getmessage('Language'), 'free', 'en');
1941         }
1942         startsysout();  
1943         system("$mysqldir/bin/mysql -u$user $database -e \"update systempreferences set value='$language' where variable='opaclanguages'\"");
1944         my @dirs;
1945         if (-d "scripts/misc/sql-datas") {
1946                 # ask for directory to look for files to append
1947                 my @directories;
1948                 push @directories,"FINISHED";
1949                 if (-d "scripts/misc/sql-datas") {
1950                         opendir D, "scripts/misc/sql-datas";
1951                         foreach my $dir (readdir D) {
1952                                 next if ($dir =~ /^\./);
1953                                 push @directories, $dir;
1954                         }
1955                 }
1956                 my $loopend=0;
1957                 while (not $loopend) {
1958                         print heading("SELECT SQL DIRECTORY");
1959                         print qq|
1960 Select a directory. You will see every file included in this directory and be able to choose file(s) to import into Koha
1961 This is a VERY important feature. By selecting the proper options, you can get a pre-setup Koha, almost ready to be put in production.
1962 Choose wisely.
1963 |;
1964                         for (my $i=0;$i<=$#directories;$i++) {
1965                                 print "$i => ".$directories[$i]."\n";
1966                         }
1967                         my $sqluploaddir =<STDIN>;
1968                         if ($sqluploaddir==0) {
1969                                 $loopend = 1;
1970                         } else {
1971                                 $sqluploaddir = $directories[$sqluploaddir];
1972                                 # CHECK for any other file to append...
1973                                 my @sql;
1974                                 push @sql,"FINISHED";
1975                                 if (-d "scripts/misc/sql-datas/$sqluploaddir") {
1976                                         opendir D, "scripts/misc/sql-datas/$sqluploaddir";
1977                                         foreach my $sql (readdir D) {
1978                                                 next unless ($sql =~ /.txt$/);
1979                                                 push @sql, $sql;
1980                                         }
1981                                 }
1982                                 $loopend=0;
1983                                 while (not $loopend) {
1984                                         print heading("SELECT SQL FILE");
1985                                         print qq|
1986 Select a file to append to the Koha DB.
1987 enter a number. A detailled explanation of the file will be given
1988 if you confirm, the file will be added to the DB
1989 |;
1990                                         for (my $i=0;$i<=$#sql;$i++) {
1991                                                 print "$i => ".$sql[$i]."\n";
1992                                         }
1993                                         my $response =<STDIN>;
1994                                         if ($response==0) {
1995                                                 $loopend = 1;
1996                                         } else {
1997                                                 # show the content of the file
1998                                                 my $FileToUpload = $sql[$response];
1999                                                 open FILE,"scripts/misc/sql-datas/$sqluploaddir/$FileToUpload";
2000                                                 my $content = <FILE>;
2001                                                 print heading("INSERT $sqluploaddir/$FileToUpload ?")."$content\n";
2002                                                 # ask confirmation
2003                                                 $response=showmessage(getmessage('ConfirmFileUpload'), 'yn', 'y');
2004                                                 # if confirmed, upload the file in the DB
2005                                                 unless ($response =~/^n/i) {
2006                                                         $FileToUpload =~ s/\.txt/\.sql/;
2007                                                         system("$mysqldir/bin/mysql -u$user $database <scripts/misc/sql-datas/$sqluploaddir/$FileToUpload");
2008                                                 }
2009                                         }
2010                                 }
2011                                 $loopend=0;
2012                         }
2013                 }
2014         }
2015 }
2016
2017 =item restartapache
2018
2019     restartapache;
2020
2021 Asks the user whether to restart Apache, and restart it if the user
2022 wants so.
2023
2024 =cut
2025
2026 $messages->{'RestartApache'}->{en} = heading('RESTART APACHE') . qq|
2027 The web server daemon needs to be restarted to load the new configuration for Koha.
2028 The installer can do this if you are using Apache and give the root password.
2029
2030 Would you like to try to restart Apache now?  [Y]/N: |;
2031
2032 sub restartapache {
2033         my ($auto_install)=@_;
2034         my $response;
2035     $response=showmessage(getmessage('RestartApache'), 'yn', 'y') unless ($auto_install->{NoPressEnter});
2036     $response='y' if ($auto_install->{NoPressEnter});
2037
2038     unless ($response=~/^n/i) {
2039                 startsysout();
2040                 # Need to support other init structures here?
2041                 if (-e "/etc/rc.d/init.d/httpd") {
2042                         system('su root -c "/etc/rc.d/init.d/httpd restart"');
2043                 } elsif (-e "/etc/init.d/apache") {
2044                         system('su root -c "/etc/init.d/apache restart"');
2045                 } elsif (-e "/etc/init.d/apache-ssl") {
2046                         system('su root -c "/etc/init.d/apache-ssl restart"');
2047                 }
2048         }
2049 }
2050
2051 =item backupkoha
2052
2053    backupkoha;
2054
2055 This function attempts to back up all koha's details.
2056
2057 =cut
2058
2059 $messages->{'BackupDir'}->{en} = heading('BACKUP STORAGE').qq|
2060 The upgrader will now try to backup your old files.
2061
2062 Please specify a directory to store the backup in [%s]: |;
2063
2064 $messages->{'BackupSummary'}->{en} = heading('BACKUP SUMMARY').qq|
2065 Backed up:
2066
2067 %6d biblio entries
2068 %6d biblioitems entries
2069 %6d items entries
2070 %6d borrowers
2071
2072 File Listing
2073 ---------------------------------------------------------------------
2074 %s
2075 ---------------------------------------------------------------------
2076
2077 Does this look right? ([Y]/N): |;
2078
2079 #FIXME: rewrite to use Install.pm
2080 sub backupkoha {
2081 if (!$ENV{prefix}) { $ENV{prefix} = "/usr/local"; }
2082 my $backupdir=$ENV{prefix}.'/backups';
2083
2084 my $answer = showmessage(getmessage('BackupDir',[$backupdir]),'free',$backupdir);
2085
2086 if (! -e $backupdir) {
2087         my $result=mkdir ($backupdir, oct(770));
2088         if ($result==0) {
2089                 my @dirs = split(m#/#, $backupdir);
2090                 my $checkdir='';
2091                 foreach (@dirs) {
2092                         $checkdir.="$_/";
2093                         unless (-e "$checkdir") {
2094                                 mkdir($checkdir, 0775);
2095                         }
2096                 }
2097         }
2098 }
2099
2100 chmod 0770, $backupdir;
2101
2102 # Backup MySql database
2103 #
2104 #
2105 my $mysqldir = getmysqldir();
2106
2107 my ($sec, $min, $hr, $day, $month, $year) = (localtime(time))[0,1,2,3,4,5];
2108 $month++;
2109 $year+=1900;
2110 my $date= sprintf "%4d-%02d-%02d_%02d:%02d:%02d", $year, $month, $day,$hr,$min,$sec;
2111
2112 open (MD, "$mysqldir/bin/mysqldump --user=$user --password=$pass --host=$hostname $database|");
2113
2114 (open BF, ">$backupdir/Koha.backup_$date") || (die "Error opening up backup file $backupdir/Koha.backup_$date: $!\n");
2115
2116 my $itemcounter=0;
2117 my $bibliocounter=0;
2118 my $biblioitemcounter=0;
2119 my $membercounter=0;
2120
2121 while (<MD>) {
2122         (/insert into items /i) && ($itemcounter++);
2123         (/insert into biblioitems /i) && ($biblioitemcounter++);
2124         (/insert into biblio /i) && ($bibliocounter++);
2125         (/insert into borrowers /i) && ($membercounter++);
2126         print BF $_;
2127 }
2128
2129 close BF;
2130 close MD;
2131
2132 my $filels=`ls -hl $backupdir/Koha.backup_$date`;
2133 chomp $filels;
2134 $answer = showmessage(getmessage('BackupSummary',[$bibliocounter, $biblioitemcounter, $itemcounter, $membercounter, $filels]),'yn');
2135
2136 if ($answer=~/^n/i) {
2137     print qq|
2138
2139 Aborting.  The database dump is located in:
2140
2141         $backupdir/Koha.backup_$date
2142
2143 |;
2144     exit;
2145 } else {
2146         print "Great! continuing upgrade... \n";
2147 };
2148
2149
2150
2151 }
2152
2153 =item finalizeconfigfile
2154
2155    finalizeconfigfile;
2156
2157 This function must be called when the installation is complete,
2158 to rename the koha.conf.tmp file to koha.conf.
2159
2160 Currently, failure to rename the file results only in a warning.
2161
2162 =cut
2163
2164 sub finalizeconfigfile {
2165         restoremycnf();
2166    rename "$etcdir/koha.conf.tmp", "$etcdir/koha.conf"
2167       || showmessage(<<EOF, 'PressEnter', undef, 1);
2168 An unexpected error, $!, occurred
2169 while the Koha config file is being saved to its final location,
2170 $etcdir/koha.conf.
2171
2172 Couldn't rename file at $etcdir. Must have write capability.
2173
2174 Press Enter to continue.
2175 EOF
2176 #'
2177 }
2178
2179
2180 =item loadconfigfile
2181
2182    loadconfigfile
2183
2184 Open the existing koha.conf file and get its values,
2185 saving the values to some global variables.
2186
2187 If the existing koha.conf file cannot be opened for any reason,
2188 the file is silently ignored.
2189
2190 =cut
2191
2192 sub loadconfigfile {
2193     my %configfile;
2194
2195         #MJR: reverted to r1.53.  Please call setetcdir().  Do NOT hardcode this.
2196         #FIXME: make a dated backup
2197     open (KC, "<$etcdir/koha.conf");
2198     while (<KC>) {
2199      chomp;
2200      (next) if (/^\s*#/);
2201      if (/(.*)\s*=\s*(.*)/) {
2202        my $variable=$1;
2203        my $value=$2;
2204        # Clean up white space at beginning and end
2205        $variable=~s/^\s*//g;
2206        $variable=~s/\s*$//g;
2207        $value=~s/^\s*//g;
2208        $value=~s/\s*$//g;
2209        $configfile{$variable}=$value;
2210      }
2211     }
2212
2213         #MJR: Reverted this too. You do not mess with my privates. Please ask for new functions if required.
2214     $intranetdir=$configfile{'intranetdir'};
2215     $opacdir=$configfile{'opacdir'};
2216     $kohaversion=$configfile{'kohaversion'};
2217     $kohalogdir=$configfile{'kohalogdir'};
2218     $database=$configfile{'database'};
2219     $hostname=$configfile{'hostname'};
2220     $user=$configfile{'user'};
2221     $pass=$configfile{'pass'};
2222 }
2223
2224 END { }       # module clean-up code here (global destructor)
2225
2226 ### These things may move
2227
2228 sub setecho {
2229 my $state=shift;
2230 my $t = POSIX::Termios->new;
2231
2232 $t->getattr();
2233 if ($state) {
2234   $t->setlflag(($t->getlflag) | &POSIX::ECHO);
2235   }
2236 else {
2237   $t->setlflag(($t->getlflag) & !(&POSIX::ECHO));
2238   }
2239 $t->setattr();
2240 }
2241
2242 sub setmysqlclipass {
2243         my $pass = shift;
2244         open(MYCNF,">$mycnf");
2245         chmod(0600,$mycnf);
2246         print MYCNF "[client]\npassword=$pass\n";
2247         close(MYCNF);
2248 }
2249
2250 sub backupmycnf {
2251         if (-e $mycnf) {
2252                 rename $mycnf,$mytmpcnf;
2253         }
2254 }
2255
2256 sub restoremycnf {
2257         if (defined $mycnf && -e $mycnf) {
2258                 unlink($mycnf);
2259         }
2260         if (defined $mytmpcnf && -e $mytmpcnf) {
2261                 rename $mytmpcnf,$mycnf;
2262         }
2263 }
2264
2265 =back
2266
2267 =head1 SEE ALSO
2268
2269 buildrelease.pl
2270 installer.pl
2271 koha.upgrade
2272
2273 =cut
2274
2275 1;