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