Fixes bug 4369: Local use does not update datelastseen
[koha.git] / tools / batchMod.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use CGI;
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use C4::Auth;
25 use C4::Output;
26 use C4::Biblio;
27 use C4::Items;
28 use C4::Context;
29 use C4::Koha; # XXX subfield_is_koha_internal_p
30 use C4::Branch; # XXX subfield_is_koha_internal_p
31 use C4::BackgroundJob;
32 use C4::ClassSource;
33 use C4::Dates;
34 use C4::Debug;
35 use YAML;
36 use Switch;
37 use MARC::File::XML;
38
39 my $input = new CGI;
40 my $dbh = C4::Context->dbh;
41 my $error        = $input->param('error');
42 my @itemnumbers  = $input->param('itemnumber');
43 my $op           = $input->param('op');
44 my $del          = $input->param('del');
45 my $completedJobID = $input->param('completedJobID');
46 my $runinbackground = $input->param('runinbackground');
47
48
49 my $template_name;
50 my $template_flag;
51 if (!defined $op) {
52     $template_name = "tools/batchMod.tmpl";
53     $template_flag = { tools => '*' };
54 } else {
55     $template_name = ($del) ? "tools/batchMod-del.tmpl" : "tools/batchMod-edit.tmpl";
56     $template_flag = ($del) ? { tools => 'items_batchdel' }   : { tools => 'items_batchmod' };
57 }
58
59
60 my ($template, $loggedinuser, $cookie)
61     = get_template_and_user({template_name => $template_name,
62                  query => $input,
63                  type => "intranet",
64                  authnotrequired => 0,
65                  flagsrequired => $template_flag,
66                  });
67
68
69 my $today_iso = C4::Dates->today('iso');
70 $template->param(today_iso => $today_iso);
71 $template->param(del       => $del);
72
73 my $itemrecord;
74 my $nextop="";
75 my @errors; # store errors found while checking data BEFORE saving item.
76 my $items_display_hashref;
77 my $frameworkcode="";
78 my $tagslib = &GetMarcStructure(1,$frameworkcode);
79
80 my $deleted_items = 0;     # Numbers of deleted items
81 my $not_deleted_items = 0; # Numbers of items that could not be deleted
82 my @not_deleted;           # List of the itemnumbers that could not be deleted
83
84 my %cookies = parse CGI::Cookie($cookie);
85 my $sessionID = $cookies{'CGISESSID'}->value;
86 my $dbh = C4::Context->dbh;
87
88
89 #--- ----------------------------------------------------------------------------
90 if ($op eq "action") {
91 #-------------------------------------------------------------------------------
92     my @tags      = $input->param('tag');
93     my @subfields = $input->param('subfield');
94     my @values    = $input->param('field_value');
95     # build indicator hash.
96     my @ind_tag   = $input->param('ind_tag');
97     my @indicator = $input->param('indicator');
98
99     # Is there something to modify ?
100     # TODO : We shall use this var to warn the user in case no modification was done to the items
101     my $something_to_modify = scalar(grep {!/^$/} @values);
102
103     # Once the job is done
104     if ($completedJobID) {
105         # If we have a reasonable amount of items, we display them
106         if (scalar(@itemnumbers) <= 1000) {
107             $items_display_hashref=BuildItemsData(@itemnumbers);
108         } else {
109             # Else, we only display the barcode
110             my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
111             $template->param("simple_items_display" => \@simple_items_display);
112         }
113
114         # Setting the job as done
115         my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
116
117         # Calling the template
118         add_saved_job_results_to_template($template, $completedJobID);
119
120     # While the job is getting done
121     } else {
122
123         # Job size is the number of items we have to process
124         my $job_size = scalar(@itemnumbers);
125         my $job = undef;
126         my $callback = sub {};
127
128         # If we asked for background processing
129         if ($runinbackground) {
130             $job = put_in_background($job_size);
131             $callback = progress_callback($job, $dbh);
132         }
133
134         # For each item
135         my $i = 1; 
136         foreach my $itemnumber(@itemnumbers){
137
138                 $job->progress($i) if $runinbackground;
139                 my $itemdata=GetItem($itemnumber);
140                 if ($input->param("del")){
141                         my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
142                         if ($return == 1) {
143                             $deleted_items++;
144                         } else {
145                             $not_deleted_items++;
146                             push @not_deleted, { biblionumber => $itemdata->{'biblionumber'}, itemnumber => $itemdata->{'itemnumber'}, barcode => $itemdata->{'barcode'}, title => $itemdata->{'title'}, $return => 1 };
147                         }
148                 } else {
149                     if ($something_to_modify) {
150                         my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
151                         my $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
152                         my $localitem = TransformMarcToKoha( $dbh, $marcitem, "", 'items' );
153                         my $localmarcitem=Item2Marc($itemdata);
154                         UpdateMarcWith($marcitem,$localmarcitem);
155                         eval{my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($localmarcitem,$itemdata->{biblionumber},$itemnumber)};
156                     }
157                 }
158                 $i++;
159         }
160     }
161 }
162 #
163 #-------------------------------------------------------------------------------
164 # build screen with existing items. and "new" one
165 #-------------------------------------------------------------------------------
166
167 if ($op eq "show"){
168         my $filefh = $input->upload('uploadfile');
169         my $filecontent = $input->param('filecontent');
170         my @notfoundbarcodes;
171
172     my @contentlist;
173     if ($filefh){
174         while (my $content=<$filefh>){
175             chomp $content;
176             push @contentlist, $content if $content;
177         }
178
179         switch ($filecontent) {
180             case "barcode_file" {
181                 foreach my $barcode (@contentlist) {
182
183                     my $itemnumber = GetItemnumberFromBarcode($barcode);
184                     if ($itemnumber) {
185                         push @itemnumbers,$itemnumber;
186                     } else {
187                         push @notfoundbarcodes, $barcode;
188                     }
189                 }
190
191             }
192
193             case "itemid_file" {
194                 @itemnumbers = @contentlist;
195             }
196         }
197     } else {
198        if ( my $list=$input->param('barcodelist')){
199         push my @barcodelist, split(/\s\n/, $list);
200
201         foreach my $barcode (@barcodelist) {
202
203             my $itemnumber = GetItemnumberFromBarcode($barcode);
204             if ($itemnumber) {
205                 push @itemnumbers,$itemnumber;
206             } else {
207                 push @notfoundbarcodes, $barcode;
208             }
209         }
210
211     }
212 }
213     # Only display the items if there are no more than 1000
214     if (scalar(@itemnumbers) <= 1000) {
215         $items_display_hashref=BuildItemsData(@itemnumbers);
216     } else {
217         $template->param("too_many_items" => scalar(@itemnumbers));
218         # Even if we do not display the items, we need the itemnumbers
219         my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
220         $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
221     }
222 # now, build the item form for entering a new item
223 my @loop_data =();
224 my $i=0;
225 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
226
227 my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
228
229 # Adding a default choice, in case the user does not want to modify the branch
230 my @nochange_branch = { branchname => '', value => '', selected => 1 };
231 unshift (@$branches, @nochange_branch);
232
233 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
234
235
236 foreach my $tag (sort keys %{$tagslib}) {
237     # loop through each subfield
238     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
239         next if subfield_is_koha_internal_p($subfield);
240         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
241         # barcode and stocknumber are not meant to be batch-modified
242         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
243         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
244         my %subfield_data;
245  
246         my $index_subfield = int(rand(1000000)); 
247         if ($subfield eq '@'){
248             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
249         } else {
250             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
251         }
252         $subfield_data{tag}        = $tag;
253         $subfield_data{subfield}   = $subfield;
254         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
255     #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
256         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
257         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
258         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
259         my ($x,$value);
260         $value =~ s/"/&quot;/g;
261         unless ($value) {
262             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
263             # get today date & replace YYYY, MM, DD if provided in the default value
264             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
265             $value =~ s/YYYY/$year/g;
266             $value =~ s/MM/$month/g;
267             $value =~ s/DD/$day/g;
268         }
269         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
270         # testing branch value if IndependantBranches.
271
272         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
273         my $attributes          = qq($attributes_no_value value="$value" );
274
275         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
276         my @authorised_values;
277         my %authorised_lib;
278         # builds list, depending on authorised value...
279   
280         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
281             foreach my $thisbranch (@$branches) {
282                 push @authorised_values, $thisbranch->{value};
283                 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
284                 $value = $thisbranch->{value} if $thisbranch->{selected};
285             }
286         }
287         elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
288             push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
289             my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
290             $sth->execute;
291             while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
292                 push @authorised_values, $itemtype;
293                 $authorised_lib{$itemtype} = $description;
294             }
295
296           #---- class_sources
297       }
298       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
299           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
300             
301           my $class_sources = GetClassSources();
302           my $default_source = C4::Context->preference("DefaultClassificationSource");
303           
304           foreach my $class_source (sort keys %$class_sources) {
305               next unless $class_sources->{$class_source}->{'used'} or
306                           ($value and $class_source eq $value)      or
307                           ($class_source eq $default_source);
308               push @authorised_values, $class_source;
309               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
310           }
311                   $value = $default_source unless ($value);
312
313           #---- "true" authorised value
314       }
315       else {
316           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
317           $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
318           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
319               push @authorised_values, $value;
320               $authorised_lib{$value} = $lib;
321           }
322       }
323       $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
324           -name     => "field_value",
325           -values   => \@authorised_values,
326           -default  => $value,
327           -labels   => \%authorised_lib,
328           -override => 1,
329           -size     => 1,
330           -multiple => 0,
331           -tabindex => 1,
332           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
333           -class    => "input_marceditor",
334       );
335     # it's a thesaurus / authority field
336     }
337     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
338         $subfield_data{marc_value} = "<input type=\"text\" $attributes />
339             <a href=\"#\" class=\"buttonDot\"
340                 onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
341     ";
342     # it's a plugin field
343     }
344     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
345         # opening plugin
346         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
347         if (do $plugin) {
348                         my $temp;
349             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
350             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
351             $subfield_data{marc_value} = qq[<input $attributes
352                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
353                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
354                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
355                 $javascript];
356         } else {
357             warn "Plugin Failed: $plugin";
358             $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
359         }
360     }
361     elsif ( $tag eq '' ) {       # it's an hidden field
362         $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
363     }
364     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
365         $subfield_data{marc_value} = qq(<input type="text" $attributes />);
366     }
367     elsif ( length($value) > 100
368             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
369                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
370             or (C4::Context->preference("marcflavour") eq "MARC21"  and
371                   500 <= $tag && $tag < 600                     )
372           ) {
373         # oversize field (textarea)
374         $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
375     } else {
376         # it's a standard field
377          $subfield_data{marc_value} = "<input $attributes />";
378     }
379 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
380     push (@loop_data, \%subfield_data);
381     $i++
382   }
383 } # -- End foreach tag
384
385
386     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
387     $template->param(item => \@loop_data);
388     if (@notfoundbarcodes) { 
389         my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
390         $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
391     }
392     $nextop="action"
393 } # -- End action="show"
394
395 $template->param(%$items_display_hashref) if $items_display_hashref;
396 $template->param(
397     op      => $nextop,
398     $op => 1,
399 );
400
401 if ($op eq "action") {
402
403     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
404
405     $template->param(
406         not_deleted_items => $not_deleted_items,
407         deleted_items => $deleted_items,
408         not_deleted_loop => \@not_deleted 
409     );
410 }
411
412 foreach my $error (@errors) {
413     $template->param($error => 1);
414 }
415 output_html_with_http_headers $input, $cookie, $template->output;
416 exit;
417
418
419 # ---------------- Functions
420
421 sub BuildItemsData{
422         my @itemnumbers=@_;
423                 # now, build existiing item list
424                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
425                 my @big_array;
426                 #---- finds where items.itemnumber is stored
427                 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
428                 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
429                 foreach my $itemnumber (@itemnumbers){
430                         my $itemdata=GetItem($itemnumber);
431                         my $itemmarc=Item2Marc($itemdata);
432                         my %this_row;
433                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
434                                 # loop through each subfield
435                                 if (my $itembranchcode=$field->subfield($branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
436                                                 #verifying rights
437                                                 my $userenv = C4::Context->userenv();
438                                                 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
439                                                                 $this_row{'nomod'}=1;
440                                                 }
441                                 }
442                                 my $tag=$field->tag();
443                                 foreach my $subfield ($field->subfields) {
444                                         my ($subfcode,$subfvalue)=@$subfield;
445                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
446                                                         && $tag        ne $itemtagfield 
447                                                         && $subfcode   ne $itemtagsubfield);
448
449                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
450                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
451                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
452                                                                         $subfcode, $subfvalue, '', $tagslib) 
453                                                                         || $subfvalue;
454                                         }
455
456                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
457                                 }
458                         }
459
460             # grab title, author, and ISBN to identify bib that the item
461             # belongs to in the display
462                         my $biblio=GetBiblioData($$itemdata{biblionumber});
463             $this_row{bibinfo} = join("\n", @$biblio{qw(title author ISBN)});
464
465                         if (%this_row) {
466                                 push(@big_array, \%this_row);
467                         }
468                 }
469                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
470
471                 # now, construct template !
472                 # First, the existing items for display
473                 my @item_value_loop;
474                 my @witnesscodessorted=sort keys %witness;
475                 for my $row ( @big_array ) {
476                         my %row_data;
477                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
478                         $row_data{item_value} = [ @item_fields ];
479                         $row_data{itemnumber} = $row->{itemnumber};
480                         #reporting this_row values
481                         $row_data{'nomod'} = $row->{'nomod'};
482             $row_data{bibinfo} = $row->{bibinfo};
483                         push(@item_value_loop,\%row_data);
484                 }
485                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
486
487         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
488 }
489
490 #BE WARN : it is not the general case 
491 # This function can be OK in the item marc record special case
492 # Where subfield is not repeated
493 # And where we are sure that field should correspond
494 # And $tag>10
495 sub UpdateMarcWith($$){
496   my ($marcfrom,$marcto)=@_;
497   #warn "FROM :",$marcfrom->as_formatted;
498         my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
499         my $fieldfrom=$marcfrom->field($itemtag);
500         my @fields_to=$marcto->field($itemtag);
501     foreach my $subfield ($fieldfrom->subfields()){
502                 foreach my $field_to_update (@fields_to){
503                                 $field_to_update->update($$subfield[0]=>$$subfield[1]) if ($$subfield[1]);
504                 }
505     }
506   #warn "TO edited:",$marcto->as_formatted;
507 }
508
509 sub find_value {
510     my ($tagfield,$insubfield,$record) = @_;
511     my $result;
512     my $indicator;
513     foreach my $field ($record->field($tagfield)) {
514         my @subfields = $field->subfields();
515         foreach my $subfield (@subfields) {
516             if (@$subfield[0] eq $insubfield) {
517                 $result .= @$subfield[1];
518                 $indicator = $field->indicator(1).$field->indicator(2);
519             }
520         }
521     }
522     return($indicator,$result);
523 }
524
525 # ----------------------------
526 # Background functions
527
528
529 sub add_results_to_template {
530     my $template = shift;
531     my $results = shift;
532     $template->param(map { $_ => $results->{$_} } keys %{ $results });
533 }
534
535 sub add_saved_job_results_to_template {
536     my $template = shift;
537     my $completedJobID = shift;
538     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
539     my $results = $job->results();
540     add_results_to_template($template, $results);
541 }
542
543 sub put_in_background {
544     my $job_size = shift;
545
546     my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
547     my $jobID = $job->id();
548
549     # fork off
550     if (my $pid = fork) {
551         # parent
552         # return job ID as JSON
553
554         # prevent parent exiting from
555         # destroying the kid's database handle
556         # FIXME: according to DBI doc, this may not work for Oracle
557         $dbh->{InactiveDestroy}  = 1;
558
559         my $reply = CGI->new("");
560         print $reply->header(-type => 'text/html');
561         print "{ jobID: '$jobID' }";
562         exit 0;
563     } elsif (defined $pid) {
564         # child
565         # close STDOUT to signal to Apache that
566         # we're now running in the background
567         close STDOUT;
568         close STDERR;
569     } else {
570         # fork failed, so exit immediately
571         warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
572         exit 0;
573     }
574     return $job;
575 }
576
577 sub progress_callback {
578     my $job = shift;
579     my $dbh = shift;
580     return sub {
581         my $progress = shift;
582         $job->progress($progress);
583     }
584 }
585
586