Bug 28606: Remove warning from C4::Auth 887
[koha.git] / tools / stage-marc-import.pl
1 #!/usr/bin/perl
2
3 # Script for handling import of MARC data into Koha db
4 #   and Z39.50 lookups
5
6 # Koha library project  www.koha-community.org
7
8 # Licensed under the GPL
9
10 # Copyright 2000-2002 Katipo Communications
11 #
12 # This file is part of Koha.
13 #
14 # Koha is free software; you can redistribute it and/or modify it
15 # under the terms of the GNU General Public License as published by
16 # the Free Software Foundation; either version 3 of the License, or
17 # (at your option) any later version.
18 #
19 # Koha is distributed in the hope that it will be useful, but
20 # WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with Koha; if not, see <http://www.gnu.org/licenses>.
26
27 use Modern::Perl;
28
29 # standard or CPAN modules used
30 use CGI qw ( -utf8 );
31 use CGI::Cookie;
32 use MARC::File::USMARC;
33
34 # Koha modules used
35 use C4::Context;
36 use C4::Auth;
37 use C4::Output;
38 use C4::Biblio;
39 use C4::ImportBatch;
40 use C4::Matcher;
41 use Koha::UploadedFiles;
42 use C4::BackgroundJob;
43 use C4::MarcModificationTemplates;
44 use Koha::Plugins;
45 use Koha::ImportBatches;
46
47 my $input = CGI->new;
48
49 my $fileID                     = $input->param('uploadedfileid');
50 my $runinbackground            = $input->param('runinbackground');
51 my $completedJobID             = $input->param('completedJobID');
52 my $matcher_id                 = $input->param('matcher');
53 my $overlay_action             = $input->param('overlay_action');
54 my $nomatch_action             = $input->param('nomatch_action');
55 my $parse_items                = $input->param('parse_items');
56 my $item_action                = $input->param('item_action');
57 my $comments                   = $input->param('comments');
58 my $record_type                = $input->param('record_type');
59 my $encoding                   = $input->param('encoding') || 'UTF-8';
60 my $format                     = $input->param('format') || 'ISO2709';
61 my $marc_modification_template = $input->param('marc_modification_template_id');
62 my $basketno                   = $input->param('basketno');
63 my $booksellerid               = $input->param('booksellerid');
64 my $profile_id                 = $input->param('profile_id');
65
66 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
67     {
68         template_name   => "tools/stage-marc-import.tt",
69         query           => $input,
70         type            => "intranet",
71         flagsrequired   => { tools => 'stage_marc_import' },
72     }
73 );
74
75 $template->param(
76     SCRIPT_NAME => '/cgi-bin/koha/tools/stage-marc-import.pl',
77     uploadmarc  => $fileID,
78     record_type => $record_type,
79     basketno => $basketno,
80     booksellerid => $booksellerid,
81 );
82
83 my %cookies = parse CGI::Cookie($cookie);
84 my $sessionID = $cookies{'CGISESSID'}->value;
85 if ($completedJobID) {
86     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
87     my $results = $job->results();
88     $template->param(map { $_ => $results->{$_} } keys %{ $results });
89 } elsif ($fileID) {
90     my $upload = Koha::UploadedFiles->find( $fileID );
91     my $file = $upload->full_path;
92     my $filename = $upload->filename;
93
94     my ( $errors, $marcrecords );
95     if( $format eq 'MARCXML' ) {
96         ( $errors, $marcrecords ) = C4::ImportBatch::RecordsFromMARCXMLFile( $file, $encoding);
97     } elsif( $format eq 'ISO2709' ) {
98         ( $errors, $marcrecords ) = C4::ImportBatch::RecordsFromISO2709File( $file, $record_type, $encoding );
99     } else { # plugin based
100         $errors = [];
101         $marcrecords = C4::ImportBatch::RecordsFromMarcPlugin( $file, $format, $encoding );
102     }
103     warn "$filename: " . ( join ',', @$errors ) if @$errors;
104         # no need to exit if we have no records (or only errors) here
105         # BatchStageMarcRecords can handle that
106
107     my $job = undef;
108     if ($runinbackground) {
109         my $job_size = scalar(@$marcrecords);
110         # if we're matching, job size is doubled
111         $job_size *= 2 if ($matcher_id ne "");
112         $job = C4::BackgroundJob->new($sessionID, $filename, '/cgi-bin/koha/tools/stage-marc-import.pl', $job_size);
113         my $jobID = $job->id();
114
115         # fork off
116         if (my $pid = fork) {
117             # parent
118             # return job ID as JSON
119             my $reply = CGI->new("");
120             print $reply->header(-type => 'text/html');
121             print '{"jobID":"' . $jobID . '"}';
122             exit 0;
123         } elsif (defined $pid) {
124             # child
125             # close STDOUT/STDERR to signal to end CGI session with Apache
126             # Otherwise, the AJAX request to this script won't return properly
127             close STDOUT;
128             close STDERR;
129         } else {
130             # fork failed, so exit immediately
131             warn "fork failed while attempting to run tools/stage-marc-import.pl as a background job: $!";
132             exit 0;
133         }
134
135         # if we get here, we're a child that has detached
136         # itself from Apache
137
138     }
139
140     my $schema = Koha::Database->new->schema;
141     $schema->storage->txn_begin;
142
143     # FIXME branch code
144     my ( $batch_id, $num_valid, $num_items, @import_errors ) =
145       BatchStageMarcRecords(
146         $record_type,    $encoding,
147         $marcrecords,    $filename,
148         $marc_modification_template,
149         $comments,       '',
150         $parse_items,    0,
151         50, staging_progress_callback( $job )
152       );
153
154     if($profile_id) {
155         my $ibatch = Koha::ImportBatches->find($batch_id);
156         $ibatch->set({profile_id => $profile_id})->store;
157     }
158
159     my $num_with_matches = 0;
160     my $checked_matches = 0;
161     my $matcher_failed = 0;
162     my $matcher_code = "";
163     if ($matcher_id ne "") {
164         my $matcher = C4::Matcher->fetch($matcher_id);
165         if (defined $matcher) {
166             $checked_matches = 1;
167             $matcher_code = $matcher->code();
168             $num_with_matches =
169               BatchFindDuplicates( $batch_id, $matcher, 10, 50,
170                 matching_progress_callback($job) );
171             SetImportBatchMatcher($batch_id, $matcher_id);
172             SetImportBatchOverlayAction($batch_id, $overlay_action);
173             SetImportBatchNoMatchAction($batch_id, $nomatch_action);
174             SetImportBatchItemAction($batch_id, $item_action);
175             $schema->storage->txn_commit;
176         } else {
177             $matcher_failed = 1;
178             $schema->storage->txn_rollback;
179         }
180     } else {
181         $schema->storage->txn_commit;
182     }
183
184     my $results = {
185         staged          => $num_valid,
186         matched         => $num_with_matches,
187         num_items       => $num_items,
188         import_errors   => scalar(@import_errors),
189         total           => $num_valid + scalar(@import_errors),
190         checked_matches => $checked_matches,
191         matcher_failed  => $matcher_failed,
192         matcher_code    => $matcher_code,
193         import_batch_id => $batch_id,
194         booksellerid    => $booksellerid,
195         basketno        => $basketno
196     };
197     if ($runinbackground) {
198         $job->finish($results);
199         exit 0;
200     } else {
201             $template->param(staged => $num_valid,
202                              matched => $num_with_matches,
203                          num_items => $num_items,
204                          import_errors => scalar(@import_errors),
205                          total => $num_valid + scalar(@import_errors),
206                          checked_matches => $checked_matches,
207                          matcher_failed => $matcher_failed,
208                          matcher_code => $matcher_code,
209                          import_batch_id => $batch_id,
210                          booksellerid => $booksellerid,
211                          basketno => $basketno
212                         );
213     }
214
215 } else {
216     # initial form
217     if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
218         $template->param( "UNIMARC" => 1 );
219     }
220     my @matchers = C4::Matcher::GetMatcherList();
221     $template->param( available_matchers => \@matchers );
222
223     my @templates = GetModificationTemplates();
224     $template->param( MarcModificationTemplatesLoop => \@templates );
225
226     if ( C4::Context->config('enable_plugins') ) {
227
228         my @plugins = Koha::Plugins->new()->GetPlugins({
229             method => 'to_marc',
230         });
231         $template->param( plugins => \@plugins );
232     }
233 }
234
235 output_html_with_http_headers $input, $cookie, $template->output;
236
237 exit 0;
238
239 sub staging_progress_callback {
240     my $job = shift;
241     return sub {
242         my $progress = shift;
243         $job->progress($progress);
244     }
245 }
246
247 sub matching_progress_callback {
248     my $job = shift;
249     my $start_progress = $job->progress();
250     return sub {
251         my $progress = shift;
252         $job->progress($start_progress + $progress);
253     }
254 }