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