Bug 19697: Move template JavaScript to the footer: Search results
[koha.git] / tools / batchMod.pl
blob0ab4db76d965ddd4e651262ae9a6c4cc275d191a
1 #!/usr/bin/perl
4 # Copyright 2000-2002 Katipo Communications
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 use CGI qw ( -utf8 );
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::Circulation;
29 use C4::Context;
30 use C4::Koha;
31 use C4::BackgroundJob;
32 use C4::ClassSource;
33 use C4::Debug;
34 use C4::Members;
35 use MARC::File::XML;
36 use List::MoreUtils qw/uniq/;
38 use Koha::Biblios;
39 use Koha::DateUtils;
40 use Koha::Items;
41 use Koha::ItemTypes;
42 use Koha::Patrons;
44 my $input = new CGI;
45 my $dbh = C4::Context->dbh;
46 my $error = $input->param('error');
47 my @itemnumbers = $input->multi_param('itemnumber');
48 my $biblionumber = $input->param('biblionumber');
49 my $op = $input->param('op');
50 my $del = $input->param('del');
51 my $del_records = $input->param('del_records');
52 my $completedJobID = $input->param('completedJobID');
53 my $runinbackground = $input->param('runinbackground');
54 my $src = $input->param('src');
55 my $use_default_values = $input->param('use_default_values');
57 my $template_name;
58 my $template_flag;
59 if (!defined $op) {
60 $template_name = "tools/batchMod.tt";
61 $template_flag = { tools => '*' };
62 $op = q{};
63 } else {
64 $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
65 $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' };
69 my ($template, $loggedinuser, $cookie)
70 = get_template_and_user({template_name => $template_name,
71 query => $input,
72 type => "intranet",
73 authnotrequired => 0,
74 flagsrequired => $template_flag,
75 });
77 # Does the user have a restricted item edition permission?
78 my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
79 my $restrictededition = $uid ? haspermission($uid, {'tools' => 'items_batchmod_restricted'}) : undef;
80 # In case user is a superlibrarian, edition is not restricted
81 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
83 $template->param(del => $del);
85 my $itemrecord;
86 my $nextop="";
87 my @errors; # store errors found while checking data BEFORE saving item.
88 my $items_display_hashref;
89 our $tagslib = &GetMarcStructure(1);
91 my $deleted_items = 0; # Number of deleted items
92 my $deleted_records = 0; # Number of deleted records ( with no items attached )
93 my $not_deleted_items = 0; # Number of items that could not be deleted
94 my @not_deleted; # List of the itemnumbers that could not be deleted
95 my $modified_items = 0; # Numbers of modified items
96 my $modified_fields = 0; # Numbers of modified fields
98 my %cookies = parse CGI::Cookie($cookie);
99 my $sessionID = $cookies{'CGISESSID'}->value;
102 #--- ----------------------------------------------------------------------------
103 if ($op eq "action") {
104 #-------------------------------------------------------------------------------
105 my @tags = $input->multi_param('tag');
106 my @subfields = $input->multi_param('subfield');
107 my @values = $input->multi_param('field_value');
108 my @disabled = $input->multi_param('disable_input');
109 # build indicator hash.
110 my @ind_tag = $input->multi_param('ind_tag');
111 my @indicator = $input->multi_param('indicator');
113 # Is there something to modify ?
114 # TODO : We shall use this var to warn the user in case no modification was done to the items
115 my $values_to_modify = scalar(grep {!/^$/} @values);
116 my $values_to_blank = scalar(@disabled);
117 my $marcitem;
119 # Once the job is done
120 if ($completedJobID) {
121 # If we have a reasonable amount of items, we display them
122 if (scalar(@itemnumbers) <= ( C4::Context->preference("MaxItemsToDisplayForBatchDel") // 1000 ) ) {
123 $items_display_hashref=BuildItemsData(@itemnumbers);
124 } else {
125 # Else, we only display the barcode
126 my @simple_items_display = map {
127 my $itemnumber = $_;
128 my $item = Koha::Items->find($itemnumber);
130 itemnumber => $itemnumber,
131 barcode => $item ? ( $item->barcode // q{} ) : q{},
132 biblionumber => $item ? $item->biblio->biblionumber : q{},
134 } @itemnumbers;
135 $template->param("simple_items_display" => \@simple_items_display);
138 # Setting the job as done
139 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
141 # Calling the template
142 add_saved_job_results_to_template($template, $completedJobID);
144 } else {
145 # While the job is getting done
147 # Job size is the number of items we have to process
148 my $job_size = scalar(@itemnumbers);
149 my $job = undef;
151 # If we asked for background processing
152 if ($runinbackground) {
153 $job = put_in_background($job_size);
156 #initializing values for updates
157 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
158 if ($values_to_modify){
159 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
160 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
162 if ($values_to_blank){
163 foreach my $disabledsubf (@disabled){
164 if ($marcitem && $marcitem->field($itemtagfield)){
165 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
167 else {
168 $marcitem = MARC::Record->new();
169 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
174 # For each item
175 my $i = 1;
176 foreach my $itemnumber(@itemnumbers){
178 $job->progress($i) if $runinbackground;
179 my $itemdata = GetItem($itemnumber);
180 if ( $del ){
181 my $return = DelItemCheck( $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
182 if ($return == 1) {
183 $deleted_items++;
184 } else {
185 $not_deleted_items++;
186 push @not_deleted,
187 { biblionumber => $itemdata->{'biblionumber'},
188 itemnumber => $itemdata->{'itemnumber'},
189 barcode => $itemdata->{'barcode'},
190 title => $itemdata->{'title'},
191 $return => 1
195 # If there are no items left, delete the biblio
196 if ( $del_records ) {
197 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
198 if ( $itemscount == 0 ) {
199 my $error = DelBiblio($itemdata->{'biblionumber'});
200 $deleted_records++ unless ( $error );
203 } else {
204 if ($values_to_modify || $values_to_blank) {
205 my $localmarcitem = Item2Marc($itemdata);
207 my $modified = UpdateMarcWith( $marcitem, $localmarcitem );
208 if ( $modified ) {
209 eval {
210 if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
211 LostItem($itemnumber) if $item->{itemlost} and not $itemdata->{itemlost};
215 if ( $runinbackground ) {
216 $modified_items++ if $modified;
217 $modified_fields += $modified;
218 $job->set({
219 modified_items => $modified_items,
220 modified_fields => $modified_fields,
225 $i++;
230 #-------------------------------------------------------------------------------
231 # build screen with existing items. and "new" one
232 #-------------------------------------------------------------------------------
234 if ($op eq "show"){
235 my $filefh = $input->upload('uploadfile');
236 my $filecontent = $input->param('filecontent');
237 my @notfoundbarcodes;
239 my @contentlist;
240 if ($filefh){
241 while (my $content=<$filefh>){
242 $content =~ s/[\r\n]*$//;
243 push @contentlist, $content if $content;
246 if ($filecontent eq 'barcode_file') {
247 foreach my $barcode (@contentlist) {
249 my $itemnumber = GetItemnumberFromBarcode($barcode);
250 if ($itemnumber) {
251 push @itemnumbers,$itemnumber;
252 } else {
253 push @notfoundbarcodes, $barcode;
257 elsif ( $filecontent eq 'itemid_file') {
258 @itemnumbers = @contentlist;
260 } else {
261 if (defined $biblionumber){
262 my @all_items = GetItemsInfo( $biblionumber );
263 foreach my $itm (@all_items) {
264 push @itemnumbers, $itm->{itemnumber};
267 if ( my $list=$input->param('barcodelist')){
268 push my @barcodelist, uniq( split(/\s\n/, $list) );
270 foreach my $barcode (@barcodelist) {
272 my $itemnumber = GetItemnumberFromBarcode($barcode);
273 if ($itemnumber) {
274 push @itemnumbers,$itemnumber;
275 } else {
276 push @notfoundbarcodes, $barcode;
283 # Flag to tell the template there are valid results, hidden or not
284 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
285 # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
286 my $max_items = $del
287 ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
288 : C4::Context->preference("MaxItemsToProcessForBatchMod");
289 if (scalar(@itemnumbers) <= ( $max_items // 1000 ) ) {
290 $items_display_hashref=BuildItemsData(@itemnumbers);
291 } else {
292 $template->param("too_many_items" => scalar(@itemnumbers));
293 # Even if we do not display the items, we need the itemnumbers
294 $template->param(itemnumbers_array => \@itemnumbers);
296 # now, build the item form for entering a new item
297 my @loop_data =();
298 my $i=0;
299 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
300 my $query = qq{SELECT authorised_value, lib FROM authorised_values};
301 $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id ) } if $branch_limit;
302 $query .= qq{ WHERE category = ?};
303 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL ) } if $branch_limit;
304 $query .= qq{ GROUP BY lib ORDER BY lib, lib_opac};
305 my $authorised_values_sth = $dbh->prepare( $query );
307 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
309 # Adding a default choice, in case the user does not want to modify the branch
310 my $nochange_branch = { branchname => '', value => '', selected => 1 };
311 unshift (@$libraries, $nochange_branch);
313 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
315 # Getting list of subfields to keep when restricted batchmod edit is enabled
316 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
317 my $allowAllSubfields = (
318 not defined $subfieldsToAllowForBatchmod
319 or $subfieldsToAllowForBatchmod == q||
320 ) ? 1 : 0;
321 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
323 foreach my $tag (sort keys %{$tagslib}) {
324 # loop through each subfield
325 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
326 next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
327 next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
328 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
329 # barcode and stocknumber are not meant to be batch-modified
330 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
331 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
332 my %subfield_data;
334 my $index_subfield = int(rand(1000000));
335 if ($subfield eq '@'){
336 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
337 } else {
338 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
340 $subfield_data{tag} = $tag;
341 $subfield_data{subfield} = $subfield;
342 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
343 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
344 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
345 my ($x,$value);
346 $value =~ s/"/&quot;/g;
347 if ( !$value && $use_default_values) {
348 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
349 # get today date & replace YYYY, MM, DD if provided in the default value
350 my $today = dt_from_string;
351 my $year = $today->year;
352 my $month = $today->month;
353 my $day = $today->day;
354 $value =~ s/YYYY/$year/g;
355 $value =~ s/MM/$month/g;
356 $value =~ s/DD/$day/g;
358 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
359 # testing branch value if IndependentBranches.
361 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
362 my @authorised_values;
363 my %authorised_lib;
364 # builds list, depending on authorised value...
366 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
367 foreach my $library (@$libraries) {
368 push @authorised_values, $library->{branchcode};
369 $authorised_lib{$library->{branchcode}} = $library->{branchname};
371 $value = "";
373 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
374 push @authorised_values, "";
375 my $itemtypes = Koha::ItemTypes->search_with_localization;
376 while ( my $itemtype = $itemtypes->next ) {
377 push @authorised_values, $itemtype->itemtype;
378 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
380 $value = "";
382 #---- class_sources
384 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
385 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
387 my $class_sources = GetClassSources();
388 my $default_source = C4::Context->preference("DefaultClassificationSource");
390 foreach my $class_source (sort keys %$class_sources) {
391 next unless $class_sources->{$class_source}->{'used'} or
392 ($value and $class_source eq $value) or
393 ($class_source eq $default_source);
394 push @authorised_values, $class_source;
395 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
397 $value = '';
399 #---- "true" authorised value
401 else {
402 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
403 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value}, $branch_limit ? $branch_limit : () );
404 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
405 push @authorised_values, $value;
406 $authorised_lib{$value} = $lib;
408 $value="";
410 $subfield_data{marc_value} = {
411 type => 'select',
412 id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
413 name => "field_value",
414 values => \@authorised_values,
415 labels => \%authorised_lib,
416 default => $value,
418 # it's a thesaurus / authority field
420 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
421 $subfield_data{marc_value} = {
422 type => 'text1',
423 id => $subfield_data{id},
424 value => $value,
425 authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
428 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
429 require Koha::FrameworkPlugin;
430 my $plugin = Koha::FrameworkPlugin->new( {
431 name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
432 item_style => 1,
434 my $temp;
435 my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
436 id => $subfield_data{id}, tabloop => \@loop_data };
437 $plugin->build( $pars );
438 if( !$plugin->errstr ) {
439 $subfield_data{marc_value} = {
440 type => 'text2',
441 id => $subfield_data{id},
442 value => $value,
443 javascript => $plugin->javascript,
444 noclick => $plugin->noclick,
446 } else {
447 warn $plugin->errstr;
448 $subfield_data{marc_value} = { # supply default input form
449 type => 'text',
450 id => $subfield_data{id},
451 value => $value,
455 elsif ( $tag eq '' ) { # it's an hidden field
456 $subfield_data{marc_value} = {
457 type => 'hidden',
458 id => $subfield_data{id},
459 value => $value,
462 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
463 $subfield_data{marc_value} = {
464 type => 'text',
465 id => $subfield_data{id},
466 value => $value,
469 elsif ( length($value) > 100
470 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
471 300 <= $tag && $tag < 400 && $subfield eq 'a' )
472 or (C4::Context->preference("marcflavour") eq "MARC21" and
473 500 <= $tag && $tag < 600 )
475 # oversize field (textarea)
476 $subfield_data{marc_value} = {
477 type => 'textarea',
478 id => $subfield_data{id},
479 value => $value,
481 } else {
482 # it's a standard field
483 $subfield_data{marc_value} = {
484 type => 'text',
485 id => $subfield_data{id},
486 value => $value,
489 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
490 push (@loop_data, \%subfield_data);
491 $i++
493 } # -- End foreach tag
494 $authorised_values_sth->finish;
498 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
499 $template->param(item => \@loop_data);
500 if (@notfoundbarcodes) {
501 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
502 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
504 $nextop="action"
505 } # -- End action="show"
507 $template->param(%$items_display_hashref) if $items_display_hashref;
508 $template->param(
509 op => $nextop,
511 $template->param( $op => 1 ) if $op;
513 if ($op eq "action") {
515 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
517 $template->param(
518 not_deleted_items => $not_deleted_items,
519 deleted_items => $deleted_items,
520 delete_records => $del_records,
521 deleted_records => $deleted_records,
522 not_deleted_loop => \@not_deleted
526 foreach my $error (@errors) {
527 $template->param($error => 1) if $error;
529 $template->param(src => $src);
530 $template->param(biblionumber => $biblionumber);
531 output_html_with_http_headers $input, $cookie, $template->output;
532 exit;
535 # ---------------- Functions
537 sub BuildItemsData{
538 my @itemnumbers=@_;
539 # now, build existiing item list
540 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
541 my @big_array;
542 #---- finds where items.itemnumber is stored
543 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
544 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
545 foreach my $itemnumber (@itemnumbers){
546 my $itemdata=GetItem($itemnumber);
547 my $itemmarc=Item2Marc($itemdata);
548 my %this_row;
549 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
550 # loop through each subfield
551 my $itembranchcode=$field->subfield($branchtagsubfield);
552 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
553 #verifying rights
554 my $userenv = C4::Context->userenv();
555 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
556 $this_row{'nomod'}=1;
559 my $tag=$field->tag();
560 foreach my $subfield ($field->subfields) {
561 my ($subfcode,$subfvalue)=@$subfield;
562 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
563 && $tag ne $itemtagfield
564 && $subfcode ne $itemtagsubfield);
566 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
567 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
568 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
569 $subfcode, $subfvalue, '', $tagslib)
570 || $subfvalue;
573 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
577 # grab title, author, and ISBN to identify bib that the item
578 # belongs to in the display
579 my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
580 $this_row{title} = $biblio->title;
581 $this_row{author} = $biblio->author;
582 $this_row{isbn} = $biblio->biblioitem->isbn;
583 $this_row{biblionumber} = $biblio->biblionumber;
585 if (%this_row) {
586 push(@big_array, \%this_row);
589 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
591 # now, construct template !
592 # First, the existing items for display
593 my @item_value_loop;
594 my @witnesscodessorted=sort keys %witness;
595 for my $row ( @big_array ) {
596 my %row_data;
597 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
598 $row_data{item_value} = [ @item_fields ];
599 $row_data{itemnumber} = $row->{itemnumber};
600 #reporting this_row values
601 $row_data{'nomod'} = $row->{'nomod'};
602 $row_data{bibinfo} = $row->{bibinfo};
603 $row_data{author} = $row->{author};
604 $row_data{title} = $row->{title};
605 $row_data{isbn} = $row->{isbn};
606 $row_data{biblionumber} = $row->{biblionumber};
607 my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
608 $row_data{onloan} = $is_on_loan ? 1 : 0;
609 push(@item_value_loop,\%row_data);
611 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
613 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
616 #BE WARN : it is not the general case
617 # This function can be OK in the item marc record special case
618 # Where subfield is not repeated
619 # And where we are sure that field should correspond
620 # And $tag>10
621 sub UpdateMarcWith {
622 my ($marcfrom,$marcto)=@_;
623 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
624 my $fieldfrom=$marcfrom->field($itemtag);
625 my @fields_to=$marcto->field($itemtag);
626 my $modified = 0;
627 foreach my $subfield ( $fieldfrom->subfields() ) {
628 foreach my $field_to_update ( @fields_to ) {
629 if ( $subfield->[1] ) {
630 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
631 $modified++;
632 $field_to_update->update( $subfield->[0] => $subfield->[1] );
635 else {
636 $modified++;
637 $field_to_update->delete_subfield( code => $subfield->[0] );
641 return $modified;
644 sub find_value {
645 my ($tagfield,$insubfield,$record) = @_;
646 my $result;
647 my $indicator;
648 foreach my $field ($record->field($tagfield)) {
649 my @subfields = $field->subfields();
650 foreach my $subfield (@subfields) {
651 if (@$subfield[0] eq $insubfield) {
652 $result .= @$subfield[1];
653 $indicator = $field->indicator(1).$field->indicator(2);
657 return($indicator,$result);
660 # ----------------------------
661 # Background functions
664 sub add_results_to_template {
665 my $template = shift;
666 my $results = shift;
667 $template->param(map { $_ => $results->{$_} } keys %{ $results });
670 sub add_saved_job_results_to_template {
671 my $template = shift;
672 my $completedJobID = shift;
673 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
674 my $results = $job->results();
675 add_results_to_template($template, $results);
677 my $fields = $job->get("modified_fields");
678 my $items = $job->get("modified_items");
679 $template->param(
680 modified_items => $items,
681 modified_fields => $fields,
685 sub put_in_background {
686 my $job_size = shift;
688 my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
689 my $jobID = $job->id();
691 # fork off
692 if (my $pid = fork) {
693 # parent
694 # return job ID as JSON
696 # prevent parent exiting from
697 # destroying the kid's database handle
698 # FIXME: according to DBI doc, this may not work for Oracle
699 $dbh->{InactiveDestroy} = 1;
701 my $reply = CGI->new("");
702 print $reply->header(-type => 'text/html');
703 print '{"jobID":"' . $jobID . '"}';
704 exit 0;
705 } elsif (defined $pid) {
706 # child
707 # close STDOUT to signal to Apache that
708 # we're now running in the background
709 close STDOUT;
710 close STDERR;
711 } else {
712 # fork failed, so exit immediately
713 warn "fork failed while attempting to run tools/batchMod.pl as a background job";
714 exit 0;
716 return $job;