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