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