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