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