bugfix : bibliotitems.dewey & deletedbiblioitems.dewey mustn't be double(8,6).
[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
22 my $all_languages=getAllLanguages();
23
24 if (defined($language) ){
25   setlanguagecookie($query,$language,"install.pl?step=1");
26 }
27 ($template, $loggedinuser, $cookie)
28         = get_template_and_user({template_name => "installer/step".($step?$step:1).".tmpl",
29                 query => $query,
30                 type => "intranet",
31                 authnotrequired => 0,
32                 debug => 1,
33                 });
34
35 my %info;
36 $info{'dbname'}=C4::Context->config("database");
37 $info{'dbms'}=(C4::Context->config("db_scheme")?C4::Context->config("db_scheme"):"mysql");
38 $info{'hostname'}=C4::Context->config("hostname");
39 ($info{'hostname'},$info{'port'})=($1,$2) if $info{'hostname'}=~/([^:]*):([0-9]+)/;
40 $info{'user'}=C4::Context->config("user");
41 $info{'password'}=C4::Context->config("pass");
42 my $dbh= DBI->connect("DBI:$info{dbms}:$info{dbname}:$info{hostname}".($info{port}?":$info{port}":""),$info{'user'}, $info{'password'});
43
44
45 if ($step && $step==1){
46   #First Step
47   #Checking ALL perl Modules and services needed are installed.
48   #Whenever there is an error, adding a report to the page
49   # I suppose here that Apache user can access /usr/bin/
50   # If mysql or zebra are in some fancy directory not in PATH
51   # Performing a disk search.
52   $template->param(language=>1);
53   my $problem;
54   
55   unless ($] >= 5.006001) {                     # Bug 179
56       $template->param("problems"=>1,"perlversion"=>1);
57       $problem=1;
58   }
59   unless (-x "/usr/bin/perl") {
60     my $realperl=`which perl`;
61     $realperl=`find / -name perl` unless ($realperl);
62     chomp $realperl;
63     $template->param("problems"=>1,'perllocation'=>1) unless ($realperl);
64     $problem=1 unless($realperl);
65   }
66   unless (-x "/usr/local/bin/mysql") {
67     my $mysql=`which mysql`;
68     $mysql=`find / -name mysql` unless ($mysql);
69     chomp $mysql;
70     $template->param("problems"=>1,'mysql'=>1) unless ($mysql);
71     $problem=1 unless($mysql);
72   }
73   unless (-x "/usr/local/bin/zebraidx" ||-x "/usr/local/bin/zebraidx-2.0") {
74     my $zebra=`which zebraidx`;
75     $zebra=`which zebraidx-2.0` unless ($zebra);
76     $zebra=`find / -name "zebraidx*"` unless ($zebra);
77     chomp $zebra;
78     $template->param("problems"=>1,'zebra'=>1) unless ($zebra);
79     $problem=1 unless ($zebra);
80   }
81   unless (-x "/usr/local/bin/zebrasrv" ||-x "/usr/local/bin/zebrasrv-2.0") {
82     my $zebra=`which zebrasrv`;
83     $zebra=`which zebrasrv-2.0` unless ($zebra);
84     $zebra=`find / -name "zebrasrv*"` unless ($zebra);
85     chomp $zebra;
86     $template->param("problems"=>1,'zebra'=>1) unless ($zebra);
87     $problem=1 unless ($zebra);
88   }
89   unless (-x "/usr/local/bin/yaz-client") {
90     my $yaz=`which yaz-client`;
91     $yaz=`find / -name "yaz-client*"` unless ($yaz);
92     chomp $yaz;
93     $template->param("problems"=>1,'yaz'=>1) unless ($yaz);
94     $problem=1 unless ($yaz);
95   }
96   # We could here use a special find 
97   my @missing = ();
98   unless (eval {require ZOOM})       {
99           push @missing, {name=>"ZOOM"};
100   }
101   unless (eval {require LWP::Simple})       {
102           push @missing, {name=>"LWP::Simple"};
103   }
104   unless (eval {require XML::Simple})       {
105           push @missing, {name=>"XML::Simple"};
106   }
107   unless (eval {require MARC::File::XML})       {
108           push @missing, {name=>"MARC::File::XML"};
109   }
110   unless (eval {require MARC::File::USMARC})       {
111           push @missing, {name=>"MARC::File::USMARC"};
112   }
113   unless (eval {require DBI})              { push @missing,{name=>"DBI"} };
114   unless (eval {require Date::Manip})      { push @missing,{name=>"Date::Manip"} };
115   unless (eval {require DBD::mysql})       { push @missing,{name=>"DBD::mysql"} };
116   unless (eval {require HTML::Template})   { push @missing,{name=>"HTML::Template::Pro"} };
117   unless (eval {require HTML::Template})   { push @missing,{name=>"Date::Calc"} };
118   unless (eval {require Digest::MD5})      { push @missing,{name=>"Digest::MD5"} };
119   unless (eval {require MARC::Record})     { push @missing,{name=>"MARC::Record"} };
120   unless (eval {require Mail::Sendmail})   { push @missing,{name=>"Mail::Sendmail",usagemail=>1} };
121 # The following modules are not mandatory, depends on how the library want to use Koha
122   unless (eval {require PDF::API2})   { 
123           if ($#missing>=0) { # only when $#missing >= 0 so this isn't fatal
124               push @missing,{name=>"PDF::API2",usagebarcode=>1};
125           }
126   }
127   unless (eval {require GD::Barcorde})   { 
128     if ($#missing>=0) { # only when $#missing >= 0 so this isn't fatal
129       push @missing,{name=>"GD::Barcode",usagebarcode=>1,usagespine=>1};
130     }
131   }
132   unless (eval {require Data::Random})   { 
133     if ($#missing>=0) { # only when $#missing >= 0 so this isn't fatal
134       push @missing,{name=>"Data::Random",usagebarcode=>1};
135     }
136   }
137   unless (eval {require PDF::Reuse::Barcode})   {
138     if ($#missing>=0) { # only when $#missing >= 0 so this isn't fatal
139       push @missing,{name=>"PDF::Reuse::Barcode",usagebarcode=>1};
140     }
141   }
142   unless (eval {require PDF::Report})   {
143     if ($#missing>=0) { # only when $#missing >= 0 so this isn't fatal
144       push @missing,{name=>"PDF::Report",usagebarcode=>1};
145     }
146   }
147   unless (eval {require GD::Barcode::UPCE})   {
148     if ($#missing>=0) { # only when $#missing >= 0 so this isn't fatal
149       push @missing,{name=>"GD::Barcode::UPCE",usagepine=>1};
150     }
151   }
152   unless (eval {require Net::LDAP})       {
153     if ($#missing>=0) { # only when $#missing >= 0 so this isn't fatal
154       push @missing,{name=>"Net::LDAP",usageLDAP=>1};
155     }
156   }
157
158   $template->param(missings=>\@missing) if (scalar(@missing)>0);
159   $template->param('checkmodule'=>1) unless (scalar(@missing) && $problem);
160   
161 } elsif ($step && $step==2){
162   # Check Database connection and access
163   $template->param(%info);
164   my $checkmysql=$query->param("checkmysql");
165   $template->param('mysqlconnection'=>$checkmysql);
166   if ($checkmysql){
167     if ($dbh){
168       # Can connect to the mysql
169       $template->param("checkdatabaseaccess"=>1);
170       if ($info{dbms} eq "mysql"){
171         #Check if database created
172         my $rv=$dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
173         if ($rv==1){$template->param('checkdatabasecreated'=>1);}
174         #Check if user have all necessary grants on this database.
175         my $rq=$dbh->prepare("SHOW GRANTS FOR \'$info{user}\'\@'$info{hostname}'");
176         $rq->execute;
177         my $grantaccess;
178         while (my ($line)=$rq->fetchrow){
179           my $dbname=$info{dbname};
180           if ($line=~m/$dbname/ || index($line,'*.*')>0){
181             $grantaccess=1 if (index($line,'ALL PRIVILEGES')>0 ||
182             ((index($line,'SELECT')>0)&&(index($line,'INSERT')>0)&&(index($line,'UPDATE')>0)&&(index($line,'DELETE')>0)&&(index($line,'CREATE')>0)&&(index($line,'DROP')>0)));
183           }
184         }
185         unless ($grantaccess){
186           $rq=$dbh->prepare("SHOW GRANTS FOR \'$info{user}\'\@'\%'");
187           $rq->execute;
188           while (my ($line)=$rq->fetchrow){
189             my $dbname=$info{dbname};
190             if ($line=~m/$dbname/ || index($line,'*.*')>0){
191               $grantaccess=1 if (index($line,'ALL PRIVILEGES')>0 ||
192               ((index($line,'SELECT')>0)&&(index($line,'INSERT')>0)&&(index($line,'UPDATE')>0)&&(index($line,'DELETE')>0)&&(index($line,'CREATE')>0)&&(index($line,'DROP')>0)));
193             }
194           }
195         }
196         $template->param("checkgrantaccess"=>$grantaccess);
197       }
198     } else {
199       $template->param("error"=>DBI::err,"message"=>DBI::errstr);
200     }
201   }
202 } elsif ($step && $step==3){
203   my $op=$query->param('op');
204   if ($op && $op eq 'finish'){
205     # Installation is finished.
206     # We just deny anybody acess to install
207     # And we redirect people to mainpage.
208     # The installer wil have to relogin since we donot pass cookie to redirection.
209     $template->param("$op"=>1);
210   }elsif ($op && $op eq 'finished'){
211     print $query->redirect("/cgi-bin/koha/mainpage.pl");
212     exit 1;
213   } elsif ($op && $op eq 'addframeworks'){
214     #Framework importing and reports
215     my $lang;
216     my %hashlevel;
217    # sort by filename -> prepend with numbers to specify order of insertion. 
218     my @fnames = sort { my @aa = split /\/|\\/, ($a); my @bb = split /\/|\\/, ($b); $aa[-1] lt $bb[-1] } $query->param('framework')  ;
219     my $request=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'");
220     $request->execute;
221     my ($systempreference)=$request->fetchrow;
222     foreach my $file (@fnames){
223 #      warn $file;
224       undef $/;
225       my $strcmd="mysql ".($info{hostname}?"-h $info{hostname} ":"").($info{port}?"-P $info{port} ":"").($info{user}?"-u $info{user} ":"").($info{password}?"-p$info{password}":"")." $info{dbname} ";
226       my $error = qx($strcmd < $file 2>&1);
227       my @file = split qr(\/|\\),$file;
228       $lang=$file[scalar(@file)-3] unless ($lang);
229       my $level=$file[scalar(@file)-2];
230       unless ($error){
231         $systempreference.="$file[scalar(@file)-1]|" unless(index($systempreference,$file[scalar(@file)-1])>=0);
232       }
233       #Bulding here a hierarchy to display files by level.
234       push @{$hashlevel{$level}},{"fwkname"=>$file[scalar(@file)-1],"error"=>$error};
235     }
236     #systempreference contains an ending |
237     chop $systempreference;
238     my @list;
239     map {push @list,{"level"=>$_,"fwklist"=>$hashlevel{$_}}} keys %hashlevel;
240     my $fwk_language;
241     for my $each_language(@$all_languages) {
242 #               warn "CODE".$each_language->{'language_code'};
243 #               warn "LANG:".$lang;
244       if ($lang eq $each_language->{'language_code'}) {
245               $fwk_language = $each_language->{language_locale_name};
246       }
247     }
248     my $updateflag=$dbh->do("UPDATE systempreferences set value=\"$systempreference\" where variable='FrameworksLoaded'");
249     unless ($updateflag==1){
250       my $string="INSERT INTO systempreferences (value, variable, explanation, type) VALUES (\"$systempreference\",'FrameworksLoaded','Frameworks loaded through webinstaller','choice')";
251       my $rq=$dbh->prepare($string);
252       $rq->execute;
253     }
254     $template->param("fwklanguage"=>$fwk_language,
255                      "list"=>\@list);
256     $template->param("$op"=>1);
257   } elsif ( $op && $op eq 'selectframeworks'){
258     #Framework Selection
259     #sql data for import are supposed to be located in misc/sql-datas/<language>/<level>
260     # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
261     # Where <level> is a category of requirement : required, recommended optional
262     # level should contain : 
263     #   SQL File for import With a readable name.
264     #   txt File taht explains what this SQL File is meant for.
265     # Could be VERY useful to have A Big file for a kind of library.
266     # But could also be useful to have some Authorised values data set prepared here.
267     # Framework Selection is achieved through checking boxes.
268     my $langchoice=$query->param('fwklanguage') ;
269     $langchoice=$query->cookie('KohaOpacLanguage') unless ($langchoice);
270     my $dir=C4::Context->config('intranetdir')."/misc/sql-datas/";
271     opendir (MYDIR,$dir);
272     my @listdir= grep { !/^\.|CVS/ && -d "$dir/$_"} readdir(MYDIR);
273     closedir MYDIR;
274     my $frmwklangs = getFrameworkLanguages();
275     my @languages;
276     map{
277       push @languages,{'dirname'=>$_->{'language_code'}, 'languagedescription'=>$_->{'language_name'},'checked'=>($_->{'language_code'} eq $langchoice) } if ($_->{'language_code'});
278     } @$frmwklangs;
279     $template->param("languagelist"=>\@languages);
280     undef $/;
281     $dir=C4::Context->config('intranetdir')."/misc/sql-datas/$langchoice";
282     opendir (MYDIR,$dir) || warn "no open $dir";
283     @listdir= grep { !/^\.|CVS/ && -d "$dir/$_"} readdir(MYDIR);
284     closedir MYDIR;
285     my @levellist;
286     my $request=$dbh->prepare("SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'");
287     $request->execute;
288     my ($frameworksloaded)=$request->fetchrow;
289     my %frameworksloaded;
290     foreach (split(/\|/,$frameworksloaded)){
291       $frameworksloaded{$_}=1;
292     }
293     foreach my $requirelevel (@listdir){
294       $dir =C4::Context->config('intranetdir')."/misc/sql-datas/$langchoice/$requirelevel";
295       opendir (MYDIR,$dir);
296       my @listname = grep { !/^\.|CVS/ && -f "$dir/$_" && $_=~m/\.sql$/} readdir(MYDIR);
297       closedir MYDIR;
298       my %cell;
299       my @frameworklist;
300       map{
301         my $name=substr($_,0,-4);
302         open FILE, "< $dir/$name.txt";
303         my $lines = <FILE>; 
304         $lines=~s/\n|\r/<br \/>/g;
305         use utf8;
306         utf8::encode($lines) unless (utf8::is_utf8($lines));
307         push @frameworklist,
308           {'fwkname'=>$name, 
309            'fwkfile'=>"$dir/$_",
310            'fwkdescription'=>$lines,
311            'checked'=>(($frameworksloaded{$_}||($requirelevel=~/(mandatory|requi|oblig|necess)/i))?1:0)
312           };
313       } @listname;
314       my @fwks = sort { $a->{'fwkname'} lt $b->{'fwkname'} } @frameworklist;
315 #       $cell{"mandatory"}=($requirelevel=~/(mandatory|requi|oblig|necess)/i);
316       $cell{"frameworks"}=\@fwks;
317       $cell{"label"}=ucfirst($requirelevel);
318       $cell{"code"}=lc($requirelevel);
319       push @levellist,\%cell;
320     }
321     $template->param("levelloop"=>\@levellist);
322     $template->param("$op"=>1);
323   } elsif ($op && $op eq 'updatestructure'){
324     #Do updatedatabase And report
325     my $execstring=C4::Context->config("intranetdir")."/updater/updatedatabase";
326     undef $/;
327     my $string= qx|$execstring 2>&1|;
328     if ($string){
329       $string=~s/\n|\r/<br \/>/g;
330       $string=~s/(DBD::mysql.*? failed: .*? line [0-9]*.|=================.*?====================)/<font color=red>$1<\/font>/g;
331       $template->param("updatereport"=>$string) ;
332     }
333     $template->param($op=>1)
334   }elsif ($op && $op eq 'importdatastructure'){
335     #Import data structure and show errors if any
336     my $filename="kohastructure.sql";
337     undef $/;
338         my $str = qx(mysql -h $info{hostname} -P $info{port} -u $info{user} -p$info{password} $info{dbname} <$filename 2>&1);
339         $str=~s/\n|\r/<br \/>/g;
340         $template->param("error"=>$str ,
341                          "$op"=> 1, );
342   } else {
343     #Check if there are enough tables.
344     # Version 2_2 was 74 tables, so we check if there is more than 75
345     # Maybe could be in step 2
346     #I put it there because it implied a data import if condition was not satisfied.
347     my $dbh= DBI->connect("DBI:$info{dbms}:$info{dbname}:$info{hostname}".($info{port}?":$info{port}":""),$info{'user'}, $info{'password'});
348     my $rq=$dbh->prepare("SHOW TABLES FROM ".$info{'dbname'});
349     $rq->execute;
350     my $data=$rq->fetchall_arrayref({});
351     my $count=scalar(@$data);
352     if ($count < 75){
353       $template->param("count"=>$count,"proposeimport"=>1);
354     } else {
355       $template->param("count"=>$count,"default"=>1);
356     }
357     $dbh->disconnect;
358   }
359 }else {
360   # LANGUAGE SELECTION page by default
361   # using opendir + language Hash
362   
363   my $langavail = getTranslatedLanguages();
364   my @languages;
365   foreach (@$langavail){
366         push @languages,{'value'=>$_->{'language_code'}, 'description'=>$_->{'language_name'} } if ($_->{'language_code'});
367   }
368   $template->param(languages=>\@languages);
369   if ($dbh){
370     my $rq=$dbh->prepare("SELECT * from systempreferences WHERE variable='Version'");
371     $rq->execute;
372     my ($version)=$rq->fetchrow;
373     if ($version){
374       $query->redirect("install.pl?step=3");
375     }
376   }
377 }
378 output_html_with_http_headers $query, $cookie, $template->output;