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