MT 1587 : CSV export for cart and shelves, with the ability to define different expor...
[koha.git] / installer / install.pl
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5 use diagnostics;
6
7 # use Install;
8 use InstallAuth;
9 use C4::Context;
10 use C4::Output;
11 use C4::Languages qw(getAllLanguages getTranslatedLanguages);
12 use C4::Installer;
13
14 use CGI;
15 use IPC::Cmd;
16
17 my $query = new CGI;
18 my $step  = $query->param('step');
19
20 my $language = $query->param('language');
21 my ( $template, $loggedinuser, $cookie );
22
23 my $all_languages = getAllLanguages();
24
25 if ( defined($language) ) {
26     setlanguagecookie( $query, $language, "install.pl?step=1" );
27 }
28 ( $template, $loggedinuser, $cookie ) = get_template_and_user(
29     {
30         template_name => "installer/step" . ( $step ? $step : 1 ) . ".tmpl",
31         query         => $query,
32         type          => "intranet",
33         authnotrequired => 0,
34         debug           => 1,
35     }
36 );
37
38 my $installer = C4::Installer->new();
39 my %info;
40 $info{'dbname'} = C4::Context->config("database");
41 $info{'dbms'} =
42   (   C4::Context->config("db_scheme")
43     ? C4::Context->config("db_scheme")
44     : "mysql" );
45 $info{'hostname'} = C4::Context->config("hostname");
46 $info{'port'}     = C4::Context->config("port");
47 $info{'user'}     = C4::Context->config("user");
48 $info{'password'} = C4::Context->config("pass");
49 my $dbh = DBI->connect(
50     "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
51       . ( $info{port} ? ";port=$info{port}" : "" ),
52     $info{'user'}, $info{'password'}
53 );
54
55 if ( $step && $step == 1 ) {
56     #First Step
57     #Checking ALL perl Modules and services needed are installed.
58     #Whenever there is an error, adding a report to the page
59     $template->param( language => 1 );
60     my $problem;
61
62     unless ( $] >= 5.006001 ) {    # Bug 179
63         $template->param( "problems" => 1, "perlversion" => 1 );
64         $problem = 1;
65     }
66
67     # We could here use a special find
68     my @missing = ();
69     unless ( eval { require ZOOM } ) {
70         push @missing, { name => "ZOOM" };
71     }
72     unless ( eval { require YAML::Syck } ) {
73         push @missing, { name => "YAML::Syck" };
74     }
75     unless ( eval { require LWP::Simple } ) {
76         push @missing, { name => "LWP::Simple" };
77     }
78     unless ( eval { require XML::Simple } ) {
79         push @missing, { name => "XML::Simple" };
80     }
81     unless ( eval { require MARC::File::XML } ) {
82         push @missing, { name => "MARC::File::XML" };
83     }
84     unless ( eval { require MARC::File::USMARC } ) {
85         push @missing, { name => "MARC::File::USMARC" };
86     }
87     unless ( eval { require DBI } ) {
88         push @missing, { name => "DBI" };
89     }
90     unless ( eval { require Date::Manip } ) {
91         push @missing, { name => "Date::Manip" };
92     }
93     unless ( eval { require DBD::mysql } ) {
94         push @missing, { name => "DBD::mysql" };
95     }
96     unless ( eval { require HTML::Template::Pro } ) {
97         push @missing, { name => "HTML::Template::Pro" };
98     }
99     unless ( eval { require Date::Calc } ) {
100         push @missing, { name => "Date::Calc" };
101     }
102     unless ( eval { require Digest::MD5 } ) {
103         push @missing, { name => "Digest::MD5" };
104     }
105     unless ( eval { require MARC::Record } ) {
106         push @missing, { name => "MARC::Record" };
107     }
108     unless ( eval { require Mail::Sendmail } ) {
109         push @missing, { name => "Mail::Sendmail", usagemail => 1 };
110     }
111     unless ( eval { require List::MoreUtils } ) {
112         push @missing, { name => "List::MoreUtils" };
113     }
114     unless ( eval { require XML::RSS } ) {
115         push @missing, { name => "XML::RSS" };
116     }
117     unless ( eval { require CGI::Carp } ) {
118         push @missing, { name => "CGI::Carp" };
119     }
120
121
122 # The following modules are not mandatory, depends on how the library want to use Koha
123     unless ( eval { require PDF::API2 } ) {
124         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
125             push @missing, { name => "PDF::API2", usagebarcode => 1 };
126         }
127     }
128     unless ( eval { require GD::Barcorde } ) {
129         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
130             push @missing,
131               { name => "GD::Barcode", usagebarcode => 1, usagespine => 1 };
132         }
133     }
134     unless ( eval { require Data::Random } ) {
135         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
136             push @missing, { name => "Data::Random", usagebarcode => 1 };
137         }
138     }
139     unless ( eval { require PDF::Reuse::Barcode } ) {
140         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
141             push @missing, { name => "PDF::Reuse::Barcode", usagebarcode => 1 };
142         }
143     }
144     unless ( eval { require PDF::Report } ) {
145         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
146             push @missing, { name => "PDF::Report", usagebarcode => 1 };
147         }
148     }
149     unless ( eval { require Algorithm::CheckDigits } ) {
150         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
151             push @missing, { name => "Algorithm::CheckDigits", usagebarcode => 1 };
152         }
153     }
154     unless ( eval { require GD::Barcode::UPCE } ) {
155         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
156             push @missing, { name => "GD::Barcode::UPCE", usagepine => 1 };
157         }
158     }
159     unless ( eval { require Net::LDAP } ) {
160         if ( $#missing >= 0 ) {   # only when $#missing >= 0 so this isn't fatal
161             push @missing, { name => "Net::LDAP", usageLDAP => 1 };
162         }
163     }
164     $template->param( missings => \@missing ) if ( scalar(@missing) > 0 );
165     $template->param( 'checkmodule' => 1 )
166       unless ( scalar(@missing) && $problem );
167
168 }
169 elsif ( $step && $step == 2 ) {
170 #
171 #STEP 2 Check Database connection and access
172 #
173     $template->param(%info);
174     my $checkdb = $query->param("checkdb");
175     $template->param( 'dbconnection' => $checkdb );
176     if ($checkdb) {
177         if ($dbh) {
178
179             # Can connect to the mysql
180             $template->param( "checkdatabaseaccess" => 1 );
181             if ( $info{dbms} eq "mysql" ) {
182
183                 #Check if database created
184                 my $rv = $dbh->do("SHOW DATABASES LIKE \'$info{dbname}\'");
185                 if ( $rv == 1 ) {
186                     $template->param( 'checkdatabasecreated' => 1 );
187                 }
188
189                 #Check if user have all necessary grants on this database.
190                 my $rq =
191                   $dbh->prepare(
192                     "SHOW GRANTS FOR \'$info{user}\'\@'$info{hostname}'");
193                 $rq->execute;
194                 my $grantaccess;
195                 while ( my ($line) = $rq->fetchrow ) {
196                     my $dbname = $info{dbname};
197                     if ( $line =~ m/^GRANT (.*?) ON `$dbname`\.\*/ || index( $line, '*.*' ) > 0 ) {
198                         $grantaccess = 1
199                           if (
200                             index( $line, 'ALL PRIVILEGES' ) > 0
201                             || (   ( index( $line, 'SELECT' ) > 0 )
202                                 && ( index( $line, 'INSERT' ) > 0 )
203                                 && ( index( $line, 'UPDATE' ) > 0 )
204                                 && ( index( $line, 'DELETE' ) > 0 )
205                                 && ( index( $line, 'CREATE' ) > 0 )
206                                 && ( index( $line, 'DROP' ) > 0 ) )
207                           );
208                     }
209                 }
210                 unless ($grantaccess) {
211                     $rq =
212                       $dbh->prepare("SHOW GRANTS FOR \'$info{user}\'\@'\%'");
213                     $rq->execute;
214                     while ( my ($line) = $rq->fetchrow ) {
215                         my $dbname = $info{dbname};
216                         if ( $line =~ m/$dbname/ || index( $line, '*.*' ) > 0 )
217                         {
218                             $grantaccess = 1
219                               if (
220                                 index( $line, 'ALL PRIVILEGES' ) > 0
221                                 || (   ( index( $line, 'SELECT' ) > 0 )
222                                     && ( index( $line, 'INSERT' ) > 0 )
223                                     && ( index( $line, 'UPDATE' ) > 0 )
224                                     && ( index( $line, 'DELETE' ) > 0 )
225                                     && ( index( $line, 'CREATE' ) > 0 )
226                                     && ( index( $line, 'DROP' ) > 0 ) )
227                               );
228                         }
229                     }
230                 }
231                 $template->param( "checkgrantaccess" => $grantaccess );
232             }   # End mysql connect check...
233             
234             elsif ( $info{dbms} eq "Pg" ) {
235                 # Check if database has been created...
236                 my $rv = $dbh->do( "SELECT * FROM pg_catalog.pg_database WHERE datname = \'$info{dbname}\';" );
237                 if ( $rv == 1 ) {
238                         $template->param( 'checkdatabasecreated' => 1 );
239                 }
240
241                 # Check if user has all necessary grants on this database...
242                 my $rq = $dbh->do( "SELECT u.usesuper
243                                     FROM pg_catalog.pg_user as u
244                                     WHERE u.usename = \'$info{user}\';" );
245                 if ( $rq == 1 ) {
246                         $template->param( "checkgrantaccess" => 1 );
247                 }
248             }   # End Pg connect check...
249         }
250         else {
251             $template->param( "error" => DBI::err, "message" => DBI::errstr );
252         }
253     }
254 }
255 elsif ( $step && $step == 3 ) {
256 #
257 #
258 # STEP 3 : database setup
259 #
260
261     my $op = $query->param('op');
262     if ( $op && $op eq 'finished' ) {
263         #
264         # we have finished, just redirect to mainpage.
265         #
266         print $query->redirect("/cgi-bin/koha/mainpage.pl");
267         exit 1;
268     }
269     elsif ( $op && $op eq 'finish' ) {
270         $installer->set_version_syspref();
271
272         # Installation is finished.
273         # We just deny anybody access to install
274         # And we redirect people to mainpage.
275         # The installer will have to relogin since we do not pass cookie to redirection.
276         $template->param( "$op" => 1 );
277     }
278     elsif ( $op && $op eq 'SetIndexingEngine' ) {
279         $installer->set_indexing_engine($query->param('NoZebra'));
280         $template->param( "$op" => 1 );
281     }
282     elsif ( $op && $op eq 'addframeworks' ) {
283     #
284     # 1ST install, 3rd sub-step : insert the SQL files the user has selected
285     #
286
287         my ($fwk_language, $list) = $installer->load_sql_in_order($all_languages, $query->param('framework'));
288         $template->param(
289             "fwklanguage" => $fwk_language,
290             "list"        => $list
291         );
292         $template->param( "$op" => 1 );
293     }
294     elsif ( $op && $op eq 'selectframeworks' ) {
295         #
296         #
297         # 1ST install, 2nd sub-step : show the user the sql datas he can insert in the database.
298         #
299         #
300         # (note that the term "selectframeworks is not correct. The user can select various files, not only frameworks)
301         
302         #Framework Selection
303         #sql data for import are supposed to be located in installer/data/<language>/<level>
304         # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
305         # Where <level> is a category of requirement : required, recommended optional
306         # level should contain :
307         #   SQL File for import With a readable name.
308         #   txt File that explains what this SQL File is meant for.
309         # Could be VERY useful to have A Big file for a kind of library.
310         # But could also be useful to have some Authorised values data set prepared here.
311         # Framework Selection is achieved through checking boxes.
312         my $langchoice = $query->param('fwklanguage');
313         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
314         my $marcflavour = $query->param('marcflavour');
315         if ($marcflavour){
316             $installer->set_marcflavour_syspref($marcflavour);
317         };    
318         $marcflavour = C4::Context->preference('marcflavour') unless ($marcflavour);
319         #Insert into database the selected marcflavour
320         undef $/; 
321         my ($marc_defaulted_to_en, $fwklist) = $installer->marc_framework_sql_list($langchoice, $marcflavour);
322         $template->param('en_marc_frameworks' => $marc_defaulted_to_en);
323         $template->param( "frameworksloop" => $fwklist );
324         $template->param( "marcflavour" => ucfirst($marcflavour));
325        
326         my ($sample_defaulted_to_en, $levellist) = $installer->sample_data_sql_list($langchoice, $marcflavour);
327         $template->param( "en_sample_data" => $sample_defaulted_to_en);
328         $template->param( "levelloop" => $levellist );
329         $template->param( "$op"       => 1 );
330     }
331     elsif ( $op && $op eq 'choosemarc' ) {
332         #
333         #
334         # 1ST install, 2nd sub-step : show the user the marcflavour available.
335         #
336         #
337         
338         #Choose Marc Flavour
339         #sql data are supposed to be located in installer/data/<dbms>/<language>/marcflavour/marcflavourname
340         # Where <dbms> is database type according to DBD syntax
341         # Where <language> is en|fr or any international abbreviation (provided language hash is updated... This will be a problem with internationlisation.)
342         # Where <level> is a category of requirement : required, recommended optional
343         # level should contain :
344         #   SQL File for import With a readable name.
345         #   txt File taht explains what this SQL File is meant for.
346         # Could be VERY useful to have A Big file for a kind of library.
347         # But could also be useful to have some Authorised values data set prepared here.
348         # Marcflavour Selection is achieved through radiobuttons.
349         my $langchoice = $query->param('fwklanguage');
350         $langchoice = $query->cookie('KohaOpacLanguage') unless ($langchoice);
351         my $dir =
352           C4::Context->config('intranetdir') . "/installer/data/$info{dbms}/$langchoice/marcflavour";
353         unless (opendir( MYDIR, $dir )) {
354             if ($langchoice eq 'en') {
355                 warn "cannot open MARC frameworks directory $dir";
356             } else {
357                 # if no translated MARC framework is available,
358                 # default to English
359                 $dir = C4::Context->config('intranetdir') . "/installer/data/$info{dbms}/en/marcflavour";
360                 opendir(MYDIR, $dir) or warn "cannot open English MARC frameworks directory $dir";
361             }
362         }
363         my @listdir = grep { !/^\./ && -d "$dir/$_" } readdir(MYDIR);
364         closedir MYDIR;
365         my $marcflavour=C4::Context->preference("marcflavour");    
366         my @flavourlist;
367         foreach my $marc (@listdir) {
368             my %cell=(    
369             "label"=> ucfirst($marc),
370             "code"=>uc($marc),
371             "checked"=> defined($marcflavour) ? uc($marc) eq $marcflavour : 0);      
372 #             $cell{"description"}= do { local $/ = undef; open INPUT "<$dir/$marc.txt"||"";<INPUT> };
373             push @flavourlist, \%cell;
374         }
375         $template->param( "flavourloop" => \@flavourlist );
376         $template->param( "$op"       => 1 );
377     }
378     elsif ( $op && $op eq 'importdatastructure' ) {
379         #
380         #
381         # 1st install, 1st "sub-step" : import kohastructure
382         #
383         #
384         my $error = $installer->load_db_schema();
385         $template->param(
386             "error" => $error,
387             "$op"   => 1,
388         );
389     }
390     elsif ( $op && $op eq 'updatestructure' ) {
391         #
392         # Not 1st install, the only sub-step : update database
393         #
394         #Do updatedatabase And report
395         my $cmd = C4::Context->config("intranetdir") . "/installer/data/$info{dbms}/updatedatabase.pl";
396         my ($success, $error_code, $full_buf, $stdout_buf, $stderr_buf) = IPC::Cmd::run(command => $cmd, verbose => 0);
397
398         if (@$stdout_buf) {
399             $template->param(update_report => [ map { { line => $_ } } split(/\n/, join('', @$stdout_buf)) ] );
400             $template->param(has_update_succeeds => 1);
401         }
402         if (@$stderr_buf) {
403             $template->param(update_errors => [ map { { line => $_ } } split(/\n/, join('', @$stderr_buf)) ] );
404             $template->param(has_update_errors => 1);
405         }
406
407         $template->param( $op => 1 );
408     }
409     else {
410         #
411         # check wether it's a 1st install or an update
412         #
413         #Check if there are enough tables.
414         # Paul has cleaned up tables so reduced the count
415         #I put it there because it implied a data import if condition was not satisfied.
416         my $dbh = DBI->connect(
417                 "DBI:$info{dbms}:dbname=$info{dbname};host=$info{hostname}"
418                 . ( $info{port} ? ";port=$info{port}" : "" ),
419                 $info{'user'}, $info{'password'}
420         );
421         my $rq;
422         if ( $info{dbms} eq 'mysql' ) { $rq = $dbh->prepare( "SHOW TABLES FROM " . $info{'dbname'} ); }
423         elsif ( $info{dbms} eq 'Pg' ) { $rq = $dbh->prepare( "SELECT *
424                                                                 FROM information_schema.tables
425                                                                 WHERE table_schema='public' and table_type='BASE TABLE';" ); }
426         $rq->execute;
427         my $data = $rq->fetchall_arrayref( {} );
428         my $count = scalar(@$data);
429         #
430         # we don't have tables, propose DB import
431         #
432         if ( $count < 70 ) {
433             $template->param( "count" => $count, "proposeimport" => 1 );
434         }
435         else {
436             #
437             # we have tables, propose to select files to upload or updatedatabase
438             #
439             $template->param( "count" => $count, "default" => 1 );
440             #
441             # 1st part of step 3 : check if there is a databaseversion systempreference
442             # if there is, then we just need to upgrade
443             # if there is none, then we need to install the database
444             #
445             if (C4::Context->preference('Version')) {
446                 my $dbversion = C4::Context->preference('Version');
447                 $dbversion =~ /(.*)\.(..)(..)(...)/;
448                 $dbversion = "$1.$2.$3.$4";
449                 $template->param("upgrading" => 1,
450                                 "dbversion" => $dbversion,
451                                 "kohaversion" => C4::Context->KOHAVERSION,
452                                 );
453             }
454         }
455
456         $dbh->disconnect;
457     }
458 }
459 else {
460
461     # LANGUAGE SELECTION page by default
462     # using opendir + language Hash
463     my $languages_loop = getTranslatedLanguages('intranet');
464     $template->param( installer_languages_loop => $languages_loop );
465     if ($dbh) {
466         my $rq =
467           $dbh->prepare(
468             "SELECT * from systempreferences WHERE variable='Version'");
469         if ( $rq->execute ) {
470             my ($version) = $rq->fetchrow;
471             if ($version) {
472                 $query->redirect("install.pl?step=3");
473                                 exit;
474             }
475         }
476     }
477 }
478 output_html_with_http_headers $query, $cookie, $template->output;