Bug 25592: Add Devinim to about page
[koha.git] / tools / batchMod.pl
blob91ede79b1e252496b9e40e6cc6d75d355be5f9fa
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 Modern::Perl;
23 use Try::Tiny;
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Circulation;
30 use C4::Context;
31 use C4::Koha;
32 use C4::BackgroundJob;
33 use C4::ClassSource;
34 use C4::Debug;
35 use C4::Members;
36 use MARC::File::XML;
37 use List::MoreUtils qw/uniq/;
39 use Koha::Database;
40 use Koha::Exceptions::Exception;
41 use Koha::AuthorisedValues;
42 use Koha::Biblios;
43 use Koha::DateUtils;
44 use Koha::Items;
45 use Koha::ItemTypes;
46 use Koha::Patrons;
48 my $input = new CGI;
49 my $dbh = C4::Context->dbh;
50 my $error = $input->param('error');
51 my @itemnumbers = $input->multi_param('itemnumber');
52 my $biblionumber = $input->param('biblionumber');
53 my $op = $input->param('op');
54 my $del = $input->param('del');
55 my $del_records = $input->param('del_records');
56 my $completedJobID = $input->param('completedJobID');
57 my $runinbackground = $input->param('runinbackground');
58 my $src = $input->param('src');
59 my $use_default_values = $input->param('use_default_values');
61 my $template_name;
62 my $template_flag;
63 if (!defined $op) {
64 $template_name = "tools/batchMod.tt";
65 $template_flag = { tools => '*' };
66 $op = q{};
67 } else {
68 $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
69 $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' };
73 my ($template, $loggedinuser, $cookie)
74 = get_template_and_user({template_name => $template_name,
75 query => $input,
76 type => "intranet",
77 authnotrequired => 0,
78 flagsrequired => $template_flag,
79 });
81 # Does the user have a restricted item edition permission?
82 my $uid = $loggedinuser ? Koha::Patrons->find( $loggedinuser )->userid : undef;
83 my $restrictededition = $uid ? haspermission($uid, {'tools' => 'items_batchmod_restricted'}) : undef;
84 # In case user is a superlibrarian, edition is not restricted
85 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
87 $template->param(del => $del);
89 my $itemrecord;
90 my $nextop="";
91 my @errors; # store errors found while checking data BEFORE saving item.
92 my $items_display_hashref;
93 our $tagslib = &GetMarcStructure(1);
95 my $deleted_items = 0; # Number of deleted items
96 my $deleted_records = 0; # Number of deleted records ( with no items attached )
97 my $not_deleted_items = 0; # Number of items that could not be deleted
98 my @not_deleted; # List of the itemnumbers that could not be deleted
99 my $modified_items = 0; # Numbers of modified items
100 my $modified_fields = 0; # Numbers of modified fields
102 my %cookies = parse CGI::Cookie($cookie);
103 my $sessionID = $cookies{'CGISESSID'}->value;
106 #--- ----------------------------------------------------------------------------
107 if ($op eq "action") {
108 #-------------------------------------------------------------------------------
109 my @tags = $input->multi_param('tag');
110 my @subfields = $input->multi_param('subfield');
111 my @values = $input->multi_param('field_value');
112 my @searches = $input->multi_param('regex_search');
113 my @replaces = $input->multi_param('regex_replace');
114 my @modifiers = $input->multi_param('regex_modifiers');
115 my @disabled = $input->multi_param('disable_input');
116 # build indicator hash.
117 my @ind_tag = $input->multi_param('ind_tag');
118 my @indicator = $input->multi_param('indicator');
120 # Is there something to modify ?
121 # TODO : We shall use this var to warn the user in case no modification was done to the items
122 my $values_to_modify = scalar(grep {!/^$/} @values) || scalar(grep {!/^$/} @searches);
123 my $values_to_blank = scalar(@disabled);
125 my $marcitem;
127 # Once the job is done
128 if ($completedJobID) {
129 # If we have a reasonable amount of items, we display them
130 my $max_items = $del ? C4::Context->preference("MaxItemsToDisplayForBatchDel") : C4::Context->preference("MaxItemsToDisplayForBatchMod");
131 if (scalar(@itemnumbers) <= $max_items ){
132 if (scalar(@itemnumbers) <= 1000 ) {
133 $items_display_hashref=BuildItemsData(@itemnumbers);
134 } else {
135 # Else, we only display the barcode
136 my @simple_items_display = map {
137 my $itemnumber = $_;
138 my $item = Koha::Items->find($itemnumber);
140 itemnumber => $itemnumber,
141 barcode => $item ? ( $item->barcode // q{} ) : q{},
142 biblionumber => $item ? $item->biblio->biblionumber : q{},
144 } @itemnumbers;
145 $template->param("simple_items_display" => \@simple_items_display);
147 } else {
148 $template->param( "too_many_items_display" => scalar(@itemnumbers) );
149 $template->param( "job_completed" => 1 );
152 # Setting the job as done
153 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
155 # Calling the template
156 add_saved_job_results_to_template($template, $completedJobID);
158 } else {
159 # While the job is getting done
161 # Job size is the number of items we have to process
162 my $job_size = scalar(@itemnumbers);
163 my $job = undef;
165 # If we asked for background processing
166 if ($runinbackground) {
167 $job = put_in_background($job_size);
170 #initializing values for updates
171 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
172 if ($values_to_modify){
173 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
174 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
176 if ($values_to_blank){
177 foreach my $disabledsubf (@disabled){
178 if ($marcitem && $marcitem->field($itemtagfield)){
179 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
181 else {
182 $marcitem = MARC::Record->new();
183 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
188 try {
189 my $schema = Koha::Database->new->schema;
190 $schema->txn_do(
191 sub {
192 # For each item
193 my $i = 1;
194 foreach my $itemnumber (@itemnumbers) {
195 $job->progress($i) if $runinbackground;
196 my $item = Koha::Items->find($itemnumber);
197 next
198 unless $item
199 ; # Should have been tested earlier, but just in case...
200 my $itemdata = $item->unblessed;
201 if ($del) {
202 my $return = $item->safe_delete;
203 if ( ref( $return ) ) {
204 $deleted_items++;
206 else {
207 $not_deleted_items++;
208 push @not_deleted,
210 biblionumber => $itemdata->{'biblionumber'},
211 itemnumber => $itemdata->{'itemnumber'},
212 barcode => $itemdata->{'barcode'},
213 title => $itemdata->{'title'},
214 reason => $return,
218 # If there are no items left, delete the biblio
219 if ($del_records) {
220 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
221 if ( $itemscount == 0 ) {
222 my $error = DelBiblio( $itemdata->{'biblionumber'} );
223 unless ($error) {
224 $deleted_records++;
225 if ( $src eq 'CATALOGUING' ) {
226 # We are coming catalogue/detail.pl, there were items from a single bib record
227 $template->param( biblio_deleted => 1 );
233 else {
234 if ( $values_to_modify || $values_to_blank ) {
235 my $localmarcitem = Item2Marc($itemdata);
236 my $modified = 0;
238 for ( my $i = 0 ; $i < @tags ; $i++ ) {
239 my $search = $searches[$i];
240 next unless $search;
242 my $tag = $tags[$i];
243 my $subfield = $subfields[$i];
244 my $replace = $replaces[$i];
246 my $value = $localmarcitem->field( $tag )->subfield( $subfield );
247 my $old_value = $value;
249 my @available_modifiers = qw( i g );
250 my $retained_modifiers = q||;
251 for my $modifier ( split //, $modifiers[$i] ) {
252 $retained_modifiers .= $modifier
253 if grep {/$modifier/} @available_modifiers;
255 if ( $retained_modifiers =~ m/^(ig|gi)$/ ) {
256 $value =~ s/$search/$replace/ig;
258 elsif ( $retained_modifiers eq 'i' ) {
259 $value =~ s/$search/$replace/i;
261 elsif ( $retained_modifiers eq 'g' ) {
262 $value =~ s/$search/$replace/g;
264 else {
265 $value =~ s/$search/$replace/;
268 my @fields_to = $localmarcitem->field($tag);
269 foreach my $field_to_update ( @fields_to ) {
270 unless ( $old_value eq $value ) {
271 $modified++;
272 $field_to_update->update( $subfield => $value );
277 $modified += UpdateMarcWith( $marcitem, $localmarcitem );
278 if ($modified) {
279 eval {
280 if (
281 my $item = ModItemFromMarc(
282 $localmarcitem,
283 $itemdata->{biblionumber},
284 $itemnumber
288 LostItem( $itemnumber, 'batchmod' )
289 if $item->{itemlost}
290 and not $itemdata->{itemlost};
294 if ($runinbackground) {
295 $modified_items++ if $modified;
296 $modified_fields += $modified;
297 $job->set(
299 modified_items => $modified_items,
300 modified_fields => $modified_fields,
306 $i++;
308 if (@not_deleted) {
309 Koha::Exceptions::Exception->throw(
310 'Some items have not been deleted, rolling back');
315 catch {
316 if ( $_->isa('Koha::Exceptions::Exception') ) {
317 $template->param( deletion_failed => 1 );
319 die "Something terrible has happened!"
320 if ($_ =~ /Rollback failed/); # Rollback failed
325 #-------------------------------------------------------------------------------
326 # build screen with existing items. and "new" one
327 #-------------------------------------------------------------------------------
329 if ($op eq "show"){
330 my $filefh = $input->upload('uploadfile');
331 my $filecontent = $input->param('filecontent');
332 my ( @notfoundbarcodes, @notfounditemnumbers);
334 my $split_chars = C4::Context->preference('BarcodeSeparators');
335 if ($filefh){
336 binmode $filefh, ':encoding(UTF-8)';
337 my @contentlist;
338 while (my $content=<$filefh>){
339 $content =~ s/[\r\n]*$//;
340 push @contentlist, $content if $content;
343 if ($filecontent eq 'barcode_file') {
344 @contentlist = grep /\S/, ( map { split /[$split_chars]/ } @contentlist );
345 @contentlist = uniq @contentlist;
346 # Note: adding lc for case insensitivity
347 my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@contentlist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
348 @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @contentlist;
349 @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @contentlist;
351 elsif ( $filecontent eq 'itemid_file') {
352 @contentlist = uniq @contentlist;
353 my %itemdata = map { $_->{itemnumber} => 1 } @{ Koha::Items->search({ itemnumber => \@contentlist }, { columns => [ 'itemnumber' ] } )->unblessed };
354 @itemnumbers = grep { exists $itemdata{$_} } @contentlist;
355 @notfounditemnumbers = grep { !exists $itemdata{$_} } @contentlist;
357 } else {
358 if (defined $biblionumber && !@itemnumbers){
359 my @all_items = GetItemsInfo( $biblionumber );
360 foreach my $itm (@all_items) {
361 push @itemnumbers, $itm->{itemnumber};
364 if ( my $list = $input->param('barcodelist') ) {
365 my @barcodelist = grep /\S/, ( split /[$split_chars]/, $list );
366 @barcodelist = uniq @barcodelist;
367 # Note: adding lc for case insensitivity
368 my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => \@barcodelist }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed };
369 @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @barcodelist;
370 @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @barcodelist;
374 # Flag to tell the template there are valid results, hidden or not
375 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
376 # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
377 my $max_display_items = $del
378 ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
379 : C4::Context->preference("MaxItemsToDisplayForBatchMod");
380 $template->param("too_many_items_process" => scalar(@itemnumbers)) if !$del && scalar(@itemnumbers) >= C4::Context->preference("MaxItemsToProcessForBatchMod");
381 if (scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) {
382 $items_display_hashref=BuildItemsData(@itemnumbers);
383 } else {
384 $template->param("too_many_items_display" => scalar(@itemnumbers));
385 # Even if we do not display the items, we need the itemnumbers
386 $template->param(itemnumbers_array => \@itemnumbers);
388 # now, build the item form for entering a new item
389 my @loop_data =();
390 my $i=0;
391 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
393 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
395 # Adding a default choice, in case the user does not want to modify the branch
396 my $nochange_branch = { branchname => '', value => '', selected => 1 };
397 unshift (@$libraries, $nochange_branch);
399 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
401 # Getting list of subfields to keep when restricted batchmod edit is enabled
402 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
403 my $allowAllSubfields = (
404 not defined $subfieldsToAllowForBatchmod
405 or $subfieldsToAllowForBatchmod eq q||
406 ) ? 1 : 0;
407 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
409 foreach my $tag (sort keys %{$tagslib}) {
410 # loop through each subfield
411 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
412 next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
413 next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
414 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
415 # barcode and stocknumber are not meant to be batch-modified
416 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
417 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
418 my %subfield_data;
420 my $index_subfield = int(rand(1000000));
421 if ($subfield eq '@'){
422 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
423 } else {
424 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
426 $subfield_data{tag} = $tag;
427 $subfield_data{subfield} = $subfield;
428 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
429 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
430 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
431 my ($x,$value);
432 if ( $use_default_values) {
433 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
434 # get today date & replace YYYY, MM, DD if provided in the default value
435 my $today = dt_from_string;
436 my $year = $today->year;
437 my $month = $today->month;
438 my $day = $today->day;
439 $value =~ s/YYYY/$year/g;
440 $value =~ s/MM/$month/g;
441 $value =~ s/DD/$day/g;
443 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
444 # testing branch value if IndependentBranches.
446 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
447 my @authorised_values;
448 my %authorised_lib;
449 # builds list, depending on authorised value...
451 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
452 foreach my $library (@$libraries) {
453 push @authorised_values, $library->{branchcode};
454 $authorised_lib{$library->{branchcode}} = $library->{branchname};
456 $value = "";
458 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
459 push @authorised_values, "";
460 my $itemtypes = Koha::ItemTypes->search_with_localization;
461 while ( my $itemtype = $itemtypes->next ) {
462 push @authorised_values, $itemtype->itemtype;
463 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
465 $value = "";
467 #---- class_sources
469 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
470 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
472 my $class_sources = GetClassSources();
473 my $default_source = C4::Context->preference("DefaultClassificationSource");
475 foreach my $class_source (sort keys %$class_sources) {
476 next unless $class_sources->{$class_source}->{'used'} or
477 ($value and $class_source eq $value) or
478 ($class_source eq $default_source);
479 push @authorised_values, $class_source;
480 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
482 $value = '';
484 #---- "true" authorised value
486 else {
487 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
489 my @avs = Koha::AuthorisedValues->search({ category => $tagslib->{$tag}->{$subfield}->{authorised_value}, branchcode => $branch_limit },{order_by=>'lib'});
490 for my $av ( @avs ) {
491 push @authorised_values, $av->authorised_value;
492 $authorised_lib{$av->authorised_value} = $av->lib;
494 $value="";
496 $subfield_data{marc_value} = {
497 type => 'select',
498 id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
499 name => "field_value",
500 values => \@authorised_values,
501 labels => \%authorised_lib,
502 default => $value,
504 # it's a thesaurus / authority field
506 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
507 $subfield_data{marc_value} = {
508 type => 'text1',
509 id => $subfield_data{id},
510 value => $value,
511 authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
514 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
515 require Koha::FrameworkPlugin;
516 my $plugin = Koha::FrameworkPlugin->new( {
517 name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
518 item_style => 1,
520 my $temp;
521 my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
522 id => $subfield_data{id}, tabloop => \@loop_data };
523 $plugin->build( $pars );
524 if( !$plugin->errstr ) {
525 $subfield_data{marc_value} = {
526 type => 'text2',
527 id => $subfield_data{id},
528 value => $value,
529 javascript => $plugin->javascript,
530 noclick => $plugin->noclick,
532 } else {
533 warn $plugin->errstr;
534 $subfield_data{marc_value} = { # supply default input form
535 type => 'text',
536 id => $subfield_data{id},
537 value => $value,
541 elsif ( $tag eq '' ) { # it's an hidden field
542 $subfield_data{marc_value} = {
543 type => 'hidden',
544 id => $subfield_data{id},
545 value => $value,
548 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
549 $subfield_data{marc_value} = {
550 type => 'text',
551 id => $subfield_data{id},
552 value => $value,
555 elsif ( length($value) > 100
556 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
557 300 <= $tag && $tag < 400 && $subfield eq 'a' )
558 or (C4::Context->preference("marcflavour") eq "MARC21" and
559 500 <= $tag && $tag < 600 )
561 # oversize field (textarea)
562 $subfield_data{marc_value} = {
563 type => 'textarea',
564 id => $subfield_data{id},
565 value => $value,
567 } else {
568 # it's a standard field
569 $subfield_data{marc_value} = {
570 type => 'text',
571 id => $subfield_data{id},
572 value => $value,
575 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
576 push (@loop_data, \%subfield_data);
577 $i++
579 } # -- End foreach tag
583 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
584 $template->param(
585 item => \@loop_data,
586 notfoundbarcodes => \@notfoundbarcodes,
587 notfounditemnumbers => \@notfounditemnumbers
589 $nextop="action"
590 } # -- End action="show"
592 $template->param(%$items_display_hashref) if $items_display_hashref;
593 $template->param(
594 op => $nextop,
596 $template->param( $op => 1 ) if $op;
598 if ($op eq "action") {
600 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
602 $template->param(
603 not_deleted_items => $not_deleted_items,
604 deleted_items => $deleted_items,
605 delete_records => $del_records,
606 deleted_records => $deleted_records,
607 not_deleted_loop => \@not_deleted
611 foreach my $error (@errors) {
612 $template->param($error => 1) if $error;
614 $template->param(src => $src);
615 $template->param(biblionumber => $biblionumber);
616 output_html_with_http_headers $input, $cookie, $template->output;
617 exit;
620 # ---------------- Functions
622 sub BuildItemsData{
623 my @itemnumbers=@_;
624 # now, build existiing item list
625 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
626 my @big_array;
627 #---- finds where items.itemnumber is stored
628 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
629 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
630 foreach my $itemnumber (@itemnumbers){
631 my $itemdata = Koha::Items->find($itemnumber);
632 next unless $itemdata; # Should have been tested earlier, but just in case...
633 $itemdata = $itemdata->unblessed;
634 my $itemmarc=Item2Marc($itemdata);
635 my %this_row;
636 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
637 # loop through each subfield
638 my $itembranchcode=$field->subfield($branchtagsubfield);
639 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
640 #verifying rights
641 my $userenv = C4::Context->userenv();
642 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
643 $this_row{'nomod'}=1;
646 my $tag=$field->tag();
647 foreach my $subfield ($field->subfields) {
648 my ($subfcode,$subfvalue)=@$subfield;
649 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
650 && $tag ne $itemtagfield
651 && $subfcode ne $itemtagsubfield);
653 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
654 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
655 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
656 $subfcode, $subfvalue, '', $tagslib)
657 || $subfvalue;
660 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
664 # grab title, author, and ISBN to identify bib that the item
665 # belongs to in the display
666 my $biblio = Koha::Biblios->find( $itemdata->{biblionumber} );
667 $this_row{title} = $biblio->title;
668 $this_row{author} = $biblio->author;
669 $this_row{isbn} = $biblio->biblioitem->isbn;
670 $this_row{biblionumber} = $biblio->biblionumber;
671 $this_row{holds} = $biblio->holds->count;
672 $this_row{item_holds} = Koha::Holds->search( { itemnumber => $itemnumber } )->count;
673 $this_row{item} = Koha::Items->find($itemnumber);
675 if (%this_row) {
676 push(@big_array, \%this_row);
679 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
681 # now, construct template !
682 # First, the existing items for display
683 my @item_value_loop;
684 my @witnesscodessorted=sort keys %witness;
685 for my $row ( @big_array ) {
686 my %row_data;
687 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
688 $row_data{item_value} = [ @item_fields ];
689 $row_data{itemnumber} = $row->{itemnumber};
690 #reporting this_row values
691 $row_data{'nomod'} = $row->{'nomod'};
692 $row_data{bibinfo} = $row->{bibinfo};
693 $row_data{author} = $row->{author};
694 $row_data{title} = $row->{title};
695 $row_data{isbn} = $row->{isbn};
696 $row_data{biblionumber} = $row->{biblionumber};
697 $row_data{holds} = $row->{holds};
698 $row_data{item_holds} = $row->{item_holds};
699 $row_data{item} = $row->{item};
700 my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
701 $row_data{onloan} = $is_on_loan ? 1 : 0;
702 push(@item_value_loop,\%row_data);
704 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
706 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
709 #BE WARN : it is not the general case
710 # This function can be OK in the item marc record special case
711 # Where subfield is not repeated
712 # And where we are sure that field should correspond
713 # And $tag>10
714 sub UpdateMarcWith {
715 my ($marcfrom,$marcto)=@_;
716 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
717 my $fieldfrom=$marcfrom->field($itemtag);
718 my @fields_to=$marcto->field($itemtag);
719 my $modified = 0;
721 return $modified unless $fieldfrom;
723 foreach my $subfield ( $fieldfrom->subfields() ) {
724 foreach my $field_to_update ( @fields_to ) {
725 if ( $subfield->[1] ) {
726 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
727 $modified++;
728 $field_to_update->update( $subfield->[0] => $subfield->[1] );
731 else {
732 $modified++;
733 $field_to_update->delete_subfield( code => $subfield->[0] );
737 return $modified;
740 sub find_value {
741 my ($tagfield,$insubfield,$record) = @_;
742 my $result;
743 my $indicator;
744 foreach my $field ($record->field($tagfield)) {
745 my @subfields = $field->subfields();
746 foreach my $subfield (@subfields) {
747 if (@$subfield[0] eq $insubfield) {
748 $result .= @$subfield[1];
749 $indicator = $field->indicator(1).$field->indicator(2);
753 return($indicator,$result);
756 # ----------------------------
757 # Background functions
760 sub add_results_to_template {
761 my $template = shift;
762 my $results = shift;
763 $template->param(map { $_ => $results->{$_} } keys %{ $results });
766 sub add_saved_job_results_to_template {
767 my $template = shift;
768 my $completedJobID = shift;
769 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
770 my $results = $job->results();
771 add_results_to_template($template, $results);
773 my $fields = $job->get("modified_fields");
774 my $items = $job->get("modified_items");
775 $template->param(
776 modified_items => $items,
777 modified_fields => $fields,
781 sub put_in_background {
782 my $job_size = shift;
784 my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
785 my $jobID = $job->id();
787 # fork off
788 if (my $pid = fork) {
789 # parent
790 # return job ID as JSON
792 # prevent parent exiting from
793 # destroying the kid's database handle
794 # FIXME: according to DBI doc, this may not work for Oracle
795 $dbh->{InactiveDestroy} = 1;
797 my $reply = CGI->new("");
798 print $reply->header(-type => 'text/html');
799 print '{"jobID":"' . $jobID . '"}';
800 exit 0;
801 } elsif (defined $pid) {
802 # child
803 # close STDOUT to signal to Apache that
804 # we're now running in the background
805 close STDOUT;
806 close STDERR;
807 } else {
808 # fork failed, so exit immediately
809 warn "fork failed while attempting to run tools/batchMod.pl as a background job";
810 exit 0;
812 return $job;