Sorting the install directory
[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 'finished' ) {
242         #
243         # we have finished, just redirect to mainpage.
244         #
245         print $query->redirect("/cgi-bin/koha/mainpage.pl");
246         exit 1;
247     }
248     elsif ( $op && $op eq 'finish' ) {
249         my $kohaversion=C4::Context::KOHAVERSION;
250         # remove the 3 last . to have a Perl number
251         $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
252         if (C4::Context->preference('Version')) {
253             warn "UPDATE Version";
254             my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'");
255             $finish->execute($kohaversion);
256         } else {
257             warn "INSERT Version";
258             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')");
259             $finish->execute($kohaversion);
260         }
261
262         # Installation is finished.
263         # We just deny anybody acess to install
264         # And we redirect people to mainpage.
265         # The installer wil have to relogin since we donot pass cookie to redirection.
266         $template->param( "$op" => 1 );
267     }
268     elsif ( $op && $op eq 'Nozebra' ) {
269         if ($query->param('Nozebra')) {
270             $dbh->do("UPDATE systempreferences SET value=1 WHERE variable='NoZebra'");
271         } else {
272             $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='NoZebra'");
273         }
274         $template->param( "$op" => 1 );
275     }
276     elsif ( $op && $op eq 'addframeworks' ) {
277     #
278     # 1ST install, 3rd sub-step : insert the SQL files the user has selected
279     #
280
281         #Framework importing and reports
282         my $lang;
283         my %hashlevel;
284
285        # sort by filename -> prepend with numbers to specify order of insertion.
286         my @fnames = sort {
287             my @aa = split /\/|\\/, ($a);
288             my @bb = split /\/|\\/, ($b);
289             $aa[-1] lt $bb[-1]
290         } $query->param('framework');
291         $dbh->do('SET FOREIGN_KEY_CHECKS=0');
292         my $request =
293           $dbh->prepare(
294             "SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'"
295           );
296         $request->execute;
297         my ($systempreference) = $request->fetchrow;
298         foreach my $file (@fnames) {
299
300             #      warn $file;
301             undef $/;
302             my $strcmd = "mysql "
303               . ( $info{hostname} ? " -h $info{hostname} " : "" )
304               . ( $info{port}     ? " -P $info{port} "     : "" )
305               . ( $info{user}     ? " -u $info{user} "     : "" )
306               . ( $info{password} ? " -p$info{password}"   : "" )
307               . " $info{dbname} ";
308             my $error = qx($strcmd < $file 2>&1);
309             my @file = split qr(\/|\\), $file;
310             $lang = $file[ scalar(@file) - 3 ] unless ($lang);
311             my $level = $file[ scalar(@file) - 2 ];
312             unless ($error) {
313                 $systempreference .= "$file[scalar(@file)-1]|"
314                   unless (
315                     index( $systempreference, $file[ scalar(@file) - 1 ] ) >=
316                     0 );
317             }
318
319             #Bulding here a hierarchy to display files by level.
320             push @{ $hashlevel{$level} },
321               { "fwkname" => $file[ scalar(@file) - 1 ], "error" => $error };
322         }
323
324         #systempreference contains an ending |
325         chop $systempreference;
326         my @list;
327         map { push @list, { "level" => $_, "fwklist" => $hashlevel{$_} } }
328           keys %hashlevel;
329         my $fwk_language;
330         for my $each_language (@$all_languages) {
331
332             #           warn "CODE".$each_language->{'language_code'};
333             #           warn "LANG:".$lang;
334             if ( $lang eq $each_language->{'language_code'} ) {
335                 $fwk_language = $each_language->{language_locale_name};
336             }
337         }
338         my $updateflag =
339           $dbh->do(
340             "UPDATE systempreferences set value=\"$systempreference\" where variable='FrameworksLoaded'"
341           );
342         unless ( $updateflag == 1 ) {
343             my $string =
344                 "INSERT INTO systempreferences (value, variable, explanation, type) VALUES (\"$systempreference\",'FrameworksLoaded','Frameworks loaded through webinstaller','choice')";
345             my $rq = $dbh->prepare($string);
346             $rq->execute;
347         }
348         $template->param(
349             "fwklanguage" => $fwk_language,
350             "list"        => \@list
351         );
352         $template->param( "$op" => 1 );
353         $dbh->do('SET FOREIGN_KEY_CHECKS=1');
354     }
355     elsif ( $op && $op eq 'selectframeworks' ) {
356         #
357         #
358         # 1ST install, 2nd sub-step : show the user the sql datas he can insert in the database.
359         #
360         #
361         # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
362         
363         #Framework Selection
364         #sql data for import are supposed to be located in installer/data/<language>/<level>
365         # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
366         # Where <level> is a category of requirement : required, recommended optional
367         # level should contain :
368         #   SQL File for import With a readable name.
369         #   txt File taht explains what this SQL File is meant for.
370         # Could be VERY useful to have A Big file for a kind of library.
371         # But could also be useful to have some Authorised values data set prepared here.
372         # Framework Selection is achieved through checking boxes.
373         my $langchoice = $query->param('fwklanguage');
374         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
375         my $dir = C4::Context->config('intranetdir') . "/installer/data/";
376         opendir( MYDIR, $dir );
377         my @listdir = grep { !/^\.|CVS/ && -d "$dir/$_" } readdir(MYDIR);
378         closedir MYDIR;
379         my $frmwklangs = getFrameworkLanguages();
380         my @languages;
381         map {
382             push @languages,
383               {
384                 'dirname'             => $_->{'language_code'},
385                 'languagedescription' => $_->{'language_name'},
386                 'checked' => ( $_->{'language_code'} eq $langchoice )
387               }
388               if ( $_->{'language_code'} );
389         } @$frmwklangs;
390         $template->param( "languagelist" => \@languages );
391         undef $/;
392         $dir =
393           C4::Context->config('intranetdir') . "/installer/data/$langchoice";
394         opendir( MYDIR, $dir ) || warn "no open $dir";
395         @listdir = sort grep { !/^\.|CVS/ && -d "$dir/$_" } readdir(MYDIR);
396         closedir MYDIR;
397         my @levellist;
398         my $request =
399           $dbh->prepare(
400             "SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'"
401           );
402         $request->execute;
403         my ($frameworksloaded) = $request->fetchrow;
404         my %frameworksloaded;
405
406         foreach ( split( /\|/, $frameworksloaded ) ) {
407             $frameworksloaded{$_} = 1;
408         }
409         foreach my $requirelevel (@listdir) {
410             $dir =
411               C4::Context->config('intranetdir')
412               . "/installer/data/$langchoice/$requirelevel";
413             opendir( MYDIR, $dir );
414             my @listname =
415               grep { !/^\.|CVS/ && -f "$dir/$_" && $_ =~ m/\.sql$/ }
416               readdir(MYDIR);
417             closedir MYDIR;
418             my %cell;
419             my @frameworklist;
420             map {
421                 my $name = substr( $_, 0, -4 );
422                 open FILE, "< $dir/$name.txt";
423                 my $lines = <FILE>;
424                 $lines =~ s/\n|\r/<br \/>/g;
425                 use utf8;
426                 utf8::encode($lines) unless ( utf8::is_utf8($lines) );
427                 push @frameworklist,
428                   {
429                     'fwkname'        => $name,
430                     'fwkfile'        => "$dir/$_",
431                     'fwkdescription' => $lines,
432                     'checked'        => (
433                         (
434                             $frameworksloaded{$_}
435                               || ( $requirelevel =~
436                                 /(mandatory|requi|oblig|necess)/i )
437                         ) ? 1 : 0
438                     )
439                   };
440             } @listname;
441             my @fwks =
442               sort { $a->{'fwkname'} lt $b->{'fwkname'} } @frameworklist;
443
444   #       $cell{"mandatory"}=($requirelevel=~/(mandatory|requi|oblig|necess)/i);
445             $cell{"frameworks"} = \@fwks;
446             $cell{"label"}      = ucfirst($requirelevel);
447             $cell{"code"}       = lc($requirelevel);
448             push @levellist, \%cell;
449         }
450         $template->param( "levelloop" => \@levellist );
451         $template->param( "$op"       => 1 );
452     }
453     elsif ( $op && $op eq 'importdatastructure' ) {
454         #
455         #
456         # 1st install, 1st "sub-step" : import kohastructure
457         #
458         #
459         my $dbh = DBI->connect(
460             "DBI:$info{dbms}:$info{dbname}:$info{hostname}"
461               . ( $info{port} ? ":$info{port}" : "" ),
462             $info{'user'}, $info{'password'}
463         );
464         open( INPUT, "<kohastructure.sql" );
465         my $file = do { local $/ = undef; <INPUT> };
466         my @commands = split( /;/, $file );
467         pop @commands;
468         map { $dbh->do($_) } @commands;
469         close(INPUT);
470         $template->param(
471             "error" => $dbh->errstr,
472             "$op"   => 1,
473         );
474         $dbh->disconnect;
475     }
476     elsif ( $op && $op eq 'updatestructure' ) {
477         #
478         # Not 1st install, the only sub-step : update database
479         #
480         #Do updatedatabase And report
481         my $execstring =
482           C4::Context->config("intranetdir") . "/updater/updatedatabase";
483         undef $/;
484         my $string = qx|$execstring 2>&1|;
485         if ($string) {
486             $string =~ s/\n|\r/<br \/>/g;
487             $string =~
488                 s/(DBD::mysql.*? failed: .*? line [0-9]*.|=================.*?====================)/<font color=red>$1<\/font>/g;
489             $template->param( "updatereport" => $string );
490         }
491         $template->param( $op => 1 );
492     }
493     else {
494         #
495         # check wether it's a 1st install or an update
496         #
497         #Check if there are enough tables.
498         # Paul has cleaned up tables so reduced the count
499         #I put it there because it implied a data import if condition was not satisfied.
500         my $dbh = DBI->connect(
501             "DBI:$info{dbms}:$info{dbname}:$info{hostname}"
502               . ( $info{port} ? ":$info{port}" : "" ),
503             $info{'user'}, $info{'password'}
504         );
505         my $rq = $dbh->prepare( "SHOW TABLES FROM " . $info{'dbname'} );
506         $rq->execute;
507         my $data = $rq->fetchall_arrayref( {} );
508         my $count = scalar(@$data);
509         #
510         # we don't have tables, propose DB import
511         #
512         if ( $count < 70 ) {
513             $template->param( "count" => $count, "proposeimport" => 1 );
514         }
515         else {
516             #
517             # we have tables, propose to select files to upload or updatedatabase
518             #
519             $template->param( "count" => $count, "default" => 1 );
520             #
521             # 1st part of step 3 : check if there is a databaseversion systempreference
522             # if there is, then we just need to upgrade
523             # if there is none, then we need to install the database
524             #
525             my $dbversion = C4::Context->preference('Version');
526             $dbversion =~ /(.*)\.(..)(..)(...)/;
527             $dbversion = "$1.$2.$3.$4";
528             if (C4::Context->preference('Version')) {
529                 $template->param("upgrading" => 1,
530                                 "dbversion" => $dbversion,
531                                 "kohaversion" => C4::Context->KOHAVERSION,
532                                 );
533             }
534         }
535
536         $dbh->disconnect;
537     }
538 }
539 else {
540
541     # LANGUAGE SELECTION page by default
542     # using opendir + language Hash
543
544     my $langavail = getTranslatedLanguages();
545
546     my @languages;
547     foreach (@$langavail) {
548         push @languages,
549           {
550             'value'       => $_->{'language_code'},
551             'description' => $_->{'language_name'}
552           }
553           if ( $_->{'language_code'} );
554     }
555     $template->param( languages => \@languages );
556     if ($dbh) {
557         my $rq =
558           $dbh->prepare(
559             "SELECT * from systempreferences WHERE variable='Version'");
560         if ( $rq->execute ) {
561             my ($version) = $rq->fetchrow;
562             if ($version) {
563                 $query->redirect("install.pl?step=3");
564             }
565         }
566     }
567 }
568 output_html_with_http_headers $query, $cookie, $template->output;