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