FIX for 1298 : removing hardcoded calls to mySQL, Perl, zebra & yaz-client
[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{'hostname'}, $info{'port'} ) = ( $1, $2 )
44   if $info{'hostname'} =~ /([^:]*):([0-9]+)/;
45 $info{'user'}     = C4::Context->config("user");
46 $info{'password'} = C4::Context->config("pass");
47 my $dbh = DBI->connect(
48     "DBI:$info{dbms}:$info{dbname}:$info{hostname}"
49       . ( $info{port} ? ":$info{port}" : "" ),
50     $info{'user'}, $info{'password'}
51 );
52
53 if ( $step && $step == 1 ) {
54     #First Step
55     #Checking ALL perl Modules and services needed are installed.
56     #Whenever there is an error, adding a report to the page
57     $template->param( language => 1 );
58     my $problem;
59
60     unless ( $] >= 5.006001 ) {    # Bug 179
61         $template->param( "problems" => 1, "perlversion" => 1 );
62         $problem = 1;
63     }
64
65     # We could here use a special find
66     my @missing = ();
67     unless ( eval { require ZOOM } ) {
68         push @missing, { name => "ZOOM" };
69     }
70     unless ( eval { require LWP::Simple } ) {
71         push @missing, { name => "LWP::Simple" };
72     }
73     unless ( eval { require XML::Simple } ) {
74         push @missing, { name => "XML::Simple" };
75     }
76     unless ( eval { require MARC::File::XML } ) {
77         push @missing, { name => "MARC::File::XML" };
78     }
79     unless ( eval { require MARC::File::USMARC } ) {
80         push @missing, { name => "MARC::File::USMARC" };
81     }
82     unless ( eval { require DBI } ) {
83         push @missing, { name => "DBI" };
84     }
85     unless ( eval { require Date::Manip } ) {
86         push @missing, { name => "Date::Manip" };
87     }
88     unless ( eval { require DBD::mysql } ) {
89         push @missing, { name => "DBD::mysql" };
90     }
91     unless ( eval { require HTML::Template } ) {
92         push @missing, { name => "HTML::Template::Pro" };
93     }
94     unless ( eval { require HTML::Template } ) {
95         push @missing, { name => "Date::Calc" };
96     }
97     unless ( eval { require Digest::MD5 } ) {
98         push @missing, { name => "Digest::MD5" };
99     }
100     unless ( eval { require MARC::Record } ) {
101         push @missing, { name => "MARC::Record" };
102     }
103     unless ( eval { require Mail::Sendmail } ) {
104         push @missing, { name => "Mail::Sendmail", usagemail => 1 };
105     }
106     unless ( eval { require List::MoreUtils } ) {
107         push @missing, { name => "List::MoreUtils" };
108     }
109     unless ( eval { require XML::RSS } ) {
110         push @missing, { name => "XML::RSS" };
111     }
112
113 # The following modules are not mandatory, depends on how the library want to use Koha
114     unless ( eval { require PDF::API2 } ) {
115         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
116             push @missing, { name => "PDF::API2", usagebarcode => 1 };
117         }
118     }
119     unless ( eval { require GD::Barcorde } ) {
120         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
121             push @missing,
122               { name => "GD::Barcode", usagebarcode => 1, usagespine => 1 };
123         }
124     }
125     unless ( eval { require Data::Random } ) {
126         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
127             push @missing, { name => "Data::Random", usagebarcode => 1 };
128         }
129     }
130     unless ( eval { require PDF::Reuse::Barcode } ) {
131         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
132             push @missing, { name => "PDF::Reuse::Barcode", usagebarcode => 1 };
133         }
134     }
135     unless ( eval { require PDF::Report } ) {
136         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
137             push @missing, { name => "PDF::Report", usagebarcode => 1 };
138         }
139     }
140     unless ( eval { require Net::LDAP } ) {
141         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
142             push @missing, { name => "Algorithm::CheckDigits", usagebarcode => 1 };
143         }
144     }
145     unless ( eval { require GD::Barcode::UPCE } ) {
146         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
147             push @missing, { name => "GD::Barcode::UPCE", usagepine => 1 };
148         }
149     }
150     unless ( eval { require Net::LDAP } ) {
151         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
152             push @missing, { name => "Net::LDAP", usageLDAP => 1 };
153         }
154     }
155     $template->param( missings => \@missing ) if ( scalar(@missing) > 0 );
156     $template->param( 'checkmodule' => 1 )
157       unless ( scalar(@missing) && $problem );
158
159 }
160 elsif ( $step && $step == 2 ) {
161 #
162 #STEP 2 Check Database conn~ection and access
163 #
164     $template->param(%info);
165     my $checkmysql = $query->param("checkmysql");
166     $template->param( 'mysqlconnection' => $checkmysql );
167     if ($checkmysql) {
168         if ($dbh) {
169
170             # Can connect to the mysql
171             $template->param( "checkdatabaseaccess" => 1 );
172             if ( $info{dbms} eq "mysql" ) {
173
174                 #Check if database created
175                 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
176                 if ( $rv == 1 ) {
177                     $template->param( 'checkdatabasecreated' => 1 );
178                 }
179
180                 #Check if user have all necessary grants on this database.
181                 my $rq =
182                   $dbh->prepare(
183                     "SHOW GRANTS FOR \'$info{user}\'\@'$info{hostname}'");
184                 $rq->execute;
185                 my $grantaccess;
186                 while ( my ($line) = $rq->fetchrow ) {
187                     my $dbname = $info{dbname};
188                     if ( $line =~ m/$dbname/ || index( $line, '*.*' ) > 0 ) {
189                         $grantaccess = 1
190                           if (
191                             index( $line, 'ALL PRIVILEGES' ) > 0
192                             || (   ( index( $line, 'SELECT' ) > 0 )
193                                 && ( index( $line, 'INSERT' ) > 0 )
194                                 && ( index( $line, 'UPDATE' ) > 0 )
195                                 && ( index( $line, 'DELETE' ) > 0 )
196                                 && ( index( $line, 'CREATE' ) > 0 )
197                                 && ( index( $line, 'DROP' ) > 0 ) )
198                           );
199                     }
200                 }
201                 unless ($grantaccess) {
202                     $rq =
203                       $dbh->prepare("SHOW GRANTS FOR \'$info{user}\'\@'\%'");
204                     $rq->execute;
205                     while ( my ($line) = $rq->fetchrow ) {
206                         my $dbname = $info{dbname};
207                         if ( $line =~ m/$dbname/ || index( $line, '*.*' ) > 0 )
208                         {
209                             $grantaccess = 1
210                               if (
211                                 index( $line, 'ALL PRIVILEGES' ) > 0
212                                 || (   ( index( $line, 'SELECT' ) > 0 )
213                                     && ( index( $line, 'INSERT' ) > 0 )
214                                     && ( index( $line, 'UPDATE' ) > 0 )
215                                     && ( index( $line, 'DELETE' ) > 0 )
216                                     && ( index( $line, 'CREATE' ) > 0 )
217                                     && ( index( $line, 'DROP' ) > 0 ) )
218                               );
219                         }
220                     }
221                 }
222                 $template->param( "checkgrantaccess" => $grantaccess );
223             }
224         }
225         else {
226             $template->param( "error" => DBI::err, "message" => DBI::errstr );
227         }
228     }
229 }
230 elsif ( $step && $step == 3 ) {
231 #
232 #
233 # STEP 3 : database setup
234 #
235
236     my $op = $query->param('op');
237     if ( $op && $op eq 'finish' ) {
238     my $kohaversion=C4::Context::KOHAVERSION;
239     # remove the 3 last . to have a Perl number
240     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
241     if (C4::Context->preference('Version')) {
242         warn "UPDATE Version";
243       my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
244       $finish->execute($kohaversion);
245     } else {
246         warn "INSERT Version";
247       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')");
248       $finish->execute($kohaversion);
249     }
250
251   # Installation is finished.
252   # We just deny anybody acess to install
253   # And we redirect people to mainpage.
254   # The installer wil have to relogin since we donot pass cookie to redirection.
255         $template->param( "$op" => 1 );
256     }
257     elsif ( $op && $op eq 'finished' ) {
258     #
259     #
260     # we have finished, just redirect to mainpage.
261     #
262     #
263         print $query->redirect("/cgi-bin/koha/mainpage.pl");
264         exit 1;
265     }
266     elsif ( $op && $op eq 'addframeworks' ) {
267     #
268     # 1ST install : insert the SQL files the user has selected
269     #
270
271         #Framework importing and reports
272         my $lang;
273         my %hashlevel;
274
275        # sort by filename -> prepend with numbers to specify order of insertion.
276         my @fnames = sort {
277             my @aa = split /\/|\\/, ($a);
278             my @bb = split /\/|\\/, ($b);
279             $aa[-1] lt $bb[-1]
280         } $query->param('framework');
281         $dbh->do('SET FOREIGN_KEY_CHECKS=0');
282         my $request =
283           $dbh->prepare(
284 "SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'"
285           );
286         $request->execute;
287         my ($systempreference) = $request->fetchrow;
288         foreach my $file (@fnames) {
289
290             #      warn $file;
291             undef $/;
292             my $strcmd = "mysql "
293               . ( $info{hostname} ? " -h $info{hostname} " : "" )
294               . ( $info{port}     ? " -P $info{port} "     : "" )
295               . ( $info{user}     ? " -u $info{user} "     : "" )
296               . ( $info{password} ? " -p$info{password}"   : "" )
297               . " $info{dbname} ";
298             my $error = qx($strcmd < $file 2>&1);
299             my @file = split qr(\/|\\), $file;
300             $lang = $file[ scalar(@file) - 3 ] unless ($lang);
301             my $level = $file[ scalar(@file) - 2 ];
302             unless ($error) {
303                 $systempreference .= "$file[scalar(@file)-1]|"
304                   unless (
305                     index( $systempreference, $file[ scalar(@file) - 1 ] ) >=
306                     0 );
307             }
308
309             #Bulding here a hierarchy to display files by level.
310             push @{ $hashlevel{$level} },
311               { "fwkname" => $file[ scalar(@file) - 1 ], "error" => $error };
312         }
313
314         #systempreference contains an ending |
315         chop $systempreference;
316         my @list;
317         map { push @list, { "level" => $_, "fwklist" => $hashlevel{$_} } }
318           keys %hashlevel;
319         my $fwk_language;
320         for my $each_language (@$all_languages) {
321
322             #           warn "CODE".$each_language->{'language_code'};
323             #           warn "LANG:".$lang;
324             if ( $lang eq $each_language->{'language_code'} ) {
325                 $fwk_language = $each_language->{language_locale_name};
326             }
327         }
328         my $updateflag =
329           $dbh->do(
330 "UPDATE systempreferences set value=\"$systempreference\" where variable='FrameworksLoaded'"
331           );
332         unless ( $updateflag == 1 ) {
333             my $string =
334 "INSERT INTO systempreferences (value, variable, explanation, type) VALUES (\"$systempreference\",'FrameworksLoaded','Frameworks loaded through webinstaller','choice')";
335             my $rq = $dbh->prepare($string);
336             $rq->execute;
337         }
338         $template->param(
339             "fwklanguage" => $fwk_language,
340             "list"        => \@list
341         );
342         $template->param( "$op" => 1 );
343         $dbh->do('SET FOREIGN_KEY_CHECKS=1');
344     }
345     elsif ( $op && $op eq 'selectframeworks' ) {
346 #
347 #
348 # 1ST install : show the user the sql datas he can insert in the database.
349 #
350 #
351 # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
352
353 #Framework Selection
354 #sql data for import are supposed to be located in installer/data/<language>/<level>
355 # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
356 # Where <level> is a category of requirement : required, recommended optional
357 # level should contain :
358 #   SQL File for import With a readable name.
359 #   txt File taht explains what this SQL File is meant for.
360 # Could be VERY useful to have A Big file for a kind of library.
361 # But could also be useful to have some Authorised values data set prepared here.
362 # Framework Selection is achieved through checking boxes.
363         my $langchoice = $query->param('fwklanguage');
364         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
365         my $dir = C4::Context->config('intranetdir') . "/installer/data/";
366         opendir( MYDIR, $dir );
367         my @listdir = grep { !/^\.|CVS/ && -d "$dir/$_" } readdir(MYDIR);
368         closedir MYDIR;
369         my $frmwklangs = getFrameworkLanguages();
370         my @languages;
371         map {
372             push @languages,
373               {
374                 'dirname'             => $_->{'language_code'},
375                 'languagedescription' => $_->{'language_name'},
376                 'checked' => ( $_->{'language_code'} eq $langchoice )
377               }
378               if ( $_->{'language_code'} );
379         } @$frmwklangs;
380         $template->param( "languagelist" => \@languages );
381         undef $/;
382         $dir =
383           C4::Context->config('intranetdir') . "/installer/data/$langchoice";
384         opendir( MYDIR, $dir ) || warn "no open $dir";
385         @listdir = grep { !/^\.|CVS/ && -d "$dir/$_" } readdir(MYDIR);
386         closedir MYDIR;
387         my @levellist;
388         my $request =
389           $dbh->prepare(
390 "SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'"
391           );
392         $request->execute;
393         my ($frameworksloaded) = $request->fetchrow;
394         my %frameworksloaded;
395
396         foreach ( split( /\|/, $frameworksloaded ) ) {
397             $frameworksloaded{$_} = 1;
398         }
399         foreach my $requirelevel (@listdir) {
400             $dir =
401               C4::Context->config('intranetdir')
402               . "/installer/data/$langchoice/$requirelevel";
403             opendir( MYDIR, $dir );
404             my @listname =
405               grep { !/^\.|CVS/ && -f "$dir/$_" && $_ =~ m/\.sql$/ }
406               readdir(MYDIR);
407             closedir MYDIR;
408             my %cell;
409             my @frameworklist;
410             map {
411                 my $name = substr( $_, 0, -4 );
412                 open FILE, "< $dir/$name.txt";
413                 my $lines = <FILE>;
414                 $lines =~ s/\n|\r/<br \/>/g;
415                 use utf8;
416                 utf8::encode($lines) unless ( utf8::is_utf8($lines) );
417                 push @frameworklist,
418                   {
419                     'fwkname'        => $name,
420                     'fwkfile'        => "$dir/$_",
421                     'fwkdescription' => $lines,
422                     'checked'        => (
423                         (
424                             $frameworksloaded{$_}
425                               || ( $requirelevel =~
426                                 /(mandatory|requi|oblig|necess)/i )
427                         ) ? 1 : 0
428                     )
429                   };
430             } @listname;
431             my @fwks =
432               sort { $a->{'fwkname'} lt $b->{'fwkname'} } @frameworklist;
433
434   #       $cell{"mandatory"}=($requirelevel=~/(mandatory|requi|oblig|necess)/i);
435             $cell{"frameworks"} = \@fwks;
436             $cell{"label"}      = ucfirst($requirelevel);
437             $cell{"code"}       = lc($requirelevel);
438             push @levellist, \%cell;
439         }
440         $template->param( "levelloop" => \@levellist );
441         $template->param( "$op"       => 1 );
442     }
443     elsif ( $op && $op eq 'updatestructure' ) {
444
445         #Do updatedatabase And report
446         my $execstring =
447           C4::Context->config("intranetdir") . "/updater/updatedatabase";
448         undef $/;
449         my $string = qx|$execstring 2>&1|;
450         if ($string) {
451             $string =~ s/\n|\r/<br \/>/g;
452             $string =~
453 s/(DBD::mysql.*? failed: .*? line [0-9]*.|=================.*?====================)/<font color=red>$1<\/font>/g;
454             $template->param( "updatereport" => $string );
455         }
456         $template->param( $op => 1 );
457     }
458     elsif ( $op && $op eq 'importdatastructure' ) {
459     #
460     #
461     # UPDATE (not 1st install) run updatedatabase
462     #
463     #
464
465         #Import data structure and show errors if any
466         #Uses DBI to read the file [MJR 2007-07-01]
467         my $dbh = DBI->connect(
468             "DBI:$info{dbms}:$info{dbname}:$info{hostname}"
469               . ( $info{port} ? ":$info{port}" : "" ),
470             $info{'user'}, $info{'password'}
471         );
472         open( INPUT, "<kohastructure.sql" );
473         my $file = do { local $/ = undef; <INPUT> };
474         my @commands = split( /;/, $file );
475         pop @commands;
476         map { $dbh->do($_) } @commands;
477         close(INPUT);
478         $template->param(
479             "error" => $dbh->errstr,
480             "$op"   => 1,
481         );
482         $dbh->disconnect;
483     }
484     else {
485
486 #Check if there are enough tables.
487 # Paul has cleaned up tables so reduced the count
488 #I put it there because it implied a data import if condition was not satisfied.
489         my $dbh = DBI->connect(
490             "DBI:$info{dbms}:$info{dbname}:$info{hostname}"
491               . ( $info{port} ? ":$info{port}" : "" ),
492             $info{'user'}, $info{'password'}
493         );
494         my $rq = $dbh->prepare( "SHOW TABLES FROM " . $info{'dbname'} );
495         $rq->execute;
496         my $data = $rq->fetchall_arrayref( {} );
497         my $count = scalar(@$data);
498         #
499         # we don't have tables, propose DB import
500         #
501         if ( $count < 70 ) {
502             $template->param( "count" => $count, "proposeimport" => 1 );
503         }
504         else {
505             #
506             # we have tables, propose to select files to upload or updatedatabase
507             #
508             $template->param( "count" => $count, "default" => 1 );
509             #
510             # 1st part of step 3 : check if there is a databaseversion systempreference
511             # if there is, then we just need to upgrade
512             # if there is none, then we need to install the database
513             #
514             my $dbversion = C4::Context->preference('Version');
515             $dbversion =~ /(.*)\.(..)(..)(...)/;
516             $dbversion = "$1.$2.$3.$4";
517             if (C4::Context->preference('Version')) {
518                 $template->param("upgrading" => 1,
519                                 "dbversion" => $dbversion,
520                                 "kohaversion" => C4::Context->KOHAVERSION,
521                                 );
522             }
523         }
524
525         $dbh->disconnect;
526     }
527 }
528 else {
529
530     # LANGUAGE SELECTION page by default
531     # using opendir + language Hash
532
533     my $langavail = getTranslatedLanguages();
534
535     my @languages;
536     foreach (@$langavail) {
537         push @languages,
538           {
539             'value'       => $_->{'language_code'},
540             'description' => $_->{'language_name'}
541           }
542           if ( $_->{'language_code'} );
543     }
544     $template->param( languages => \@languages );
545     if ($dbh) {
546         my $rq =
547           $dbh->prepare(
548             "SELECT * from systempreferences WHERE variable='Version'");
549         if ( $rq->execute ) {
550             my ($version) = $rq->fetchrow;
551             if ($version) {
552                 $query->redirect("install.pl?step=3");
553             }
554         }
555     }
556 }
557 output_html_with_http_headers $query, $cookie, $template->output;