More work on 'conversion' script for HTML::Toolkit to Template::Tolkit
[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 Switch;
36 use MARC::File::XML;
37
38 my $input = new CGI;
39 my $dbh = C4::Context->dbh;
40 my $error        = $input->param('error');
41 my @itemnumbers  = $input->param('itemnumber');
42 my $op           = $input->param('op');
43 my $del          = $input->param('del');
44 my $completedJobID = $input->param('completedJobID');
45 my $runinbackground = $input->param('runinbackground');
46
47
48 my $template_name;
49 my $template_flag;
50 if (!defined $op) {
51     $template_name = "tools/batchMod.tmpl";
52     $template_flag = { tools => '*' };
53 } else {
54     $template_name = ($del) ? "tools/batchMod-del.tmpl" : "tools/batchMod-edit.tmpl";
55     $template_flag = ($del) ? { tools => 'items_batchdel' }   : { tools => 'items_batchmod' };
56 }
57
58
59 my ($template, $loggedinuser, $cookie)
60     = get_template_and_user({template_name => $template_name,
61                  query => $input,
62                  type => "intranet",
63                  authnotrequired => 0,
64                  flagsrequired => $template_flag,
65                  });
66
67
68 my $today_iso = C4::Dates->today('iso');
69 $template->param(today_iso => $today_iso);
70 $template->param(del       => $del);
71
72 my $itemrecord;
73 my $nextop="";
74 my @errors; # store errors found while checking data BEFORE saving item.
75 my $items_display_hashref;
76 my $frameworkcode="";
77 my $tagslib = &GetMarcStructure(1,$frameworkcode);
78
79 my $deleted_items = 0;     # Numbers of deleted items
80 my $not_deleted_items = 0; # Numbers of items that could not be deleted
81 my @not_deleted;           # List of the itemnumbers that could not be deleted
82
83 my %cookies = parse CGI::Cookie($cookie);
84 my $sessionID = $cookies{'CGISESSID'}->value;
85 my $dbh = C4::Context->dbh;
86
87
88 #--- ----------------------------------------------------------------------------
89 if ($op eq "action") {
90 #-------------------------------------------------------------------------------
91     my @tags      = $input->param('tag');
92     my @subfields = $input->param('subfield');
93     my @values    = $input->param('field_value');
94     # build indicator hash.
95     my @ind_tag   = $input->param('ind_tag');
96     my @indicator = $input->param('indicator');
97
98     # Is there something to modify ?
99     # TODO : We shall use this var to warn the user in case no modification was done to the items
100     my $something_to_modify = scalar(grep {!/^$/} @values);
101
102     # Once the job is done
103     if ($completedJobID) {
104         # If we have a reasonable amount of items, we display them
105         if (scalar(@itemnumbers) <= 1000) {
106             $items_display_hashref=BuildItemsData(@itemnumbers);
107         } else {
108             # Else, we only display the barcode
109             my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
110             $template->param("simple_items_display" => \@simple_items_display);
111         }
112
113         # Setting the job as done
114         my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
115
116         # Calling the template
117         add_saved_job_results_to_template($template, $completedJobID);
118
119     # While the job is getting done
120     } else {
121
122         # Job size is the number of items we have to process
123         my $job_size = scalar(@itemnumbers);
124         my $job = undef;
125         my $callback = sub {};
126
127         # If we asked for background processing
128         if ($runinbackground) {
129             $job = put_in_background($job_size);
130             $callback = progress_callback($job, $dbh);
131         }
132
133         # For each item
134         my $i = 1; 
135         foreach my $itemnumber(@itemnumbers){
136
137                 $job->progress($i) if $runinbackground;
138                 my $itemdata=GetItem($itemnumber);
139                 if ($input->param("del")){
140                         my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
141                         if ($return == 1) {
142                             $deleted_items++;
143                         } else {
144                             $not_deleted_items++;
145                             push @not_deleted, { biblionumber => $itemdata->{'biblionumber'}, itemnumber => $itemdata->{'itemnumber'}, barcode => $itemdata->{'barcode'}, title => $itemdata->{'title'}, $return => 1 };
146                         }
147                 } else {
148                     if ($something_to_modify) {
149                         my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
150                         my $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
151                         my $localitem = TransformMarcToKoha( $dbh, $marcitem, "", 'items' );
152                         my $localmarcitem=Item2Marc($itemdata);
153                         UpdateMarcWith($marcitem,$localmarcitem);
154                         eval{my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($localmarcitem,$itemdata->{biblionumber},$itemnumber)};
155                     }
156                 }
157                 $i++;
158         }
159     }
160 }
161 #
162 #-------------------------------------------------------------------------------
163 # build screen with existing items. and "new" one
164 #-------------------------------------------------------------------------------
165
166 if ($op eq "show"){
167         my $filefh = $input->upload('uploadfile');
168         my $filecontent = $input->param('filecontent');
169         my @notfoundbarcodes;
170
171     my @contentlist;
172     if ($filefh){
173         while (my $content=<$filefh>){
174             chomp $content;
175             push @contentlist, $content if $content;
176         }
177
178         switch ($filecontent) {
179             case "barcode_file" {
180                 foreach my $barcode (@contentlist) {
181
182                     my $itemnumber = GetItemnumberFromBarcode($barcode);
183                     if ($itemnumber) {
184                         push @itemnumbers,$itemnumber;
185                     } else {
186                         push @notfoundbarcodes, $barcode;
187                     }
188                 }
189
190             }
191
192             case "itemid_file" {
193                 @itemnumbers = @contentlist;
194             }
195         }
196     } else {
197        if ( my $list=$input->param('barcodelist')){
198         push my @barcodelist, split(/\s\n/, $list);
199
200         foreach my $barcode (@barcodelist) {
201
202             my $itemnumber = GetItemnumberFromBarcode($barcode);
203             if ($itemnumber) {
204                 push @itemnumbers,$itemnumber;
205             } else {
206                 push @notfoundbarcodes, $barcode;
207             }
208         }
209
210     }
211 }
212     # Only display the items if there are no more than 1000
213     if (scalar(@itemnumbers) <= 1000) {
214         $items_display_hashref=BuildItemsData(@itemnumbers);
215     } else {
216         $template->param("too_many_items" => scalar(@itemnumbers));
217         # Even if we do not display the items, we need the itemnumbers
218         my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
219         $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
220     }
221 # now, build the item form for entering a new item
222 my @loop_data =();
223 my $i=0;
224 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
225
226 my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
227
228 # Adding a default choice, in case the user does not want to modify the branch
229 my $nochange_branch = { branchname => '', value => '', selected => 1 };
230 unshift (@$branches, $nochange_branch);
231
232 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
233
234
235 foreach my $tag (sort keys %{$tagslib}) {
236     # loop through each subfield
237     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
238         next if subfield_is_koha_internal_p($subfield);
239         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
240         # barcode and stocknumber are not meant to be batch-modified
241         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
242         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
243         my %subfield_data;
244  
245         my $index_subfield = int(rand(1000000)); 
246         if ($subfield eq '@'){
247             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
248         } else {
249             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
250         }
251         $subfield_data{tag}        = $tag;
252         $subfield_data{subfield}   = $subfield;
253         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
254     #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
255         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
256         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
257         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
258         my ($x,$value);
259         $value =~ s/"/&quot;/g;
260         unless ($value) {
261             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
262             # get today date & replace YYYY, MM, DD if provided in the default value
263             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
264             $value =~ s/YYYY/$year/g;
265             $value =~ s/MM/$month/g;
266             $value =~ s/DD/$day/g;
267         }
268         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
269         # testing branch value if IndependantBranches.
270
271         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
272         my $attributes          = qq($attributes_no_value value="$value" );
273
274         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
275         my @authorised_values;
276         my %authorised_lib;
277         # builds list, depending on authorised value...
278   
279         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
280             foreach my $thisbranch (@$branches) {
281                 push @authorised_values, $thisbranch->{value};
282                 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
283             }
284         $value = "";
285         }
286         elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
287             push @authorised_values, "";
288             my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
289             $sth->execute;
290             while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
291                 push @authorised_values, $itemtype;
292                 $authorised_lib{$itemtype} = $description;
293             }
294         $value = "";
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 = '';
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