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