Bug 24663: Remove authnotrequired if set to 0
[koha.git] / cataloguing / additem.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use Modern::Perl;
23
24 use CGI qw ( -utf8 );
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Context;
30 use C4::Circulation;
31 use C4::Koha;
32 use C4::ClassSource;
33 use Koha::DateUtils;
34 use Koha::Items;
35 use Koha::ItemTypes;
36 use Koha::Libraries;
37 use Koha::Patrons;
38 use List::MoreUtils qw/any/;
39 use C4::Search;
40 use Storable qw(thaw freeze);
41 use URI::Escape;
42 use C4::Members;
43
44 use MARC::File::XML;
45 use URI::Escape;
46
47 our $dbh = C4::Context->dbh;
48
49 sub find_value {
50     my ($tagfield,$insubfield,$record) = @_;
51     my $result;
52     my $indicator;
53     foreach my $field ($record->field($tagfield)) {
54         my @subfields = $field->subfields();
55         foreach my $subfield (@subfields) {
56             if (@$subfield[0] eq $insubfield) {
57                 $result .= @$subfield[1];
58                 $indicator = $field->indicator(1).$field->indicator(2);
59             }
60         }
61     }
62     return($indicator,$result);
63 }
64
65 sub get_item_from_barcode {
66     my ($barcode)=@_;
67     my $dbh=C4::Context->dbh;
68     my $result;
69     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
70     $rq->execute($barcode);
71     ($result)=$rq->fetchrow;
72     return($result);
73 }
74
75 sub set_item_default_location {
76     my $itemnumber = shift;
77     my $item       = Koha::Items->find($itemnumber);
78     if ( C4::Context->preference('NewItemsDefaultLocation') ) {
79         $item->permanent_location($item->location);
80         $item->location(C4::Context->preference('NewItemsDefaultLocation'));
81     }
82     else {
83         # It seems that we are dealing with that in too many places
84         $item->permanent_location($item->location) unless defined $item->permanent_location;
85     }
86     $item->store;
87 }
88
89 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
90 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
91 sub _increment_barcode {
92     my ($record, $frameworkcode) = @_;
93     my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
94     unless ($record->field($tagfield)->subfield($tagsubfield)) {
95         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
96         $sth_barcode->execute;
97         my ($newbarcode) = $sth_barcode->fetchrow;
98         $newbarcode++;
99         # OK, we have the new barcode, now create the entry in MARC record
100         my $fieldItem = $record->field($tagfield);
101         $record->delete_field($fieldItem);
102         $fieldItem->add_subfields($tagsubfield => $newbarcode);
103         $record->insert_fields_ordered($fieldItem);
104     }
105     return $record;
106 }
107
108
109 sub generate_subfield_form {
110         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition, $item) = @_;
111   
112         my $frameworkcode = &GetFrameworkCode($biblionumber);
113
114         my %subfield_data;
115         my $dbh = C4::Context->dbh;
116         
117         my $index_subfield = int(rand(1000000)); 
118         if ($subfieldtag eq '@'){
119             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
120         } else {
121             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
122         }
123         
124         $subfield_data{tag}        = $tag;
125         $subfield_data{subfield}   = $subfieldtag;
126         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
127         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
128         $subfield_data{important}  = $subfieldlib->{important};
129         $subfield_data{repeatable} = $subfieldlib->{repeatable};
130         $subfield_data{maxlength}  = $subfieldlib->{maxlength};
131         
132         if ( ! defined( $value ) || $value eq '')  {
133             $value = $subfieldlib->{defaultvalue};
134             if ( $value ) {
135                 # get today date & replace <<YYYY>>, <<YY>>, <<MM>>, <<DD>> if provided in the default value
136                 my $today_dt = dt_from_string;
137                 my $year = $today_dt->strftime('%Y');
138                 my $shortyear = $today_dt->strftime('%y');
139                 my $month = $today_dt->strftime('%m');
140                 my $day = $today_dt->strftime('%d');
141                 $value =~ s/<<YYYY>>/$year/g;
142                 $value =~ s/<<YY>>/$shortyear/g;
143                 $value =~ s/<<MM>>/$month/g;
144                 $value =~ s/<<DD>>/$day/g;
145                 # And <<USER>> with surname (?)
146                 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
147                 $value=~s/<<USER>>/$username/g;
148             }
149         }
150
151         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
152
153         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
154         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
155             foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
156                 my $CNtag       = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
157                 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
158                 my $temp2 = $temp->field($CNtag);
159
160                 next unless $temp2;
161                 $value = $temp2->as_string( $CNsubfields, ' ' );
162                 last if $value;
163             }
164         }
165
166         if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
167             my $input = new CGI;
168             $value = $input->param('barcode');
169         }
170
171         if ( $subfieldlib->{authorised_value} ) {
172             my @authorised_values;
173             my %authorised_lib;
174             # builds list, depending on authorised value...
175             if ( $subfieldlib->{authorised_value} eq "LOST" ) {
176                 my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue');
177                 my $item_is_return_claim = $ClaimReturnedLostValue && $item && $item->itemlost && $ClaimReturnedLostValue eq $item->itemlost;
178                 $subfield_data{IS_RETURN_CLAIM} = $item_is_return_claim;
179
180                 $subfield_data{IS_LOST_AV} = 1;
181
182                 push @authorised_values, qq{};
183                 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
184                 for my $r ( @$av ) {
185                     push @authorised_values, $r->{authorised_value};
186                     $authorised_lib{$r->{authorised_value}} = $r->{lib};
187                 }
188             }
189             elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
190                 foreach my $thisbranch (@$branches) {
191                     push @authorised_values, $thisbranch->{branchcode};
192                     $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
193                     $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
194                 }
195             }
196             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
197                   push @authorised_values, "";
198                   my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
199                   my $itemtypes;
200                   if($branch_limit) {
201                       $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
202                   } else {
203                       $itemtypes = Koha::ItemTypes->search_with_localization;
204                   }
205                   while ( my $itemtype = $itemtypes->next ) {
206                       push @authorised_values, $itemtype->itemtype;
207                       $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
208                   }
209
210                   unless ( $value ) {
211                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
212                       $itype_sth->execute( $biblionumber );
213                       ( $value ) = $itype_sth->fetchrow_array;
214                   }
215           
216                   #---- class_sources
217             }
218             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
219                   push @authorised_values, "";
220                     
221                   my $class_sources = GetClassSources();
222                   my $default_source = C4::Context->preference("DefaultClassificationSource");
223                   
224                   foreach my $class_source (sort keys %$class_sources) {
225                       next unless $class_sources->{$class_source}->{'used'} or
226                                   ($value and $class_source eq $value)      or
227                                   ($class_source eq $default_source);
228                       push @authorised_values, $class_source;
229                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
230                   }
231                           $value = $default_source unless ($value);
232         
233                   #---- "true" authorised value
234             }
235             else {
236                   push @authorised_values, qq{};
237                   my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
238                   for my $r ( @$av ) {
239                       push @authorised_values, $r->{authorised_value};
240                       $authorised_lib{$r->{authorised_value}} = $r->{lib};
241                   }
242             }
243
244             if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
245                 $subfield_data{marc_value} = {
246                     type        => 'hidden',
247                     id          => $subfield_data{id},
248                     maxlength   => $subfield_data{maxlength},
249                     value       => $value,
250                     ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
251                 };
252             }
253             else {
254                 $subfield_data{marc_value} = {
255                     type     => 'select',
256                     id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
257                     values   => \@authorised_values,
258                     labels   => \%authorised_lib,
259                     default  => $value,
260                     ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
261                 };
262             }
263         }
264             # it's a thesaurus / authority field
265         elsif ( $subfieldlib->{authtypecode} ) {
266                 $subfield_data{marc_value} = {
267                     type         => 'text_auth',
268                     id           => $subfield_data{id},
269                     maxlength    => $subfield_data{maxlength},
270                     value        => $value,
271                     authtypecode => $subfieldlib->{authtypecode},
272                 };
273         }
274             # it's a plugin field
275         elsif ( $subfieldlib->{value_builder} ) { # plugin
276             require Koha::FrameworkPlugin;
277             my $plugin = Koha::FrameworkPlugin->new({
278                 name => $subfieldlib->{'value_builder'},
279                 item_style => 1,
280             });
281             my $pars=  { dbh => $dbh, record => $temp, tagslib =>$tagslib,
282                 id => $subfield_data{id}, tabloop => $loop_data };
283             $plugin->build( $pars );
284             if( !$plugin->errstr ) {
285                 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
286                 $subfield_data{marc_value} = {
287                     type        => 'text_plugin',
288                     id          => $subfield_data{id},
289                     maxlength   => $subfield_data{maxlength},
290                     value       => $value,
291                     class       => $class,
292                     nopopup     => $plugin->noclick,
293                     javascript  => $plugin->javascript,
294                 };
295             } else {
296                 warn $plugin->errstr;
297                 $subfield_data{marc_value} = {
298                     type        => 'text',
299                     id          => $subfield_data{id},
300                     maxlength   => $subfield_data{maxlength},
301                     value       => $value,
302                 }; # supply default input form
303             }
304         }
305         elsif ( $tag eq '' ) {       # it's an hidden field
306             $subfield_data{marc_value} = {
307                 type        => 'hidden',
308                 id          => $subfield_data{id},
309                 maxlength   => $subfield_data{maxlength},
310                 value       => $value,
311             };
312         }
313         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
314             $subfield_data{marc_value} = {
315                 type        => 'text',
316                 id          => $subfield_data{id},
317                 maxlength   => $subfield_data{maxlength},
318                 value       => $value,
319             };
320         }
321         elsif (
322                 (
323                     $value and length($value) > 100
324                 )
325                 or (
326                     C4::Context->preference("marcflavour") eq "UNIMARC"
327                     and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
328                 )
329                 or (
330                     C4::Context->preference("marcflavour") eq "MARC21"
331                     and 500 <= $tag && $tag < 600
332                 )
333               ) {
334             # oversize field (textarea)
335             $subfield_data{marc_value} = {
336                 type        => 'textarea',
337                 id          => $subfield_data{id},
338                 value       => $value,
339             };
340         } else {
341             # it's a standard field
342             $subfield_data{marc_value} = {
343                 type        => 'text',
344                 id          => $subfield_data{id},
345                 maxlength   => $subfield_data{maxlength},
346                 value       => $value,
347             };
348         }
349
350         # Getting list of subfields to keep when restricted editing is enabled
351         my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
352         my $allowAllSubfields = (
353             not defined $subfieldsToAllowForRestrictedEditing
354               or $subfieldsToAllowForRestrictedEditing eq q||
355         ) ? 1 : 0;
356         my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
357
358         # If we're on restricted editing, and our field is not in the list of subfields to allow,
359         # then it is read-only
360         $subfield_data{marc_value}->{readonly} = (
361             not $allowAllSubfields
362             and $restrictededition
363             and !grep { $tag . '$' . $subfieldtag  eq $_ } @subfieldsToAllow
364         ) ? 1: 0;
365
366         return \%subfield_data;
367 }
368
369 # Removes some subfields when prefilling items
370 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
371 sub removeFieldsForPrefill {
372
373     my $item = shift;
374
375     # Getting item tag
376     my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
377
378     # Getting list of subfields to keep
379     my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
380
381     # Removing subfields that are not in the syspref
382     if ($tag && $subfieldsToUseWhenPrefill) {
383         my $field = $item->field($tag);
384         my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
385         foreach my $subfield ($field->subfields()) {
386             if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
387                 $field->delete_subfield(code => $subfield->[0]);
388             }
389
390         }
391     }
392
393     return $item;
394
395 }
396
397 my $input        = new CGI;
398 my $error        = $input->param('error');
399 my $biblionumber = $input->param('biblionumber');
400 my $itemnumber   = $input->param('itemnumber');
401 my $op           = $input->param('op') || q{};
402 my $hostitemnumber = $input->param('hostitemnumber');
403 my $marcflavour  = C4::Context->preference("marcflavour");
404 my $searchid     = $input->param('searchid');
405 # fast cataloguing datas
406 my $fa_circborrowernumber = $input->param('circborrowernumber');
407 my $fa_barcode            = $input->param('barcode');
408 my $fa_branch             = $input->param('branch');
409 my $fa_stickyduedate      = $input->param('stickyduedate');
410 my $fa_duedatespec        = $input->param('duedatespec');
411
412 my $frameworkcode = &GetFrameworkCode($biblionumber);
413
414 # Defining which userflag is needing according to the framework currently used
415 my $userflags;
416 if (defined $input->param('frameworkcode')) {
417     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
418 }
419
420 if (not defined $userflags) {
421     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
422 }
423
424 my ($template, $loggedinuser, $cookie)
425     = get_template_and_user({template_name => "cataloguing/additem.tt",
426                  query => $input,
427                  type => "intranet",
428                  flagsrequired => {editcatalogue => $userflags},
429                  debug => 1,
430                  });
431
432
433 # Does the user have a restricted item editing permission?
434 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
435 my $restrictededition = $uid ? haspermission($uid,  {'editcatalogue' => 'edit_items_restricted'}) : undef;
436 # In case user is a superlibrarian, editing is not restricted
437 $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibrarian());
438 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
439 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
440
441 my $tagslib = &GetMarcStructure(1,$frameworkcode);
442 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
443
444 output_and_exit_if_error( $input, $cookie, $template,
445     { module => 'cataloguing', record => $record } );
446
447 my $oldrecord = TransformMarcToKoha($record);
448 my $itemrecord;
449 my $nextop="additem";
450 my @errors; # store errors found while checking data BEFORE saving item.
451
452 # Getting last created item cookie
453 my $prefillitem = C4::Context->preference('PrefillItem');
454 my $justaddeditem;
455 my $cookieitemrecord;
456 if ($prefillitem) {
457     my $lastitemcookie = $input->cookie('LastCreatedItem');
458     if ($lastitemcookie) {
459         $lastitemcookie = uri_unescape($lastitemcookie);
460         eval {
461             if ( thaw($lastitemcookie) ) {
462                 $cookieitemrecord = thaw($lastitemcookie);
463                 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
464             }
465         };
466         if ($@) {
467             $lastitemcookie = 'undef' unless $lastitemcookie;
468             warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
469         }
470     }
471 }
472
473 #-------------------------------------------------------------------------------
474 if ($op eq "additem") {
475
476     #-------------------------------------------------------------------------------
477     # rebuild
478     my @tags      = $input->multi_param('tag');
479     my @subfields = $input->multi_param('subfield');
480     my @values    = $input->multi_param('field_value');
481     # build indicator hash.
482     my @ind_tag   = $input->multi_param('ind_tag');
483     my @indicator = $input->multi_param('indicator');
484     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
485     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
486
487     # type of add
488     my $add_submit                 = $input->param('add_submit');
489     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
490     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
491     my $number_of_copies           = $input->param('number_of_copies');
492
493     # This is a bit tricky : if there is a cookie for the last created item and
494     # we just added an item, the cookie value is not correct yet (it will be updated
495     # next page). To prevent the form from being filled with outdated values, we
496     # force the use of "add and duplicate" feature, so the form will be filled with
497     # correct values.
498     $add_duplicate_submit = 1 if ($prefillitem);
499     $justaddeditem = 1;
500
501     # if autoBarcode is set to 'incremental', calculate barcode...
502     if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
503         $record = _increment_barcode($record, $frameworkcode);
504     }
505
506     my $addedolditem = TransformMarcToKoha( $record );
507
508     # If we have to add or add & duplicate, we add the item
509     if ( $add_submit || $add_duplicate_submit ) {
510
511         # check for item barcode # being unique
512         my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
513         push @errors, "barcode_not_unique" if ($exist_itemnumber);
514
515         # if barcode exists, don't create, but report The problem.
516         unless ($exist_itemnumber) {
517             my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
518             set_item_default_location($oldbibitemnum);
519
520             # Pushing the last created item cookie back
521             if ($prefillitem && defined $record) {
522                 my $itemcookie = $input->cookie(
523                     -name => 'LastCreatedItem',
524                     # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
525                     -value   => uri_escape_utf8( freeze( $record ) ),
526                     -HttpOnly => 1,
527                     -expires => ''
528                 );
529
530                 $cookie = [ $cookie, $itemcookie ];
531             }
532
533         }
534         $nextop = "additem";
535         if ($exist_itemnumber) {
536             $itemrecord = $record;
537         }
538     }
539
540     # If we have to add & duplicate
541     if ($add_duplicate_submit) {
542         $itemrecord = $record;
543         if (C4::Context->preference('autoBarcode') eq 'incremental') {
544             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
545         }
546         else {
547             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
548             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
549             my $fieldItem = $itemrecord->field($tagfield);
550             $itemrecord->delete_field($fieldItem);
551             $fieldItem->delete_subfields($tagsubfield);
552             $itemrecord->insert_fields_ordered($fieldItem);
553         }
554     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
555     }
556
557     # If we have to add multiple copies
558     if ($add_multiple_copies_submit) {
559
560         use C4::Barcodes;
561         my $barcodeobj = C4::Barcodes->new;
562         my $copynumber = $addedolditem->{'copynumber'};
563         my $oldbarcode = $addedolditem->{'barcode'};
564         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
565         my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
566
567     # If there is a barcode and we can't find their new values, we can't add multiple copies
568         my $testbarcode;
569         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
570         if ($oldbarcode && !$testbarcode) {
571
572             push @errors, "no_next_barcode";
573             $itemrecord = $record;
574
575         } else {
576         # We add each item
577
578             # For the first iteration
579             my $barcodevalue = $oldbarcode;
580             my $exist_itemnumber;
581
582
583             for (my $i = 0; $i < $number_of_copies;) {
584
585                 # If there is a barcode
586                 if ($barcodevalue) {
587
588                     # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
589                     $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
590
591                     # Putting it into the record
592                     if ($barcodevalue) {
593                 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
594                     # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
595                     # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
596                     # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
597                     # But when adding multiple copies we need to prefix it here,
598                     # so we retrieve the homebranch from the item and prefix the barcode with it.
599                     my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
600                     my $homebranch = $record->subfield($hb_field, $hb_subfield);
601                     $barcodevalue = $homebranch . $barcodevalue;
602                 }
603                 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
604                     }
605
606                     # Checking if the barcode already exists
607                     $exist_itemnumber = get_item_from_barcode($barcodevalue);
608                 }
609         # Updating record with the new copynumber
610         if ( $copynumber  ){
611             $record->field($copytagfield)->update($copytagsubfield => $copynumber);
612         }
613
614                 # Adding the item
615         if (!$exist_itemnumber) {
616             my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
617                 AddItemFromMarc( $record, $biblionumber, { skip_modzebra_update => 1 } );
618             set_item_default_location($oldbibitemnum);
619
620             # We count the item only if it was really added
621             # That way, all items are added, even if there was some already existing barcodes
622             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
623             $i++;
624             # Only increment copynumber if item was really added
625             $copynumber++  if ( $copynumber && $copynumber =~ m/^\d+$/ );
626         }
627
628                 # Preparing the next iteration
629                 $oldbarcode = $barcodevalue;
630             }
631
632         C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
633
634             undef($itemrecord);
635         }
636     }   
637     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
638         print $input->redirect(
639            '/cgi-bin/koha/circ/circulation.pl?'
640            .'borrowernumber='.$fa_circborrowernumber
641            .'&barcode='.uri_escape_utf8($fa_barcode)
642            .'&duedatespec='.$fa_duedatespec
643            .'&stickyduedate=1'
644         );
645         exit;
646     }
647
648
649 #-------------------------------------------------------------------------------
650 } elsif ($op eq "edititem") {
651 #-------------------------------------------------------------------------------
652 # retrieve item if exist => then, it's a modif
653     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
654     $nextop = "saveitem";
655 #-------------------------------------------------------------------------------
656 } elsif ($op eq "dupeitem") {
657 #-------------------------------------------------------------------------------
658 # retrieve item if exist => then, it's a modif
659     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
660     if (C4::Context->preference('autoBarcode') eq 'incremental') {
661         $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
662     }
663     else {
664         # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
665         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
666         my $fieldItem = $itemrecord->field($tagfield);
667         $itemrecord->delete_field($fieldItem);
668         $fieldItem->delete_subfields($tagsubfield);
669         $itemrecord->insert_fields_ordered($fieldItem);
670     }
671
672     #check for hidden subfield and remove them for the duplicated item
673     foreach my $field ($itemrecord->fields()){
674         my $tag = $field->{_tag};
675         foreach my $subfield ($field->subfields()){
676             my $subfieldtag = $subfield->[0];
677             if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
678             ||  abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
679                 my $fieldItem = $itemrecord->field($tag);
680                 $itemrecord->delete_field($fieldItem);
681                 $fieldItem->delete_subfields($subfieldtag);
682                 $itemrecord->insert_fields_ordered($fieldItem);
683             }
684         }
685     }
686
687     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
688     $nextop = "additem";
689 #-------------------------------------------------------------------------------
690 } elsif ($op eq "delitem") {
691 #-------------------------------------------------------------------------------
692     # check that there is no issue on this item before deletion.
693     my $item = Koha::Items->find($itemnumber);
694     $error = $item->safe_delete;
695     if(ref($error) eq 'Koha::Item'){
696         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
697     }else{
698         push @errors,$error;
699         $nextop="additem";
700     }
701 #-------------------------------------------------------------------------------
702 } elsif ($op eq "delallitems") {
703 #-------------------------------------------------------------------------------
704     my $items = Koha::Items->search({ biblionumber => $biblionumber });
705     while ( my $item = $items->next ) {
706         $error = $item->safe_delete({ skip_modzebra_update => 1 });
707         next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
708         push @errors,$error;
709     }
710     C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
711     if ( @errors ) {
712         $nextop="additem";
713     } else {
714         my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
715         my $views = { C4::Search::enabled_staff_search_views };
716         if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
717             print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
718         } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
719             print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
720         } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
721             print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
722         } else {
723             print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
724         }
725         exit;
726     }
727 #-------------------------------------------------------------------------------
728 } elsif ($op eq "saveitem") {
729 #-------------------------------------------------------------------------------
730     # rebuild
731     my @tags      = $input->multi_param('tag');
732     my @subfields = $input->multi_param('subfield');
733     my @values    = $input->multi_param('field_value');
734     # build indicator hash.
735     my @ind_tag   = $input->multi_param('ind_tag');
736     my @indicator = $input->multi_param('indicator');
737     # my $itemnumber = $input->param('itemnumber');
738     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
739     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
740     # MARC::Record builded => now, record in DB
741     # warn "R: ".$record->as_formatted;
742     # check that the barcode don't exist already
743     my $addedolditem = TransformMarcToKoha($itemtosave);
744     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
745     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
746         push @errors,"barcode_not_unique";
747     } else {
748         my $item = Koha::Items->find($itemnumber );
749         my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
750         $itemnumber = q{};
751         my $olditemlost = $item->itemlost;
752         my $newitemlost = $newitem->{itemlost};
753         if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
754             LostItem( $item->itemnumber, 'additem' )
755         }
756     }
757     $nextop="additem";
758 } elsif ($op eq "delinkitem"){
759     my $analyticfield = '773';
760         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
761         $analyticfield = '773';
762     } elsif ($marcflavour eq 'UNIMARC') {
763         $analyticfield = '461';
764     }
765     foreach my $field ($record->field($analyticfield)){
766         if ($field->subfield('9') eq $hostitemnumber){
767             $record->delete_field($field);
768             last;
769         }
770     }
771         my $modbibresult = ModBiblio($record, $biblionumber,'');
772 }
773
774 #
775 #-------------------------------------------------------------------------------
776 # build screen with existing items. and "new" one
777 #-------------------------------------------------------------------------------
778
779 # now, build existiing item list
780 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
781 #my @fields = $record->fields();
782
783
784 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
785 my @big_array;
786 #---- finds where items.itemnumber is stored
787 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
788 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
789 C4::Biblio::EmbedItemsInMarcBiblio({
790     marc_record  => $temp,
791     biblionumber => $biblionumber });
792 my @fields = $temp->fields();
793
794
795 my @hostitemnumbers;
796 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
797     my $analyticfield = '773';
798     if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC') {
799         $analyticfield = '773';
800     } elsif ($marcflavour eq 'UNIMARC') {
801         $analyticfield = '461';
802     }
803     foreach my $hostfield ($temp->field($analyticfield)){
804         my $hostbiblionumber = $hostfield->subfield('0');
805         if ($hostbiblionumber){
806             my $hostrecord = GetMarcBiblio({
807                 biblionumber => $hostbiblionumber,
808                 embed_items  => 1 });
809             if ($hostrecord) {
810                 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
811                 foreach my $hostitem ($hostrecord->field($itemfield)){
812                     if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
813                         push (@fields, $hostitem);
814                         push (@hostitemnumbers, $hostfield->subfield('9'));
815                     }
816                 }
817             }
818         }
819     }
820 }
821
822 foreach my $field (@fields) {
823     next if ( $field->tag() < 10 );
824
825     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
826     my %this_row;
827     # loop through each subfield
828     my $i = 0;
829     foreach my $subfield (@subf){
830         my $subfieldcode = $subfield->[0];
831         my $subfieldvalue= $subfield->[1];
832
833         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
834                 && ($field->tag() ne $itemtagfield 
835                 && $subfieldcode   ne $itemtagsubfield));
836         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
837                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
838                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
839                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
840                         $subfieldcode, $subfieldvalue, '', $tagslib) 
841                                                 || $subfieldvalue;
842         }
843
844         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
845             #verifying rights
846             my $userenv = C4::Context->userenv();
847             unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
848                 $this_row{'nomod'} = 1;
849             }
850         }
851         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
852
853         if ( C4::Context->preference('EasyAnalyticalRecords') ) {
854             foreach my $hostitemnumber (@hostitemnumbers) {
855                 my $item = Koha::Items->find( $hostitemnumber );
856                 if ($this_row{itemnumber} eq $hostitemnumber) {
857                     $this_row{hostitemflag} = 1;
858                     $this_row{hostbiblionumber}= $item->biblio->biblionumber;
859                     last;
860                 }
861             }
862         }
863     }
864     if (%this_row) {
865         push(@big_array, \%this_row);
866     }
867 }
868
869 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
870 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
871
872 # now, construct template !
873 # First, the existing items for display
874 my @item_value_loop;
875 my @header_value_loop;
876 for my $row ( @big_array ) {
877     my %row_data;
878     my @item_fields;
879     foreach my $key (sort keys %witness){
880         my $item_field;
881         if ( $row->{$key} ){
882             $item_field->{field} = $row->{$key};
883         } else {
884             $item_field->{field} = '';
885         }
886
887         for my $kohafield (
888             qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
889           )
890         {
891             my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
892             next unless $key eq $subfield;
893             $item_field->{datatype} = 'date';
894         }
895
896         push @item_fields, $item_field;
897     }
898     $row_data{item_value} = [ @item_fields ];
899     $row_data{itemnumber} = $row->{itemnumber};
900     #reporting this_row values
901     $row_data{'nomod'} = $row->{'nomod'};
902     $row_data{'hostitemflag'} = $row->{'hostitemflag'};
903     $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
904 #       $row_data{'countanalytics'} = $row->{'countanalytics'};
905     push(@item_value_loop,\%row_data);
906 }
907 foreach my $subfield_code (sort keys(%witness)) {
908     my %header_value;
909     $header_value{header_value} = $witness{$subfield_code};
910
911     my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
912     my $kohafield = $subfieldlib->{kohafield};
913     if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
914         $header_value{column_name} = $1;
915     }
916
917     push(@header_value_loop, \%header_value);
918 }
919
920 # now, build the item form for entering a new item
921 my @loop_data =();
922 my $i=0;
923
924 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
925 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
926 for my $library ( @$libraries ) {
927     $library->{selected} = 1 if $library->{branchcode} eq $branch
928 }
929
930 my $item = Koha::Items->find($itemnumber);
931
932 # We generate form, from actuel record
933 @fields = ();
934 if($itemrecord){
935     foreach my $field ($itemrecord->fields()){
936         my $tag = $field->{_tag};
937         foreach my $subfield ( $field->subfields() ){
938
939             my $subfieldtag = $subfield->[0];
940             my $value       = $subfield->[1];
941             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
942
943             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
944
945             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
946             push @fields, "$tag$subfieldtag";
947             push (@loop_data, $subfield_data);
948             $i++;
949                     }
950
951                 }
952             }
953     # and now we add fields that are empty
954
955 # Using last created item if it exists
956
957 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
958
959 # We generate form, and fill with values if defined
960 foreach my $tag ( keys %{$tagslib}){
961     foreach my $subtag (keys %{$tagslib->{$tag}}){
962         next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
963         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
964         next if any { /^$tag$subtag$/ }  @fields;
965
966         my @values = (undef);
967         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
968         for my $value (@values){
969             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
970             push (@loop_data, $subfield_data);
971             $i++;
972         }
973   }
974 }
975 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
976
977 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
978 $template->param(
979     biblionumber => $biblionumber,
980     title        => $oldrecord->{title},
981     author       => $oldrecord->{author},
982     item_loop        => \@item_value_loop,
983     item_header_loop => \@header_value_loop,
984     item             => \@loop_data,
985     itemnumber       => $itemnumber,
986     barcode          => $item ? $item->barcode : undef,
987     itemtagfield     => $itemtagfield,
988     itemtagsubfield  => $itemtagsubfield,
989     op      => $nextop,
990     popup => scalar $input->param('popup') ? 1: 0,
991     C4::Search::enabled_staff_search_views,
992 );
993 $template->{'VARS'}->{'searchid'} = $searchid;
994
995 if ($frameworkcode eq 'FA'){
996     # fast cataloguing datas
997     $template->param(
998         'circborrowernumber' => $fa_circborrowernumber,
999         'barcode'            => $fa_barcode,
1000         'branch'             => $fa_branch,
1001         'stickyduedate'      => $fa_stickyduedate,
1002         'duedatespec'        => $fa_duedatespec,
1003     );
1004 }
1005
1006 foreach my $error (@errors) {
1007     $template->param($error => 1);
1008 }
1009 output_html_with_http_headers $input, $cookie, $template->output;