install.pl - Important fix for Algorithm::CheckDigits mismatch
[koha.git] / installer / install.pl
1 #!/usr/bin/perl -w # please develop with -w
2
3 #use diagnostics;
4
5 # use Install;
6 use InstallAuth;
7 use C4::Context;
8 use C4::Output;
9 use C4::Languages;
10
11 use strict;    # please develop with the strict pragma
12
13 use CGI;
14
15 my $query = new CGI;
16 my $step  = $query->param('step');
17
18 my $language = $query->param('language');
19 my ( $template, $loggedinuser, $cookie );
20
21 my $all_languages = getAllLanguages();
22
23 if ( defined($language) ) {
24     setlanguagecookie( $query, $language, "install.pl?step=1" );
25 }
26 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
27     {
28         template_name => "installer/step" . ( $step ? $step : 1 ) . ".tmpl",
29         query         => $query,
30         type          => "intranet",
31         authnotrequired => 0,
32         debug           => 1,
33     }
34 );
35
36 my %info;
37 $info{'dbname'} = C4::Context->config("database");
38 $info{'dbms'} =
39   (   C4::Context->config("db_scheme")
40     ? C4::Context->config("db_scheme")
41     : "mysql" );
42 $info{'hostname'} = C4::Context->config("hostname");
43 $info{'port'}     = C4::Context->config("port");
44 $info{'user'}     = C4::Context->config("user");
45 $info{'password'} = C4::Context->config("pass");
46 my $dbh = DBI->connect(
47     "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
48       . ( $info{port} ? ";port=$info{port}" : "" ),
49     $info{'user'}, $info{'password'}
50 );
51
52 if ( $step && $step == 1 ) {
53     #First Step
54     #Checking ALL perl Modules and services needed are installed.
55     #Whenever there is an error, adding a report to the page
56     $template->param( language => 1 );
57     my $problem;
58
59     unless ( $] >= 5.006001 ) {    # Bug 179
60         $template->param( "problems" => 1, "perlversion" => 1 );
61         $problem = 1;
62     }
63
64     # We could here use a special find
65     my @missing = ();
66     unless ( eval { require ZOOM } ) {
67         push @missing, { name => "ZOOM" };
68     }
69     unless ( eval { require LWP::Simple } ) {
70         push @missing, { name => "LWP::Simple" };
71     }
72     unless ( eval { require XML::Simple } ) {
73         push @missing, { name => "XML::Simple" };
74     }
75     unless ( eval { require MARC::File::XML } ) {
76         push @missing, { name => "MARC::File::XML" };
77     }
78     unless ( eval { require MARC::File::USMARC } ) {
79         push @missing, { name => "MARC::File::USMARC" };
80     }
81     unless ( eval { require DBI } ) {
82         push @missing, { name => "DBI" };
83     }
84     unless ( eval { require Date::Manip } ) {
85         push @missing, { name => "Date::Manip" };
86     }
87     unless ( eval { require DBD::mysql } ) {
88         push @missing, { name => "DBD::mysql" };
89     }
90     unless ( eval { require HTML::Template::Pro } ) {
91         push @missing, { name => "HTML::Template::Pro" };
92     }
93     unless ( eval { require Date::Calc } ) {
94         push @missing, { name => "Date::Calc" };
95     }
96     unless ( eval { require Digest::MD5 } ) {
97         push @missing, { name => "Digest::MD5" };
98     }
99     unless ( eval { require MARC::Record } ) {
100         push @missing, { name => "MARC::Record" };
101     }
102     unless ( eval { require Mail::Sendmail } ) {
103         push @missing, { name => "Mail::Sendmail", usagemail => 1 };
104     }
105     unless ( eval { require List::MoreUtils } ) {
106         push @missing, { name => "List::MoreUtils" };
107     }
108     unless ( eval { require XML::RSS } ) {
109         push @missing, { name => "XML::RSS" };
110     }
111     unless ( eval { require CGI::Carp } ) {
112         push @missing, { name => "CGI::Carp" };
113     }
114
115
116 # The following modules are not mandatory, depends on how the library want to use Koha
117     unless ( eval { require PDF::API2 } ) {
118         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
119             push @missing, { name => "PDF::API2", usagebarcode => 1 };
120         }
121     }
122     unless ( eval { require GD::Barcorde } ) {
123         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
124             push @missing,
125               { name => "GD::Barcode", usagebarcode => 1, usagespine => 1 };
126         }
127     }
128     unless ( eval { require Data::Random } ) {
129         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
130             push @missing, { name => "Data::Random", usagebarcode => 1 };
131         }
132     }
133     unless ( eval { require PDF::Reuse::Barcode } ) {
134         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
135             push @missing, { name => "PDF::Reuse::Barcode", usagebarcode => 1 };
136         }
137     }
138     unless ( eval { require PDF::Report } ) {
139         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
140             push @missing, { name => "PDF::Report", usagebarcode => 1 };
141         }
142     }
143     unless ( eval { require Algorithm::CheckDigits } ) {
144         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
145             push @missing, { name => "Algorithm::CheckDigits", usagebarcode => 1 };
146         }
147     }
148     unless ( eval { require GD::Barcode::UPCE } ) {
149         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
150             push @missing, { name => "GD::Barcode::UPCE", usagepine => 1 };
151         }
152     }
153     unless ( eval { require Net::LDAP } ) {
154         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
155             push @missing, { name => "Net::LDAP", usageLDAP => 1 };
156         }
157     }
158     $template->param( missings => \@missing ) if ( scalar(@missing) > 0 );
159     $template->param( 'checkmodule' => 1 )
160       unless ( scalar(@missing) && $problem );
161
162 }
163 elsif ( $step && $step == 2 ) {
164 #
165 #STEP 2 Check Database connection and access
166 #
167     $template->param(%info);
168     my $checkdb = $query->param("checkdb");
169     $template->param( 'dbconnection' => $checkdb );
170     if ($checkdb) {
171         if ($dbh) {
172
173             # Can connect to the mysql
174             $template->param( "checkdatabaseaccess" => 1 );
175             if ( $info{dbms} eq "mysql" ) {
176
177                 #Check if database created
178                 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
179                 if ( $rv == 1 ) {
180                     $template->param( 'checkdatabasecreated' => 1 );
181                 }
182
183                 #Check if user have all necessary grants on this database.
184                 my $rq =
185                   $dbh->prepare(
186                     "SHOW GRANTS FOR \'$info{user}\'\@'$info{hostname}'");
187                 $rq->execute;
188                 my $grantaccess;
189                 while ( my ($line) = $rq->fetchrow ) {
190                     my $dbname = $info{dbname};
191                     if ( $line =~ m/$dbname/ || index( $line, '*.*' ) > 0 ) {
192                         $grantaccess = 1
193                           if (
194                             index( $line, 'ALL PRIVILEGES' ) > 0
195                             || (   ( index( $line, 'SELECT' ) > 0 )
196                                 && ( index( $line, 'INSERT' ) > 0 )
197                                 && ( index( $line, 'UPDATE' ) > 0 )
198                                 && ( index( $line, 'DELETE' ) > 0 )
199                                 && ( index( $line, 'CREATE' ) > 0 )
200                                 && ( index( $line, 'DROP' ) > 0 ) )
201                           );
202                     }
203                 }
204                 unless ($grantaccess) {
205                     $rq =
206                       $dbh->prepare("SHOW GRANTS FOR \'$info{user}\'\@'\%'");
207                     $rq->execute;
208                     while ( my ($line) = $rq->fetchrow ) {
209                         my $dbname = $info{dbname};
210                         if ( $line =~ m/$dbname/ || index( $line, '*.*' ) > 0 )
211                         {
212                             $grantaccess = 1
213                               if (
214                                 index( $line, 'ALL PRIVILEGES' ) > 0
215                                 || (   ( index( $line, 'SELECT' ) > 0 )
216                                     && ( index( $line, 'INSERT' ) > 0 )
217                                     && ( index( $line, 'UPDATE' ) > 0 )
218                                     && ( index( $line, 'DELETE' ) > 0 )
219                                     && ( index( $line, 'CREATE' ) > 0 )
220                                     && ( index( $line, 'DROP' ) > 0 ) )
221                               );
222                         }
223                     }
224                 }
225                 $template->param( "checkgrantaccess" => $grantaccess );
226             }   # End mysql connect check...
227             
228             elsif ( $info{dbms} eq "Pg" ) {
229                 # Check if database has been created...
230                 my $rv = $dbh->do( "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';" );
231                 if ( $rv == 1 ) {
232                         $template->param( 'checkdatabasecreated' => 1 );
233                 }
234
235                 # Check if user has all necessary grants on this database...
236                 my $rq = $dbh->do( "SELECT u.usesuper
237                                     FROM pg_catalog.pg_user as u
238                                     WHERE u.usename = \'$info{user}\';" );
239                 if ( $rq == 1 ) {
240                         $template->param( "checkgrantaccess" => 1 );
241                 }
242             }   # End Pg connect check...
243         }
244         else {
245             $template->param( "error" => DBI::err, "message" => DBI::errstr );
246         }
247     }
248 }
249 elsif ( $step && $step == 3 ) {
250 #
251 #
252 # STEP 3 : database setup
253 #
254
255     my $op = $query->param('op');
256     if ( $op && $op eq 'finished' ) {
257         #
258         # we have finished, just redirect to mainpage.
259         #
260         print $query->redirect("/cgi-bin/koha/mainpage.pl");
261         exit 1;
262     }
263     elsif ( $op && $op eq 'finish' ) {
264         my $kohaversion=C4::Context::KOHAVERSION;
265         # remove the 3 last . to have a Perl number
266         $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
267         if (C4::Context->preference('Version')) {
268             warn "UPDATE Version";
269             my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
270             $finish->execute($kohaversion);
271         } else {
272             warn "INSERT Version";
273             my $finish=$dbh->prepare("INSERT into systempreferences (variable,value,explanation) values ('Version',?,'The Koha database version. Don t change this value manually, it s holded by the webinstaller')");
274             $finish->execute($kohaversion);
275         }
276
277         # Installation is finished.
278         # We just deny anybody access to install
279         # And we redirect people to mainpage.
280         # The installer will have to relogin since we do not pass cookie to redirection.
281         $template->param( "$op" => 1 );
282     }
283     elsif ( $op && $op eq 'Nozebra' ) {
284         if ($query->param('Nozebra')) {
285             $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='NoZebra'");
286             $dbh->do("UPDATE systempreferences SET value=0 WHERE variable in ('QueryFuzzy','QueryWeightFields','QueryStemming')");
287         } else {
288             $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
289         }
290         $template->param( "$op" => 1 );
291     }
292     elsif ( $op && $op eq 'addframeworks' ) {
293     #
294     # 1ST install, 3rd sub-step : insert the SQL files the user has selected
295     #
296
297         #Framework importing and reports
298         my $lang;
299         my %hashlevel;
300
301        # sort by filename -> prepend with numbers to specify order of insertion.
302         my @fnames = sort {
303             my @aa = split /\/|\\/, ($a);
304             my @bb = split /\/|\\/, ($b);
305             $aa[-1] cmp $bb[-1]
306         } $query->param('framework');
307         if ( $info{dbms} eq 'mysql' ) { $dbh->do('SET FOREIGN_KEY_CHECKS=0'); }
308         elsif ( $info{dbms} eq 'Pg' ) { $dbh->do('SET CONSTRAINTS ALL DEFERRED;'); }
309         my $request =
310           $dbh->prepare(
311             "SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'"
312           );
313         $request->execute;
314         my ($systempreference) = $request->fetchrow;
315         foreach my $file (@fnames) {
316
317             #      warn $file;
318             undef $/;
319             my $error;
320             if ( $info{dbms} eq 'mysql' ) {
321                 my $strcmd = "mysql "
322                         . ( $info{hostname} ? " -h $info{hostname} " : "" )
323                         . ( $info{port}     ? " -P $info{port} "     : "" )
324                         . ( $info{user}     ? " -u $info{user} "     : "" )
325                         . ( $info{password} ? " -p$info{password}"   : "" )
326                         . " $info{dbname} ";
327                 $error = qx($strcmd < $file 2>&1 1>/dev/null);                  # We want to send stdout to null and return only stderr... -fbcit
328             }
329             elsif ( $info{dbms} eq 'Pg' ) { 
330                 my $strcmd = "psql "
331                         . ( $info{hostname} ? " -h $info{hostname} " : "" )
332                         . ( $info{port}     ? " -p $info{port} "     : "" )
333                         . ( $info{user}     ? " -U $info{user} "     : "" )
334 #                        . ( $info{password} ? " -W $info{password}"   : "" )
335                         . " $info{dbname} ";
336                 $error = qx($strcmd -f $file 2>&1 1>/dev/null);                 # ...even more so with psql...
337             }
338             my @file = split qr(\/|\\), $file;
339             $lang = $file[ scalar(@file) - 3 ] unless ($lang);
340             my $level = $file[ scalar(@file) - 2 ];
341             unless ($error) {
342                 $systempreference .= "$file[scalar(@file)-1]|"
343                   unless (
344                     index( $systempreference, $file[ scalar(@file) - 1 ] ) >=
345                     0 );
346             }
347
348             #Bulding here a hierarchy to display files by level.
349             push @{ $hashlevel{$level} },
350               { "fwkname" => $file[ scalar(@file) - 1 ], "error" => $error };
351         }
352
353         #systempreference contains an ending |
354         chop $systempreference;
355         my @list;
356         map { push @list, { "level" => $_, "fwklist" => $hashlevel{$_} } }
357           keys %hashlevel;
358         my $fwk_language;
359         for my $each_language (@$all_languages) {
360
361             #           warn "CODE".$each_language->{'language_code'};
362             #           warn "LANG:".$lang;
363             if ( $lang eq $each_language->{'language_code'} ) {
364                 $fwk_language = $each_language->{language_locale_name};
365             }
366         }
367         my $updateflag =
368           $dbh->do(
369             "UPDATE systempreferences set value=\"$systempreference\" where variable='FrameworksLoaded'"
370           );
371         unless ( $updateflag == 1 ) {
372             my $string =
373                 "INSERT INTO systempreferences (value, variable, explanation, type) VALUES (\"$systempreference\",'FrameworksLoaded','Frameworks loaded through webinstaller','choice')";
374             my $rq = $dbh->prepare($string);
375             $rq->execute;
376         }
377         $template->param(
378             "fwklanguage" => $fwk_language,
379             "list"        => \@list
380         );
381         $template->param( "$op" => 1 );
382         if ( $info{dbms} eq 'mysql' ) { $dbh->do('SET FOREIGN_KEY_CHECKS=1'); }
383         elsif ( $info{dbms} eq 'Pg' ) { $dbh->do('SET CONSTRAINTS ALL IMMEDIATE;'); }
384     }
385     elsif ( $op && $op eq 'selectframeworks' ) {
386         #
387         #
388         # 1ST install, 2nd sub-step : show the user the sql datas he can insert in the database.
389         #
390         #
391         # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
392         
393         #Framework Selection
394         #sql data for import are supposed to be located in installer/data/<language>/<level>
395         # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
396         # Where <level> is a category of requirement : required, recommended optional
397         # level should contain :
398         #   SQL File for import With a readable name.
399         #   txt File taht explains what this SQL File is meant for.
400         # Could be VERY useful to have A Big file for a kind of library.
401         # But could also be useful to have some Authorised values data set prepared here.
402         # Framework Selection is achieved through checking boxes.
403         my $langchoice = $query->param('fwklanguage');
404         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
405         my $marcflavour = $query->param('marcflavour');
406         if ($marcflavour){
407             # we can have some variants of marc flavour, by having different directories, like : unimarc_small and unimarc_full, for small and complete unimarc frameworks.
408             # marc_cleaned finds the marcflavour, without the variant.
409             my $marc_cleaned = 'MARC21';
410             $marc_cleaned = 'UNIMARC' if $marcflavour =~ /unimarc/;
411           my $request =
412             $dbh->prepare(
413               "INSERT IGNORE INTO `systempreferences` (variable,value,explanation,options,type) VALUES('marcflavour','$marc_cleaned','Define global MARC flavor (MARC21 or UNIMARC) used for character encoding','MARC21|UNIMARC','Choice');"
414             );     
415           $request->execute;
416         };    
417         $marcflavour = C4::Context->preference('marcflavour') unless ($marcflavour);
418         #Insert into database the selected marcflavour
419     
420         undef $/;
421         my $dir =
422           C4::Context->config('intranetdir') . "/installer/data/$info{dbms}/$langchoice/marcflavour/".lc($marcflavour);
423         opendir( MYDIR, $dir ) || warn "no open $dir";
424         my @listdir = sort grep { !/^\.|marcflavour/ && -d "$dir/$_" } readdir(MYDIR);
425         closedir MYDIR;
426                   
427         my @fwklist;
428         my $request =
429           $dbh->prepare(
430             "SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'"
431           );
432         $request->execute;
433         my ($frameworksloaded) = $request->fetchrow;
434         my %frameworksloaded;
435         foreach ( split( /\|/, $frameworksloaded ) ) {
436             $frameworksloaded{$_} = 1;
437         }
438         
439         foreach my $requirelevel (@listdir) {
440             opendir( MYDIR, "$dir/$requirelevel" );
441             my @listname =
442               grep { !/^\./ && -f "$dir/$requirelevel/$_" && $_ =~ m/\.sql$/ }
443               readdir(MYDIR);
444             closedir MYDIR;
445             my %cell;
446             my @frameworklist;
447             map {
448                 my $name = substr( $_, 0, -4 );
449                 open FILE, "< $dir/$requirelevel/$name.txt";
450                 my $lines = <FILE>;
451                 $lines =~ s/\n|\r/<br \/>/g;
452                 use utf8;
453                 utf8::encode($lines) unless ( utf8::is_utf8($lines) );
454                 push @frameworklist,
455                   {
456                     'fwkname'        => $name,
457                     'fwkfile'        => "$dir/$requirelevel/$_",
458                     'fwkdescription' => $lines,
459                     'checked'        => (
460                         (
461                             $frameworksloaded{$_}
462                               || ( $requirelevel =~
463                                 /(mandatory|requi|oblig|necess)/i )
464                         ) ? 1 : 0
465                     )
466                   };
467             } @listname;
468             my @fwks =
469               sort { $a->{'fwkname'} lt $b->{'fwkname'} } @frameworklist;
470
471 #             $cell{"mandatory"}=($requirelevel=~/(mandatory|requi|oblig|necess)/i);
472             $cell{"frameworks"} = \@fwks;
473             $cell{"label"}      = ucfirst($requirelevel);
474             $cell{"code"}       = lc($requirelevel);
475             push @fwklist, \%cell;
476         }
477         $template->param( "frameworksloop" => \@fwklist );
478         $template->param( "marcflavour" => ucfirst($marcflavour));
479         
480         $dir =
481           C4::Context->config('intranetdir') . "/installer/data/$info{dbms}/$langchoice";
482         opendir( MYDIR, $dir ) || warn "no open $dir";
483         @listdir = sort grep { !/^\.|marcflavour/ && -d "$dir/$_" } readdir(MYDIR);
484         closedir MYDIR;
485         my @levellist;
486         foreach my $requirelevel (@listdir) {
487             opendir( MYDIR, "$dir/$requirelevel" );
488             my @listname =
489               grep { !/^\./ && -f "$dir/$requirelevel/$_" && $_ =~ m/\.sql$/ }
490               readdir(MYDIR);
491             closedir MYDIR;
492             my %cell;
493             my @frameworklist;
494             map {
495                 my $name = substr( $_, 0, -4 );
496                 open FILE, "< $dir/$requirelevel/$name.txt";
497                 my $lines = <FILE>;
498                 $lines =~ s/\n|\r/<br \/>/g;
499                 use utf8;
500                 utf8::encode($lines) unless ( utf8::is_utf8($lines) );
501                 push @frameworklist,
502                   {
503                     'fwkname'        => $name,
504                     'fwkfile'        => "$dir/$requirelevel/$_",
505                     'fwkdescription' => $lines,
506                     'checked'        => (
507                         (
508                             $frameworksloaded{$_}
509                               || ( $requirelevel =~
510                                 /(mandatory|requi|oblig|necess)/i )
511                         ) ? 1 : 0
512                     )
513                   };
514             } @listname;
515             my @fwks =
516               sort { $a->{'fwkname'} lt $b->{'fwkname'} } @frameworklist;
517
518 #             $cell{"mandatory"}=($requirelevel=~/(mandatory|requi|oblig|necess)/i);
519             $cell{"frameworks"} = \@fwks;
520             $cell{"label"}      = ucfirst($requirelevel);
521             $cell{"code"}       = lc($requirelevel);
522             push @levellist, \%cell;
523         }
524         $template->param( "levelloop" => \@levellist );
525         $template->param( "$op"       => 1 );
526     }
527     elsif ( $op && $op eq 'choosemarc' ) {
528         #
529         #
530         # 1ST install, 2nd sub-step : show the user the marcflavour available.
531         #
532         #
533         
534         #Choose Marc Flavour
535         #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
536         # Where <dbms> is database type according to DBD syntax
537         # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
538         # Where <level> is a category of requirement : required, recommended optional
539         # level should contain :
540         #   SQL File for import With a readable name.
541         #   txt File taht explains what this SQL File is meant for.
542         # Could be VERY useful to have A Big file for a kind of library.
543         # But could also be useful to have some Authorised values data set prepared here.
544         # Marcflavour Selection is achieved through radiobuttons.
545         my $langchoice = $query->param('fwklanguage');
546         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
547         my $dir =
548           C4::Context->config('intranetdir') . "/installer/data/$info{dbms}/$langchoice/marcflavour";
549         opendir( MYDIR, $dir ) || warn "no open $dir";
550         my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
551         closedir MYDIR;
552         my $marcflavour=C4::Context->preference("marcflavour");    
553         my @flavourlist;
554         foreach my $marc (@listdir) {
555             my %cell=(    
556             "label"=> ucfirst($marc),
557             "code"=>uc($marc),
558             "checked"=>uc($marc) eq $marcflavour);      
559 #             $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
560             push @flavourlist, \%cell;
561         }
562         $template->param( "flavourloop" => \@flavourlist );
563         $template->param( "$op"       => 1 );
564     }
565     elsif ( $op && $op eq 'importdatastructure' ) {
566         #
567         #
568         # 1st install, 1st "sub-step" : import kohastructure
569         #
570         #
571         my $datadir = C4::Context->config('intranetdir') . "/installer/data/$info{dbms}";
572         my $error;
573         if ( $info{dbms} eq 'mysql' ) {
574             my $strcmd = "mysql "
575                 . ( $info{hostname} ? " -h $info{hostname} " : "" )
576                 . ( $info{port}     ? " -P $info{port} "     : "" )
577                 . ( $info{user}     ? " -u $info{user} "     : "" )
578                 . ( $info{password} ? " -p$info{password}"   : "" )
579                 . " $info{dbname} ";
580             $error = qx($strcmd <$datadir/kohastructure.sql 2>&1 1>/dev/null);
581         }
582         elsif ( $info{dbms} eq 'Pg' ) { 
583             my $strcmd = "psql "
584                 . ( $info{hostname} ? " -h $info{hostname} " : "" )
585                 . ( $info{port}     ? " -p $info{port} "     : "" )
586                 . ( $info{user}     ? " -U $info{user} "     : "" )
587 #                . ( $info{password} ? " -W $info{password}"   : "" )           # psql will NOT accept a password, but prompts...
588                 . " $info{dbname} ";                                            # Therefore, be sure to run 'trust' on localhost in pg_hba.conf -fbcit
589             $error = qx($strcmd -f $datadir/kohastructure.sql 2>&1 1>/dev/null);# Be sure to set 'client_min_messages = error' in postgresql.conf
590                                                                                 # so that only true errors are returned to stderr or else the installer will
591                                                                                 # report the import a failure although it really succeded -fbcit
592         }
593         $template->param(
594             "error" => $error,
595             "$op"   => 1,
596         );
597     }
598     elsif ( $op && $op eq 'updatestructure' ) {
599         #
600         # Not 1st install, the only sub-step : update database
601         #
602         #Do updatedatabase And report
603         my $execstring =
604           C4::Context->config("intranetdir") . "/installer/data/$info{dbms}/updatedatabase.pl";
605         undef $/;
606         my $string = qx($execstring 2>&1 1>/dev/null);                          # added '1>/dev/null' to return only stderr in $string. Needs testing here. -fbcit
607         if ($string) {
608             $string =~ s/\n|\r/<br \/>/g;
609             $string =~
610                 s/(DBD::mysql.*? failed: .*? line [0-9]*.|=================.*?====================)/<font color=red>$1<\/font>/g;
611             $template->param( "updatereport" => $string );
612         }
613         $template->param( $op => 1 );
614     }
615     else {
616         #
617         # check wether it's a 1st install or an update
618         #
619         #Check if there are enough tables.
620         # Paul has cleaned up tables so reduced the count
621         #I put it there because it implied a data import if condition was not satisfied.
622         my $dbh = DBI->connect(
623                 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
624                 . ( $info{port} ? ";port=$info{port}" : "" ),
625                 $info{'user'}, $info{'password'}
626         );
627         my $rq;
628         if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare( "SHOW TABLES FROM " . $info{'dbname'} ); }
629         elsif ( $info{dbms} eq 'Pg' ) { $rq = $dbh->prepare( "SELECT *
630                                                                 FROM information_schema.tables
631                                                                 WHERE table_schema='public' and table_type='BASE TABLE';" ); }
632         $rq->execute;
633         my $data = $rq->fetchall_arrayref( {} );
634         my $count = scalar(@$data);
635         #
636         # we don't have tables, propose DB import
637         #
638         if ( $count < 70 ) {
639             $template->param( "count" => $count, "proposeimport" => 1 );
640         }
641         else {
642             #
643             # we have tables, propose to select files to upload or updatedatabase
644             #
645             $template->param( "count" => $count, "default" => 1 );
646             #
647             # 1st part of step 3 : check if there is a databaseversion systempreference
648             # if there is, then we just need to upgrade
649             # if there is none, then we need to install the database
650             #
651             if (C4::Context->preference('Version')) {
652                 my $dbversion = C4::Context->preference('Version');
653                 $dbversion =~ /(.*)\.(..)(..)(...)/;
654                 $dbversion = "$1.$2.$3.$4";
655                 $template->param("upgrading" => 1,
656                                 "dbversion" => $dbversion,
657                                 "kohaversion" => C4::Context->KOHAVERSION,
658                                 );
659             }
660         }
661
662         $dbh->disconnect;
663     }
664 }
665 else {
666
667     # LANGUAGE SELECTION page by default
668     # using opendir + language Hash
669
670     my $langavail = getTranslatedLanguages();
671
672     my @languages;
673     foreach (@$langavail) {
674         push @languages,
675           {
676             'value'       => $_->{'language_code'},
677             'description' => $_->{'language_name'}
678           }
679           if ( $_->{'language_code'} );
680     }
681     $template->param( languages => \@languages );
682     if ($dbh) {
683         my $rq =
684           $dbh->prepare(
685             "SELECT * from systempreferences WHERE variable='Version'");
686         if ( $rq->execute ) {
687             my ($version) = $rq->fetchrow;
688             if ($version) {
689                 $query->redirect("install.pl?step=3");
690             }
691         }
692     }
693 }
694 output_html_with_http_headers $query, $cookie, $template->output;