Bug 19040: Refactor GetMarcBiblio parameters
[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 strict;
23 #use warnings; FIXME - Bug 2505
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 = GetItem( $itemnumber );
78     if ( C4::Context->preference('NewItemsDefaultLocation') ) {
79         $item->{'permanent_location'} = $item->{'location'};
80         $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
81         ModItem( $item, undef, $itemnumber);
82     }
83     else {
84       $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
85       ModItem( $item, undef, $itemnumber);
86     }
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",$frameworkcode);
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) = @_;
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{repeatable} = $subfieldlib->{repeatable};
129         $subfield_data{maxlength}  = $subfieldlib->{maxlength};
130         
131         $value =~ s/"/&quot;/g;
132         if ( ! defined( $value ) || $value eq '')  {
133             $value = $subfieldlib->{defaultvalue};
134             # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
135             my $today_dt = dt_from_string;
136             my $year = $today_dt->strftime('%Y');
137             my $month = $today_dt->strftime('%m');
138             my $day = $today_dt->strftime('%d');
139             $value =~ s/<<YYYY>>/$year/g;
140             $value =~ s/<<MM>>/$month/g;
141             $value =~ s/<<DD>>/$day/g;
142             # And <<USER>> with surname (?)
143             my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
144             $value=~s/<<USER>>/$username/g;
145         }
146         
147         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
148         
149         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
150         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
151             my $CNtag       = substr($pref_itemcallnumber, 0, 3);
152             my $CNsubfield  = substr($pref_itemcallnumber, 3, 1);
153             my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
154             my $temp2 = $temp->field($CNtag);
155             if ($temp2) {
156                 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
157                 #remove any trailing space incase one subfield is used
158                 $value =~ s/^\s+|\s+$//g;
159             }
160         }
161         
162         if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
163             my $input = new CGI;
164             $value = $input->param('barcode');
165         }
166
167         # Getting list of subfields to keep when restricted editing is enabled
168         my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
169         my $allowAllSubfields = (
170             not defined $subfieldsToAllowForRestrictedEditing
171               or $subfieldsToAllowForRestrictedEditing == q||
172         ) ? 1 : 0;
173         my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
174
175         if ( $subfieldlib->{authorised_value} ) {
176             my @authorised_values;
177             my %authorised_lib;
178             # builds list, depending on authorised value...
179             if ( $subfieldlib->{authorised_value} eq "branches" ) {
180                 foreach my $thisbranch (@$branches) {
181                     push @authorised_values, $thisbranch->{branchcode};
182                     $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
183                     $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
184                 }
185             }
186             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
187                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
188                   my $itemtypes = Koha::ItemTypes->search_with_localization;
189                   while ( my $itemtype = $itemtypes->next ) {
190                       push @authorised_values, $itemtype->itemtype;
191                       $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
192                   }
193
194                   unless ( $value ) {
195                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
196                       $itype_sth->execute( $biblionumber );
197                       ( $value ) = $itype_sth->fetchrow_array;
198                   }
199           
200                   #---- class_sources
201             }
202             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
203                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
204                     
205                   my $class_sources = GetClassSources();
206                   my $default_source = C4::Context->preference("DefaultClassificationSource");
207                   
208                   foreach my $class_source (sort keys %$class_sources) {
209                       next unless $class_sources->{$class_source}->{'used'} or
210                                   ($value and $class_source eq $value)      or
211                                   ($class_source eq $default_source);
212                       push @authorised_values, $class_source;
213                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
214                   }
215                           $value = $default_source unless ($value);
216         
217                   #---- "true" authorised value
218             }
219             else {
220                   push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
221                   my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
222                   for my $r ( @$av ) {
223                       push @authorised_values, $r->{authorised_value};
224                       $authorised_lib{$r->{authorised_value}} = $r->{lib};
225                   }
226             }
227
228             if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
229                 $subfield_data{marc_value} = {
230                     type        => 'hidden',
231                     id          => $subfield_data{id},
232                     maxlength   => $subfield_data{max_length},
233                     value       => $value,
234                 };
235             }
236             else {
237                 $subfield_data{marc_value} = {
238                     type     => 'select',
239                     id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
240                     values   => \@authorised_values,
241                     labels   => \%authorised_lib,
242                     default  => $value,
243                 };
244                 # If we're on restricted editing, and our field is not in the list of subfields to allow,
245                 # then it is read-only
246                 $subfield_data{marc_value}->{readonlyselect} = (
247                     not $allowAllSubfields
248                     and $restrictededition
249                     and !grep { $tag . '$' . $subfieldtag  eq $_ } @subfieldsToAllow
250                 ) ? 1: 0;
251             }
252         }
253             # it's a thesaurus / authority field
254         elsif ( $subfieldlib->{authtypecode} ) {
255                 $subfield_data{marc_value} = {
256                     type         => 'text_auth',
257                     id           => $subfield_data{id},
258                     maxlength    => $subfield_data{max_length},
259                     value        => $value,
260                     authtypecode => $subfieldlib->{authtypecode},
261                 };
262         }
263             # it's a plugin field
264         elsif ( $subfieldlib->{value_builder} ) { # plugin
265             require Koha::FrameworkPlugin;
266             my $plugin = Koha::FrameworkPlugin->new({
267                 name => $subfieldlib->{'value_builder'},
268                 item_style => 1,
269             });
270             my $pars=  { dbh => $dbh, record => $temp, tagslib =>$tagslib,
271                 id => $subfield_data{id}, tabloop => $loop_data };
272             $plugin->build( $pars );
273             if( !$plugin->errstr ) {
274                 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
275                 $subfield_data{marc_value} = {
276                     type        => 'text_plugin',
277                     id          => $subfield_data{id},
278                     maxlength   => $subfield_data{max_length},
279                     value       => $value,
280                     class       => $class,
281                     nopopup     => $plugin->noclick,
282                     javascript  => $plugin->javascript,
283                 };
284             } else {
285                 warn $plugin->errstr;
286                 $subfield_data{marc_value} = {
287                     type        => 'text',
288                     id          => $subfield_data{id},
289                     maxlength   => $subfield_data{max_length},
290                     value       => $value,
291                 }; # supply default input form
292             }
293         }
294         elsif ( $tag eq '' ) {       # it's an hidden field
295             $subfield_data{marc_value} = {
296                 type        => 'hidden',
297                 id          => $subfield_data{id},
298                 maxlength   => $subfield_data{max_length},
299                 value       => $value,
300             };
301         }
302         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
303             $subfield_data{marc_value} = {
304                 type        => 'text',
305                 id          => $subfield_data{id},
306                 maxlength   => $subfield_data{max_length},
307                 value       => $value,
308             };
309         }
310         elsif (
311                 length($value) > 100
312                 or (
313                     C4::Context->preference("marcflavour") eq "UNIMARC"
314                     and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
315                 )
316                 or (
317                     C4::Context->preference("marcflavour") eq "MARC21"
318                     and 500 <= $tag && $tag < 600
319                 )
320               ) {
321             # oversize field (textarea)
322             $subfield_data{marc_value} = {
323                 type        => 'textarea',
324                 id          => $subfield_data{id},
325                 value       => $value,
326             };
327         } else {
328             # it's a standard field
329             $subfield_data{marc_value} = {
330                 type        => 'text',
331                 id          => $subfield_data{id},
332                 maxlength   => $subfield_data{max_length},
333                 value       => $value,
334             };
335         }
336         
337         return \%subfield_data;
338 }
339
340 # Removes some subfields when prefilling items
341 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
342 sub removeFieldsForPrefill {
343
344     my $item = shift;
345
346     # Getting item tag
347     my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
348
349     # Getting list of subfields to keep
350     my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
351
352     # Removing subfields that are not in the syspref
353     if ($tag && $subfieldsToUseWhenPrefill) {
354         my $field = $item->field($tag);
355         my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
356         foreach my $subfield ($field->subfields()) {
357             if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
358                 $field->delete_subfield(code => $subfield->[0]);
359             }
360
361         }
362     }
363
364     return $item;
365
366 }
367
368 my $input        = new CGI;
369 my $error        = $input->param('error');
370 my $biblionumber = $input->param('biblionumber');
371 my $itemnumber   = $input->param('itemnumber');
372 my $op           = $input->param('op');
373 my $hostitemnumber = $input->param('hostitemnumber');
374 my $marcflavour  = C4::Context->preference("marcflavour");
375 my $searchid     = $input->param('searchid');
376 # fast cataloguing datas
377 my $fa_circborrowernumber = $input->param('circborrowernumber');
378 my $fa_barcode            = $input->param('barcode');
379 my $fa_branch             = $input->param('branch');
380 my $fa_stickyduedate      = $input->param('stickyduedate');
381 my $fa_duedatespec        = $input->param('duedatespec');
382
383 my $frameworkcode = &GetFrameworkCode($biblionumber);
384
385 # Defining which userflag is needing according to the framework currently used
386 my $userflags;
387 if (defined $input->param('frameworkcode')) {
388     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
389 }
390
391 if (not defined $userflags) {
392     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
393 }
394
395 my ($template, $loggedinuser, $cookie)
396     = get_template_and_user({template_name => "cataloguing/additem.tt",
397                  query => $input,
398                  type => "intranet",
399                  authnotrequired => 0,
400                  flagsrequired => {editcatalogue => $userflags},
401                  debug => 1,
402                  });
403
404
405 # Does the user have a restricted item editing permission?
406 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
407 my $restrictededition = $uid ? haspermission($uid,  {'editcatalogue' => 'edit_items_restricted'}) : undef;
408 # In case user is a superlibrarian, editing is not restricted
409 $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibrarian());
410 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
411 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
412
413 my $tagslib = &GetMarcStructure(1,$frameworkcode);
414 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
415 my $oldrecord = TransformMarcToKoha($record);
416 my $itemrecord;
417 my $nextop="additem";
418 my @errors; # store errors found while checking data BEFORE saving item.
419
420 # Getting last created item cookie
421 my $prefillitem = C4::Context->preference('PrefillItem');
422 my $justaddeditem;
423 my $cookieitemrecord;
424 if ($prefillitem) {
425     my $lastitemcookie = $input->cookie('LastCreatedItem');
426     if ($lastitemcookie) {
427         $lastitemcookie = uri_unescape($lastitemcookie);
428         eval {
429             if ( thaw($lastitemcookie) ) {
430                 $cookieitemrecord = thaw($lastitemcookie);
431                 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
432             }
433         };
434         if ($@) {
435             $lastitemcookie = 'undef' unless $lastitemcookie;
436             warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
437         }
438     }
439 }
440
441 #-------------------------------------------------------------------------------
442 if ($op eq "additem") {
443
444     #-------------------------------------------------------------------------------
445     # rebuild
446     my @tags      = $input->multi_param('tag');
447     my @subfields = $input->multi_param('subfield');
448     my @values    = $input->multi_param('field_value');
449     # build indicator hash.
450     my @ind_tag   = $input->multi_param('ind_tag');
451     my @indicator = $input->multi_param('indicator');
452     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
453     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
454
455     # type of add
456     my $add_submit                 = $input->param('add_submit');
457     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
458     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
459     my $number_of_copies           = $input->param('number_of_copies');
460
461     # This is a bit tricky : if there is a cookie for the last created item and
462     # we just added an item, the cookie value is not correct yet (it will be updated
463     # next page). To prevent the form from being filled with outdated values, we
464     # force the use of "add and duplicate" feature, so the form will be filled with
465     # correct values.
466     $add_duplicate_submit = 1 if ($prefillitem);
467     $justaddeditem = 1;
468
469     # if autoBarcode is set to 'incremental', calculate barcode...
470     if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
471         $record = _increment_barcode($record, $frameworkcode);
472     }
473
474     my $addedolditem = TransformMarcToKoha( $record );
475
476     # If we have to add or add & duplicate, we add the item
477     if ( $add_submit || $add_duplicate_submit ) {
478
479         # check for item barcode # being unique
480         my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
481         push @errors, "barcode_not_unique" if ($exist_itemnumber);
482
483         # if barcode exists, don't create, but report The problem.
484         unless ($exist_itemnumber) {
485             my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
486             set_item_default_location($oldbibitemnum);
487
488             # Pushing the last created item cookie back
489             if ($prefillitem && defined $record) {
490                 my $itemcookie = $input->cookie(
491                     -name => 'LastCreatedItem',
492                     # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
493                     -value   => uri_escape_utf8( freeze( $record ) ),
494                     -HttpOnly => 1,
495                     -expires => ''
496                 );
497
498                 $cookie = [ $cookie, $itemcookie ];
499             }
500
501         }
502         $nextop = "additem";
503         if ($exist_itemnumber) {
504             $itemrecord = $record;
505         }
506     }
507
508     # If we have to add & duplicate
509     if ($add_duplicate_submit) {
510         $itemrecord = $record;
511         if (C4::Context->preference('autoBarcode') eq 'incremental') {
512             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
513         }
514         else {
515             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
516             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
517             my $fieldItem = $itemrecord->field($tagfield);
518             $itemrecord->delete_field($fieldItem);
519             $fieldItem->delete_subfields($tagsubfield);
520             $itemrecord->insert_fields_ordered($fieldItem);
521         }
522     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
523     }
524
525     # If we have to add multiple copies
526     if ($add_multiple_copies_submit) {
527
528         use C4::Barcodes;
529         my $barcodeobj = C4::Barcodes->new;
530         my $oldbarcode = $addedolditem->{'barcode'};
531         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
532
533     # If there is a barcode and we can't find their new values, we can't add multiple copies
534         my $testbarcode;
535         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
536         if ($oldbarcode && !$testbarcode) {
537
538             push @errors, "no_next_barcode";
539             $itemrecord = $record;
540
541         } else {
542         # We add each item
543
544             # For the first iteration
545             my $barcodevalue = $oldbarcode;
546             my $exist_itemnumber;
547
548
549             for (my $i = 0; $i < $number_of_copies;) {
550
551                 # If there is a barcode
552                 if ($barcodevalue) {
553
554                     # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
555                     $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
556
557                     # Putting it into the record
558                     if ($barcodevalue) {
559                         $record->field($tagfield)->update($tagsubfield => $barcodevalue);
560                     }
561
562                     # Checking if the barcode already exists
563                     $exist_itemnumber = get_item_from_barcode($barcodevalue);
564                 }
565
566                 # Adding the item
567         if (!$exist_itemnumber) {
568             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
569             set_item_default_location($oldbibitemnum);
570
571             # We count the item only if it was really added
572             # That way, all items are added, even if there was some already existing barcodes
573             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
574             $i++;
575         }
576
577                 # Preparing the next iteration
578                 $oldbarcode = $barcodevalue;
579             }
580             undef($itemrecord);
581         }
582     }   
583     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
584         print $input->redirect(
585            '/cgi-bin/koha/circ/circulation.pl?'
586            .'borrowernumber='.$fa_circborrowernumber
587            .'&barcode='.uri_escape_utf8($fa_barcode)
588            .'&duedatespec='.$fa_duedatespec
589            .'&stickyduedate=1'
590         );
591         exit;
592     }
593
594
595 #-------------------------------------------------------------------------------
596 } elsif ($op eq "edititem") {
597 #-------------------------------------------------------------------------------
598 # retrieve item if exist => then, it's a modif
599     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
600     $nextop = "saveitem";
601 #-------------------------------------------------------------------------------
602 } elsif ($op eq "dupeitem") {
603 #-------------------------------------------------------------------------------
604 # retrieve item if exist => then, it's a modif
605     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
606     if (C4::Context->preference('autoBarcode') eq 'incremental') {
607         $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
608     }
609     else {
610         # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
611         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
612         my $fieldItem = $itemrecord->field($tagfield);
613         $itemrecord->delete_field($fieldItem);
614         $fieldItem->delete_subfields($tagsubfield);
615         $itemrecord->insert_fields_ordered($fieldItem);
616     }
617
618     #check for hidden subfield and remove them for the duplicated item
619     foreach my $field ($itemrecord->fields()){
620         my $tag = $field->{_tag};
621         foreach my $subfield ($field->subfields()){
622             my $subfieldtag = $subfield->[0];
623             if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
624             ||  abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
625                 my $fieldItem = $itemrecord->field($tag);
626                 $itemrecord->delete_field($fieldItem);
627                 $fieldItem->delete_subfields($subfieldtag);
628                 $itemrecord->insert_fields_ordered($fieldItem);
629             }
630         }
631     }
632
633     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
634     $nextop = "additem";
635 #-------------------------------------------------------------------------------
636 } elsif ($op eq "delitem") {
637 #-------------------------------------------------------------------------------
638     # check that there is no issue on this item before deletion.
639     $error = &DelItemCheck( $biblionumber,$itemnumber);
640     if($error == 1){
641         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
642     }else{
643         push @errors,$error;
644         $nextop="additem";
645     }
646 #-------------------------------------------------------------------------------
647 } elsif ($op eq "delallitems") {
648 #-------------------------------------------------------------------------------
649     my $itemnumbers = C4::Items::GetItemnumbersForBiblio( $biblionumber );
650     foreach my $itemnumber ( @$itemnumbers ) {
651         $error = C4::Items::DelItemCheck( $biblionumber, $itemnumber );
652         next if $error == 1; # Means ok
653         push @errors,$error;
654     }
655     if ( @errors ) {
656         $nextop="additem";
657     } else {
658         my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
659         my $views = { C4::Search::enabled_staff_search_views };
660         if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
661             print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
662         } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
663             print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
664         } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
665             print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
666         } else {
667             print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
668         }
669         exit;
670     }
671 #-------------------------------------------------------------------------------
672 } elsif ($op eq "saveitem") {
673 #-------------------------------------------------------------------------------
674     # rebuild
675     my @tags      = $input->multi_param('tag');
676     my @subfields = $input->multi_param('subfield');
677     my @values    = $input->multi_param('field_value');
678     # build indicator hash.
679     my @ind_tag   = $input->multi_param('ind_tag');
680     my @indicator = $input->multi_param('indicator');
681     # my $itemnumber = $input->param('itemnumber');
682     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
683     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
684     # MARC::Record builded => now, record in DB
685     # warn "R: ".$record->as_formatted;
686     # check that the barcode don't exist already
687     my $addedolditem = TransformMarcToKoha($itemtosave);
688     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
689     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
690         push @errors,"barcode_not_unique";
691     } else {
692         ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
693         $itemnumber="";
694     }
695   my $item = GetItem( $itemnumber );
696     my $olditemlost =  $item->{'itemlost'};
697
698    my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
699
700    my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
701     if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
702   LostItem($itemnumber,'MARK RETURNED');
703     }
704     $nextop="additem";
705 } elsif ($op eq "delinkitem"){
706     my $analyticfield = '773';
707         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
708         $analyticfield = '773';
709     } elsif ($marcflavour eq 'UNIMARC') {
710         $analyticfield = '461';
711     }
712     foreach my $field ($record->field($analyticfield)){
713         if ($field->subfield('9') eq $hostitemnumber){
714             $record->delete_field($field);
715             last;
716         }
717     }
718         my $modbibresult = ModBiblio($record, $biblionumber,'');
719 }
720
721 #
722 #-------------------------------------------------------------------------------
723 # build screen with existing items. and "new" one
724 #-------------------------------------------------------------------------------
725
726 # now, build existiing item list
727 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
728 #my @fields = $record->fields();
729
730
731 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
732 my @big_array;
733 #---- finds where items.itemnumber is stored
734 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
735 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
736 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
737 my @fields = $temp->fields();
738
739
740 my @hostitemnumbers;
741 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
742     my $analyticfield = '773';
743     if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC') {
744         $analyticfield = '773';
745     } elsif ($marcflavour eq 'UNIMARC') {
746         $analyticfield = '461';
747     }
748     foreach my $hostfield ($temp->field($analyticfield)){
749         my $hostbiblionumber = $hostfield->subfield('0');
750         if ($hostbiblionumber){
751             my $hostrecord = GetMarcBiblio({
752                 biblionumber => $hostbiblionumber,
753                 embed_items  => 1 });
754             if ($hostrecord) {
755                 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
756                 foreach my $hostitem ($hostrecord->field($itemfield)){
757                     if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
758                         push (@fields, $hostitem);
759                         push (@hostitemnumbers, $hostfield->subfield('9'));
760                     }
761                 }
762             }
763         }
764     }
765 }
766
767
768 foreach my $field (@fields) {
769     next if ( $field->tag() < 10 );
770
771     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
772     my %this_row;
773     # loop through each subfield
774     my $i = 0;
775     foreach my $subfield (@subf){
776         my $subfieldcode = $subfield->[0];
777         my $subfieldvalue= $subfield->[1];
778
779         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
780                 && ($field->tag() ne $itemtagfield 
781                 && $subfieldcode   ne $itemtagsubfield));
782         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
783                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
784                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
785                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
786                         $subfieldcode, $subfieldvalue, '', $tagslib) 
787                                                 || $subfieldvalue;
788         }
789
790         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
791             #verifying rights
792             my $userenv = C4::Context->userenv();
793             unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
794                 $this_row{'nomod'} = 1;
795             }
796         }
797         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
798
799         if ( C4::Context->preference('EasyAnalyticalRecords') ) {
800             foreach my $hostitemnumber (@hostitemnumbers){
801             my $item = Koha::Items->find( $hostitemnumber );
802                 if ($this_row{itemnumber} eq $hostitemnumber){
803                         $this_row{hostitemflag} = 1;
804             $this_row{hostbiblionumber}= $item->biblio->biblionumber;
805                         last;
806                 }
807             }
808
809 #           my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
810 #           if ($countanalytics > 0){
811 #                $this_row{countanalytics} = $countanalytics;
812 #           }
813         }
814
815     }
816     if (%this_row) {
817         push(@big_array, \%this_row);
818     }
819 }
820
821 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
822 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
823
824 # now, construct template !
825 # First, the existing items for display
826 my @item_value_loop;
827 my @header_value_loop;
828 for my $row ( @big_array ) {
829     my %row_data;
830     my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
831     $row_data{item_value} = [ @item_fields ];
832     $row_data{itemnumber} = $row->{itemnumber};
833     #reporting this_row values
834     $row_data{'nomod'} = $row->{'nomod'};
835     $row_data{'hostitemflag'} = $row->{'hostitemflag'};
836     $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
837 #       $row_data{'countanalytics'} = $row->{'countanalytics'};
838     push(@item_value_loop,\%row_data);
839 }
840 foreach my $subfield_code (sort keys(%witness)) {
841     my %header_value;
842     $header_value{header_value} = $witness{$subfield_code};
843
844     my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
845     my $kohafield = $subfieldlib->{kohafield};
846     if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
847         $header_value{column_name} = $1;
848     }
849
850     push(@header_value_loop, \%header_value);
851 }
852
853 # now, build the item form for entering a new item
854 my @loop_data =();
855 my $i=0;
856
857 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
858
859 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
860 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
861 for my $library ( @$libraries ) {
862     $library->{selected} = 1 if $library->{branchcode} eq $branch
863 }
864
865 # We generate form, from actuel record
866 @fields = ();
867 if($itemrecord){
868     foreach my $field ($itemrecord->fields()){
869         my $tag = $field->{_tag};
870         foreach my $subfield ( $field->subfields() ){
871
872             my $subfieldtag = $subfield->[0];
873             my $value       = $subfield->[1];
874             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
875
876             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
877
878             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
879             push @fields, "$tag$subfieldtag";
880             push (@loop_data, $subfield_data);
881             $i++;
882                     }
883
884                 }
885             }
886     # and now we add fields that are empty
887
888 # Using last created item if it exists
889
890 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
891
892 # We generate form, and fill with values if defined
893 foreach my $tag ( keys %{$tagslib}){
894     foreach my $subtag (keys %{$tagslib->{$tag}}){
895         next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
896         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
897         next if any { /^$tag$subtag$/ }  @fields;
898
899         my @values = (undef);
900         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
901         for my $value (@values){
902             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
903             push (@loop_data, $subfield_data);
904             $i++;
905         }
906   }
907 }
908 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
909
910 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
911 $template->param(
912     biblionumber => $biblionumber,
913     title        => $oldrecord->{title},
914     author       => $oldrecord->{author},
915     item_loop        => \@item_value_loop,
916     item_header_loop => \@header_value_loop,
917     item             => \@loop_data,
918     itemnumber       => $itemnumber,
919     barcode          => GetBarcodeFromItemnumber($itemnumber),
920     itemtagfield     => $itemtagfield,
921     itemtagsubfield  => $itemtagsubfield,
922     op      => $nextop,
923     opisadd => ($nextop eq "saveitem") ? 0 : 1,
924     popup => scalar $input->param('popup') ? 1: 0,
925     C4::Search::enabled_staff_search_views,
926 );
927 $template->{'VARS'}->{'searchid'} = $searchid;
928
929 if ($frameworkcode eq 'FA'){
930     # fast cataloguing datas
931     $template->param(
932         'circborrowernumber' => $fa_circborrowernumber,
933         'barcode'            => $fa_barcode,
934         'branch'             => $fa_branch,
935         'stickyduedate'      => $fa_stickyduedate,
936         'duedatespec'        => $fa_duedatespec,
937     );
938 }
939
940 foreach my $error (@errors) {
941     $template->param($error => 1);
942 }
943 output_html_with_http_headers $input, $cookie, $template->output;