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