Merge remote-tracking branch 'origin/new/bug_8185'
[koha.git] / tools / manage-marc-import.pl
1 #!/usr/bin/perl
2
3 # Copyright (C) 2007 LibLime
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 use warnings;
22
23 # standard or CPAN modules used
24 use CGI;
25 use CGI::Cookie;
26 use MARC::File::USMARC;
27
28 # Koha modules used
29 use C4::Context;
30 use C4::Koha;
31 use C4::Auth;
32 use C4::AuthoritiesMarc;
33 use C4::Output;
34 use C4::Biblio;
35 use C4::ImportBatch;
36 use C4::Matcher;
37 use C4::BackgroundJob;
38 use C4::Labels::Batch;
39 use C4::Branch qw(get_branch_code_from_name);
40
41 my $script_name = "/cgi-bin/koha/tools/manage-marc-import.pl";
42
43 my $input = new CGI;
44 my $op = $input->param('op') || '';
45 my $completedJobID = $input->param('completedJobID');
46 our $runinbackground = $input->param('runinbackground');
47 my $import_batch_id = $input->param('import_batch_id') || '';
48
49 # record list displays
50 my $offset = $input->param('offset') || 0;
51 my $results_per_page = $input->param('results_per_page') || 25; 
52
53 my ($template, $loggedinuser, $cookie)
54     = get_template_and_user({template_name => "tools/manage-marc-import.tmpl",
55                  query => $input,
56                  type => "intranet",
57                  authnotrequired => 0,
58                  flagsrequired => {tools => 'manage_staged_marc'},
59                  debug => 1,
60                  });
61
62 my %cookies = parse CGI::Cookie($cookie);
63 our $sessionID = $cookies{'CGISESSID'}->value;
64 our $dbh = C4::Context->dbh;
65
66 # Frameworks selection loop
67 {
68     my $frameworks = getframeworks;
69     my $arrayref = [];
70     while ( my ($key, $value) = each %$frameworks ) {
71         push @$arrayref, { value => $key, label => $value->{frameworktext} };
72     }
73     $template->param( frameworks => $arrayref );
74 }
75
76 if ($op eq "create_labels") {
77         #create a batch of labels, then lose $op & $import_batch_id so we get back to import batch list.
78         my $label_batch_id = create_labelbatch_from_importbatch($import_batch_id);
79         if ($label_batch_id == -1) {
80             $template->param(   label_batch_msg => "Error attempting to create label batch. Please ask your system administrator to check the log for more details.",
81                                 message_type    => 'alert',
82             );
83         }
84         else {
85             $template->param(   label_batch_msg => "Label batch #$label_batch_id created.",
86                                 message_type    => 'dialog',
87             );
88         }
89         $op='';
90         $import_batch_id='';
91 }
92 if ($op) {
93     $template->param(script_name => $script_name, $op => 1);
94 } else {
95     $template->param(script_name => $script_name);
96 }
97
98 if ($op eq "") {
99     # displaying a list
100     if ($import_batch_id eq '') {
101         import_batches_list($template, $offset, $results_per_page);
102     } else {
103         import_records_list($template, $import_batch_id, $offset, $results_per_page);
104     }
105 } elsif ($op eq "commit-batch") {
106     if ($completedJobID) {
107         add_saved_job_results_to_template($template, $completedJobID);
108     } else {
109         my $framework = $input->param('framework');
110         commit_batch($template, $import_batch_id, $framework);
111     }
112     import_records_list($template, $import_batch_id, $offset, $results_per_page);
113 } elsif ($op eq "revert-batch") {
114     if ($completedJobID) {
115         add_saved_job_results_to_template($template, $completedJobID);
116     } else {
117         revert_batch($template, $import_batch_id);
118     }
119     import_records_list($template, $import_batch_id, $offset, $results_per_page);
120 } elsif ($op eq "clean-batch") {
121     CleanBatch($import_batch_id);
122     import_batches_list($template, $offset, $results_per_page);
123     $template->param( 
124         did_clean       => 1,
125         import_batch_id => $import_batch_id,
126     );
127 } elsif ($op eq "redo-matching") {
128     my $new_matcher_id = $input->param('new_matcher_id');
129     my $current_matcher_id = $input->param('current_matcher_id');
130     my $overlay_action = $input->param('overlay_action');
131     my $nomatch_action = $input->param('nomatch_action');
132     my $item_action = $input->param('item_action');
133     redo_matching($template, $import_batch_id, $new_matcher_id, $current_matcher_id, 
134                   $overlay_action, $nomatch_action, $item_action);
135     import_records_list($template, $import_batch_id, $offset, $results_per_page);
136
137
138 output_html_with_http_headers $input, $cookie, $template->output;
139
140 exit 0;
141
142 sub redo_matching {
143     my ($template, $import_batch_id, $new_matcher_id, $current_matcher_id, $overlay_action, $nomatch_action, $item_action) = @_;
144     my $rematch_failed = 0;
145     return if not defined $new_matcher_id and not defined $current_matcher_id;
146     my $old_overlay_action = GetImportBatchOverlayAction($import_batch_id);
147     my $old_nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
148     my $old_item_action = GetImportBatchItemAction($import_batch_id);
149     return if $new_matcher_id eq $current_matcher_id and 
150               $old_overlay_action eq $overlay_action and 
151               $old_nomatch_action eq $nomatch_action and 
152               $old_item_action eq $item_action;
153  
154     if ($old_overlay_action ne $overlay_action) {
155         SetImportBatchOverlayAction($import_batch_id, $overlay_action);
156         $template->param('changed_overlay_action' => 1);
157     }
158     if ($old_nomatch_action ne $nomatch_action) {
159         SetImportBatchNoMatchAction($import_batch_id, $nomatch_action);
160         $template->param('changed_nomatch_action' => 1);
161     }
162     if ($old_item_action ne $item_action) {
163         SetImportBatchItemAction($import_batch_id, $item_action);
164         $template->param('changed_item_action' => 1);
165     }
166
167     my $num_with_matches = 0;
168     if (defined $new_matcher_id and $new_matcher_id ne "") {
169         my $matcher = C4::Matcher->fetch($new_matcher_id);
170         if (defined $matcher) {
171             $num_with_matches = BatchFindDuplicates($import_batch_id, $matcher);
172             SetImportBatchMatcher($import_batch_id, $new_matcher_id);
173         } else {
174             $rematch_failed = 1;
175         }
176     } else {
177         $num_with_matches = BatchFindDuplicates($import_batch_id, undef);
178         SetImportBatchMatcher($import_batch_id, undef);
179         SetImportBatchOverlayAction('create_new');
180     }
181     $template->param(rematch_failed => $rematch_failed);
182     $template->param(rematch_attempted => 1);
183     $template->param(num_with_matches => $num_with_matches);
184 }
185
186 sub create_labelbatch_from_importbatch {
187         my ($batch_id) = @_;
188         my $err = undef;
189         my $branch_code = C4::Context->userenv->{'branch'};
190         my $batch = C4::Labels::Batch->new(branch_code => $branch_code);
191         my @items = GetItemNumbersFromImportBatch($batch_id);
192         if (grep{$_ == 0} @items) {
193             warn sprintf('create_labelbatch_from_importbatch() : Call to C4::ImportBatch::GetItemNumbersFromImportBatch returned no item number(s) from import batch #%s.', $batch_id);
194             return -1;
195         }
196         foreach my $item_number (@items) {
197             $err = $batch->add_item($item_number);
198             if ($err == -1) {
199                 warn sprintf('create_labelbatch_from_importbatch() : Error attempting to add item #%s of import batch #%s to label batch.', $item_number, $batch_id);
200                 return -1;
201             }
202         }
203         return $batch->get_attr('batch_id');
204 }
205
206 sub import_batches_list {
207     my ($template, $offset, $results_per_page) = @_;
208     my $batches = GetImportBatchRangeDesc($offset, $results_per_page);
209
210     my @list = ();
211     foreach my $batch (@$batches) {
212         push @list, {
213             import_batch_id => $batch->{'import_batch_id'},
214             num_records => $batch->{'num_records'},
215             num_items => $batch->{'num_items'},
216             upload_timestamp => $batch->{'upload_timestamp'},
217             import_status => $batch->{'import_status'},
218             file_name => $batch->{'file_name'} || "($batch->{'batch_type'})",
219             comments => $batch->{'comments'},
220             can_clean => ($batch->{'import_status'} ne 'cleaned') ? 1 : 0,
221             record_type => $batch->{'record_type'},
222         };
223     }
224     $template->param(batch_list => \@list); 
225     my $num_batches = GetNumberOfNonZ3950ImportBatches();
226     add_page_numbers($template, $offset, $results_per_page, $num_batches);
227     $template->param(offset => $offset);
228     $template->param(range_top => $offset + $results_per_page - 1);
229     $template->param(num_results => $num_batches);
230     $template->param(results_per_page => $results_per_page);
231
232 }
233
234 sub commit_batch {
235     my ($template, $import_batch_id, $framework) = @_;
236
237     my $job = undef;
238     $dbh->{AutoCommit} = 0;
239     my $callback = sub {};
240     if ($runinbackground) {
241         $job = put_in_background($import_batch_id);
242         $callback = progress_callback($job, $dbh);
243     }
244     my ($num_added, $num_updated, $num_items_added, $num_items_errored, $num_ignored) = 
245         BatchCommitRecords($import_batch_id, $framework, 50, $callback);
246     $dbh->commit();
247
248     my $results = {
249         did_commit => 1,
250         num_added => $num_added,
251         num_updated => $num_updated,
252         num_items_added => $num_items_added,
253         num_items_errored => $num_items_errored,
254         num_ignored => $num_ignored
255     };
256     if ($runinbackground) {
257         $job->finish($results);
258     } else {
259         add_results_to_template($template, $results);
260     }
261 }
262
263 sub revert_batch {
264     my ($template, $import_batch_id) = @_;
265
266     $dbh->{AutoCommit} = 0;
267     my $job = undef;
268     my $callback = sub {};
269     if ($runinbackground) {
270         $job = put_in_background($import_batch_id);
271         $callback = progress_callback($job, $dbh);
272     }
273     my ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored) = 
274         BatchRevertRecords($import_batch_id, 50, $callback);
275     $dbh->commit();
276
277     my $results = {
278         did_revert => 1,
279         num_deleted => $num_deleted,
280         num_items_deleted => $num_items_deleted,
281         num_errors => $num_errors,
282         num_reverted => $num_reverted,
283         num_ignored => $num_ignored,
284     };
285     if ($runinbackground) {
286         $job->finish($results);
287     } else {
288         add_results_to_template($template, $results);
289     }
290 }
291
292 sub put_in_background {
293     my $import_batch_id = shift;
294
295     my $batch = GetImportBatch($import_batch_id);
296     my $job = C4::BackgroundJob->new($sessionID, $batch->{'file_name'}, $ENV{'SCRIPT_NAME'}, $batch->{'num_records'});
297     my $jobID = $job->id();
298
299     # fork off
300     if (my $pid = fork) {
301         # parent
302         # return job ID as JSON
303
304         # prevent parent exiting from
305         # destroying the kid's database handle
306         # FIXME: according to DBI doc, this may not work for Oracle
307         $dbh->{InactiveDestroy}  = 1;
308
309         my $reply = CGI->new("");
310         print $reply->header(-type => 'text/html');
311         print '{"jobID":"' . $jobID . '"}';
312         exit 0;
313     } elsif (defined $pid) {
314         # child
315         # close STDOUT to signal to Apache that
316         # we're now running in the background
317         close STDOUT;
318         close STDERR;
319     } else {
320         # fork failed, so exit immediately
321         warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
322         exit 0;
323     }
324     return $job;
325 }
326
327 sub progress_callback {
328     my $job = shift;
329     my $dbh = shift;
330     return sub {
331         my $progress = shift;
332         $job->progress($progress);
333         $dbh->commit();
334     }
335 }
336
337 sub add_results_to_template {
338     my $template = shift;
339     my $results = shift;
340     $template->param(map { $_ => $results->{$_} } keys %{ $results });
341 }
342
343 sub add_saved_job_results_to_template {
344     my $template = shift;
345     my $completedJobID = shift;
346     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
347     my $results = $job->results();
348     add_results_to_template($template, $results);
349 }
350
351 sub import_records_list {
352     my ($template, $import_batch_id, $offset, $results_per_page) = @_;
353
354     my $batch = GetImportBatch($import_batch_id);
355     my $records = GetImportRecordsRange($import_batch_id, $offset, $results_per_page);
356     my @list = ();
357     foreach my $record (@$records) {
358         my $citation = $record->{'title'} || $record->{'authorized_heading'};
359         $citation .= " $record->{'author'}" if $record->{'author'};
360         $citation .= " (" if $record->{'issn'} or $record->{'isbn'};
361         $citation .= $record->{'isbn'} if $record->{'isbn'};
362         $citation .= ", " if $record->{'issn'} and $record->{'isbn'};
363         $citation .= $record->{'issn'} if $record->{'issn'};
364         $citation .= ")" if $record->{'issn'} or $record->{'isbn'};
365
366         my $match = GetImportRecordMatches($record->{'import_record_id'}, 1);
367         my $match_citation = '';
368         if ($#$match > -1) {
369             if ($match->[0]->{'record_type'} eq 'biblio') {
370                 $match_citation .= $match->[0]->{'title'} if defined($match->[0]->{'title'});
371                 $match_citation .= ' ' . $match->[0]->{'author'} if defined($match->[0]->{'author'});
372             } elsif ($match->[0]->{'record_type'} eq 'auth') {
373                 $match_citation .= $match->[0]->{'authorized_heading'} if defined($match->[0]->{'authorized_heading'});
374             }
375         }
376
377         push @list,
378           { import_record_id         => $record->{'import_record_id'},
379             final_match_id           => $record->{'matched_biblionumber'} || $record->{'matched_authid'},
380             citation                 => $citation,
381             status                   => $record->{'status'},
382             record_sequence          => $record->{'record_sequence'},
383             overlay_status           => $record->{'overlay_status'},
384             # Sorry about the match_id being from the "biblionumber" field;
385             # as it turns out, any match id will go in biblionumber
386             match_id                 => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
387             match_citation           => $match_citation,
388             match_score              => $#$match > -1 ? $match->[0]->{'score'} : 0,
389             record_type              => $record->{'record_type'},
390           };
391     }
392     my $num_records = $batch->{'num_records'};
393     $template->param(record_list => \@list);
394     add_page_numbers($template, $offset, $results_per_page, $num_records);
395     $template->param(offset => $offset);
396     $template->param(range_top => $offset + $results_per_page - 1);
397     $template->param(num_results => $num_records);
398     $template->param(results_per_page => $results_per_page);
399     $template->param(import_batch_id => $import_batch_id);
400     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
401     $template->param("overlay_action_${overlay_action}" => 1);
402     $template->param(overlay_action => $overlay_action);
403     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
404     $template->param("nomatch_action_${nomatch_action}" => 1);
405     $template->param(nomatch_action => $nomatch_action);
406     my $item_action = GetImportBatchItemAction($import_batch_id);
407     $template->param("item_action_${item_action}" => 1);
408     $template->param(item_action => $item_action);
409     batch_info($template, $batch);
410     
411 }
412
413 sub batch_info {
414     my ($template, $batch) = @_;
415     $template->param(batch_info => 1);
416     $template->param(file_name => $batch->{'file_name'});
417     $template->param(comments => $batch->{'comments'});
418     $template->param(import_status => $batch->{'import_status'});
419     $template->param(upload_timestamp => $batch->{'upload_timestamp'});
420     $template->{VARS}->{'record_type'} = $batch->{'record_type'};
421     $template->param(num_records => $batch->{'num_records'});
422     $template->param(num_items => $batch->{'num_items'});
423     if ($batch->{'import_status'} ne 'cleaned') {
424         $template->param(can_clean => 1);
425     }
426     if ($batch->{'num_records'} > 0) {
427         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
428             $template->param(can_commit => 1);
429         }
430         if ($batch->{'import_status'} eq 'imported') {
431             $template->param(can_revert => 1);
432         }
433     }
434     if (defined $batch->{'matcher_id'}) {
435         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
436         if (defined $matcher) {
437             $template->param('current_matcher_id' => $batch->{'matcher_id'});
438             $template->param('current_matcher_code' => $matcher->code());
439             $template->param('current_matcher_description' => $matcher->description());
440         }
441     }
442     add_matcher_list($template,$batch->{'matcher_id'});
443 }
444
445 sub add_matcher_list {
446     my ($template,$current_matcher_id) = @_;
447     my @matchers = C4::Matcher::GetMatcherList();
448     if (defined $current_matcher_id) {
449         for (my $i = 0; $i <= $#matchers; $i++) {
450             if ($matchers[$i]->{'matcher_id'} eq $current_matcher_id) {
451                 $matchers[$i]->{'selected'} = 1;
452             }
453         }
454     }
455     $template->param(available_matchers => \@matchers);
456 }
457
458 sub add_page_numbers {
459     my ($template, $offset, $results_per_page, $total_results) = @_;
460     my $max_pages = POSIX::ceil($total_results / $results_per_page);
461     return if $max_pages < 2;
462     my $current_page = int($offset / $results_per_page) + 1;
463     my @pages = ();
464     for (my $i = 1; $i <= $max_pages; $i++) {
465         push @pages, {
466             page_number => $i,
467             current_page => ($current_page == $i) ? 1 : 0,
468             offset => ($i - 1) * $results_per_page
469         }
470     }
471     $template->param(pages => \@pages);
472 }
473