Bug 7639 - system preference to forgive fines on lost items - QA Followup
[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 under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use CGI;
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; # XXX subfield_is_koha_internal_p
32 use C4::Branch; # XXX subfield_is_koha_internal_p
33 use C4::ClassSource;
34 use C4::Dates;
35 use List::MoreUtils qw/any/;
36 use C4::Search;
37 use Storable qw(thaw freeze);
38 use URI::Escape;
39
40
41 use MARC::File::XML;
42 use URI::Escape;
43
44 our $dbh = C4::Context->dbh;
45
46 sub find_value {
47     my ($tagfield,$insubfield,$record) = @_;
48     my $result;
49     my $indicator;
50     foreach my $field ($record->field($tagfield)) {
51         my @subfields = $field->subfields();
52         foreach my $subfield (@subfields) {
53             if (@$subfield[0] eq $insubfield) {
54                 $result .= @$subfield[1];
55                 $indicator = $field->indicator(1).$field->indicator(2);
56             }
57         }
58     }
59     return($indicator,$result);
60 }
61
62 sub get_item_from_barcode {
63     my ($barcode)=@_;
64     my $dbh=C4::Context->dbh;
65     my $result;
66     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
67     $rq->execute($barcode);
68     ($result)=$rq->fetchrow;
69     return($result);
70 }
71
72 sub set_item_default_location {
73     my $itemnumber = shift;
74     my $item = GetItem( $itemnumber );
75     if ( C4::Context->preference('NewItemsDefaultLocation') ) {
76         $item->{'permanent_location'} = $item->{'location'};
77         $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
78         ModItem( $item, undef, $itemnumber);
79     }
80     else {
81       $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
82       ModItem( $item, undef, $itemnumber);
83     }
84 }
85
86 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
87 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
88 sub _increment_barcode {
89     my ($record, $frameworkcode) = @_;
90     my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
91     unless ($record->field($tagfield)->subfield($tagsubfield)) {
92         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
93         $sth_barcode->execute;
94         my ($newbarcode) = $sth_barcode->fetchrow;
95         $newbarcode++;
96         # OK, we have the new barcode, now create the entry in MARC record
97         my $fieldItem = $record->field($tagfield);
98         $record->delete_field($fieldItem);
99         $fieldItem->add_subfields($tagsubfield => $newbarcode);
100         $record->insert_fields_ordered($fieldItem);
101     }
102     return $record;
103 }
104
105
106 sub generate_subfield_form {
107         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $today_iso, $biblionumber, $temp, $loop_data, $i) = @_;
108   
109   my $frameworkcode = &GetFrameworkCode($biblionumber);
110         my %subfield_data;
111         my $dbh = C4::Context->dbh;
112         
113         my $index_subfield = int(rand(1000000)); 
114         if ($subfieldtag eq '@'){
115             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
116         } else {
117             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
118         }
119         
120         $subfield_data{tag}        = $tag;
121         $subfield_data{subfield}   = $subfieldtag;
122         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
123         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
124         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
125         $subfield_data{repeatable} = $subfieldlib->{repeatable};
126         $subfield_data{maxlength}  = $subfieldlib->{maxlength};
127         
128         $value =~ s/"/&quot;/g;
129         if ( ! defined( $value ) || $value eq '')  {
130             $value = $subfieldlib->{defaultvalue};
131             # get today date & replace YYYY, MM, DD if provided in the default value
132             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
133             $value =~ s/YYYY/$year/g;
134             $value =~ s/MM/$month/g;
135             $value =~ s/DD/$day/g;
136         }
137         
138         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} < -4));
139         
140         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
141         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
142             my $CNtag       = substr($pref_itemcallnumber, 0, 3);
143             my $CNsubfield  = substr($pref_itemcallnumber, 3, 1);
144             my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
145             my $temp2 = $temp->field($CNtag);
146             if ($temp2) {
147                 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
148                 #remove any trailing space incase one subfield is used
149                 $value =~ s/^\s+|\s+$//g;
150             }
151         }
152         
153         if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
154             my $input = new CGI;
155             $value = $input->param('barcode');
156         }
157         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="$subfield_data{maxlength}" );
158         my $attributes_no_value_textarea = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" rows="5" cols="64" );
159         my $attributes          = qq($attributes_no_value value="$value" );
160         
161         if ( $subfieldlib->{authorised_value} ) {
162             my @authorised_values;
163             my %authorised_lib;
164             # builds list, depending on authorised value...
165             if ( $subfieldlib->{authorised_value} eq "branches" ) {
166                 foreach my $thisbranch (@$branches) {
167                     push @authorised_values, $thisbranch->{value};
168                     $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
169                     $value = $thisbranch->{value} if $thisbranch->{selected} && !$value;
170                 }
171             }
172             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
173                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
174                   my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
175                   $sth->execute;
176                   while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
177                       push @authorised_values, $itemtype;
178                       $authorised_lib{$itemtype} = $description;
179                   }
180         
181                   unless ( $value ) {
182                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
183                       $itype_sth->execute( $biblionumber );
184                       ( $value ) = $itype_sth->fetchrow_array;
185                   }
186           
187                   #---- class_sources
188             }
189             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
190                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
191                     
192                   my $class_sources = GetClassSources();
193                   my $default_source = C4::Context->preference("DefaultClassificationSource");
194                   
195                   foreach my $class_source (sort keys %$class_sources) {
196                       next unless $class_sources->{$class_source}->{'used'} or
197                                   ($value and $class_source eq $value)      or
198                                   ($class_source eq $default_source);
199                       push @authorised_values, $class_source;
200                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
201                   }
202                           $value = $default_source unless ($value);
203         
204                   #---- "true" authorised value
205             }
206             else {
207                   push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
208                   my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
209                   for my $r ( @$av ) {
210                       push @authorised_values, $r->{authorised_value};
211                       $authorised_lib{$r->{authorised_value}} = $r->{lib};
212                   }
213             }
214
215             if ($subfieldlib->{'hidden'}) {
216                 $subfield_data{marc_value} = qq(<input type="hidden" $attributes /> $authorised_lib{$value});
217             }
218             else {
219                 $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
220                     -name     => "field_value",
221                     -values   => \@authorised_values,
222                     -default  => $value,
223                     -labels   => \%authorised_lib,
224                     -override => 1,
225                     -size     => 1,
226                     -multiple => 0,
227                     -tabindex => 1,
228                     -id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
229                     -class    => "input_marceditor",
230                 );
231             }
232
233         }
234             # it's a thesaurus / authority field
235         elsif ( $subfieldlib->{authtypecode} ) {
236                 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
237                     <a href=\"#\" class=\"buttonDot\"
238                         onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$subfieldlib->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
239             ";
240         }
241             # it's a plugin field
242         elsif ( $subfieldlib->{value_builder} ) {
243                 # opening plugin
244                 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $subfieldlib->{'value_builder'};
245                 if (do $plugin) {
246                     my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
247                     my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
248                     my $change = index($javascript, 'function Change') > -1 ?
249                         "return Change$function_name($subfield_data{random}, '$subfield_data{id}');" :
250                         'return 1;';
251                     $subfield_data{marc_value} = qq[<input type="text" $attributes
252                         onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
253                         onchange=" $change"
254                          onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
255                         <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
256                         $javascript];
257                 } else {
258                     warn "Plugin Failed: $plugin";
259                     $subfield_data{marc_value} = "<input type=\"text\" $attributes />"; # supply default input form
260                 }
261         }
262         elsif ( $tag eq '' ) {       # it's an hidden field
263             $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
264         }
265         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
266             $subfield_data{marc_value} = qq(<input type="text" $attributes />);
267         }
268         elsif ( length($value) > 100
269                     or (C4::Context->preference("marcflavour") eq "UNIMARC" and
270                           300 <= $tag && $tag < 400 && $subfieldtag eq 'a' )
271                     or (C4::Context->preference("marcflavour") eq "MARC21"  and
272                           500 <= $tag && $tag < 600                     )
273                   ) {
274             # oversize field (textarea)
275             $subfield_data{marc_value} = "<textarea $attributes_no_value_textarea>$value</textarea>\n";
276         } else {
277            # it's a standard field
278            $subfield_data{marc_value} = "<input type=\"text\" $attributes />";
279         }
280         
281         return \%subfield_data;
282 }
283
284 # Removes some subfields when prefilling items
285 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
286 sub removeFieldsForPrefill {
287
288     my $item = shift;
289
290     # Getting item tag
291     my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
292
293     # Getting list of subfields to keep
294     my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
295
296     # Removing subfields that are not in the syspref
297     if ($tag && $subfieldsToUseWhenPrefill) {
298         my $field = $item->field($tag);
299         my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
300         foreach my $subfield ($field->subfields()) {
301             if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
302                 $field->delete_subfield(code => $subfield->[0]);
303             }
304
305         }
306     }
307
308     return $item;
309
310 }
311
312 my $input        = new CGI;
313 my $error        = $input->param('error');
314 my $biblionumber = $input->param('biblionumber');
315 my $itemnumber   = $input->param('itemnumber');
316 my $op           = $input->param('op');
317 my $hostitemnumber = $input->param('hostitemnumber');
318 my $marcflavour  = C4::Context->preference("marcflavour");
319 my $searchid     = $input->param('searchid');
320 # fast cataloguing datas
321 my $fa_circborrowernumber = $input->param('circborrowernumber');
322 my $fa_barcode            = $input->param('barcode');
323 my $fa_branch             = $input->param('branch');
324 my $fa_stickyduedate      = $input->param('stickyduedate');
325 my $fa_duedatespec        = $input->param('duedatespec');
326
327 my $frameworkcode = &GetFrameworkCode($biblionumber);
328
329 # Defining which userflag is needing according to the framework currently used
330 my $userflags;
331 if (defined $input->param('frameworkcode')) {
332     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
333 }
334
335 if (not defined $userflags) {
336     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
337 }
338
339 my ($template, $loggedinuser, $cookie)
340     = get_template_and_user({template_name => "cataloguing/additem.tt",
341                  query => $input,
342                  type => "intranet",
343                  authnotrequired => 0,
344                  flagsrequired => {editcatalogue => $userflags},
345                  debug => 1,
346                  });
347
348
349 my $today_iso = C4::Dates->today('iso');
350 my $tagslib = &GetMarcStructure(1,$frameworkcode);
351 my $record = GetMarcBiblio($biblionumber);
352 my $oldrecord = TransformMarcToKoha($dbh,$record);
353 my $itemrecord;
354 my $nextop="additem";
355 my @errors; # store errors found while checking data BEFORE saving item.
356
357 # Getting last created item cookie
358 my $prefillitem = C4::Context->preference('PrefillItem');
359 my $justaddeditem;
360 my $cookieitemrecord;
361 if ($prefillitem) {
362     my $lastitemcookie = $input->cookie('LastCreatedItem');
363     if ($lastitemcookie) {
364         $lastitemcookie = uri_unescape($lastitemcookie);
365         if ( thaw($lastitemcookie) ) {
366             $cookieitemrecord = thaw($lastitemcookie) ;
367             $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
368         }
369     }
370 }
371
372 #-------------------------------------------------------------------------------
373 if ($op eq "additem") {
374
375     #-------------------------------------------------------------------------------
376     # rebuild
377     my @tags      = $input->param('tag');
378     my @subfields = $input->param('subfield');
379     my @values    = $input->param('field_value');
380     # build indicator hash.
381     my @ind_tag   = $input->param('ind_tag');
382     my @indicator = $input->param('indicator');
383     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
384     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
385
386     # type of add
387     my $add_submit                 = $input->param('add_submit');
388     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
389     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
390     my $number_of_copies           = $input->param('number_of_copies');
391
392     # This is a bit tricky : if there is a cookie for the last created item and
393     # we just added an item, the cookie value is not correct yet (it will be updated
394     # next page). To prevent the form from being filled with outdated values, we
395     # force the use of "add and duplicate" feature, so the form will be filled with
396     # correct values.
397     $add_duplicate_submit = 1 if ($prefillitem);
398     $justaddeditem = 1;
399
400     # if autoBarcode is set to 'incremental', calculate barcode...
401     if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
402         $record = _increment_barcode($record, $frameworkcode);
403     }
404
405
406     if (C4::Context->preference('autoBarcode') eq 'incremental') {
407         $record = _increment_barcode($record, $frameworkcode);
408     }
409
410     my $addedolditem = TransformMarcToKoha( $dbh, $record );
411
412     # If we have to add or add & duplicate, we add the item
413     if ( $add_submit || $add_duplicate_submit ) {
414
415         # check for item barcode # being unique
416         my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
417         push @errors, "barcode_not_unique" if ($exist_itemnumber);
418
419         # if barcode exists, don't create, but report The problem.
420         unless ($exist_itemnumber) {
421             my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
422             set_item_default_location($oldbibitemnum);
423
424             # Pushing the last created item cookie back
425             if ($prefillitem && defined $record) {
426                 my $itemcookie = $input->cookie(
427                     -name => 'LastCreatedItem',
428                     # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
429                     -value   => uri_escape_utf8( freeze( $record ) ),
430                     -HttpOnly => 1,
431                     -expires => ''
432                 );
433
434                 $cookie = [ $cookie, $itemcookie ];
435             }
436
437         }
438         $nextop = "additem";
439         if ($exist_itemnumber) {
440             $itemrecord = $record;
441         }
442     }
443
444     # If we have to add & duplicate
445     if ($add_duplicate_submit) {
446         $itemrecord = $record;
447         if (C4::Context->preference('autoBarcode') eq 'incremental') {
448             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
449         }
450         else {
451             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
452             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
453             my $fieldItem = $itemrecord->field($tagfield);
454             $itemrecord->delete_field($fieldItem);
455             $fieldItem->delete_subfields($tagsubfield);
456             $itemrecord->insert_fields_ordered($fieldItem);
457         }
458     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
459     }
460
461     # If we have to add multiple copies
462     if ($add_multiple_copies_submit) {
463
464         use C4::Barcodes;
465         my $barcodeobj = C4::Barcodes->new;
466         my $oldbarcode = $addedolditem->{'barcode'};
467         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
468
469         # If there is a barcode and we can't find him new values, we can't add multiple copies
470         my $testbarcode;
471         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
472         if ($oldbarcode && !$testbarcode) {
473
474             push @errors, "no_next_barcode";
475             $itemrecord = $record;
476
477         } else {
478         # We add each item
479
480             # For the first iteration
481             my $barcodevalue = $oldbarcode;
482             my $exist_itemnumber;
483
484
485             for (my $i = 0; $i < $number_of_copies;) {
486
487                 # If there is a barcode
488                 if ($barcodevalue) {
489
490                     # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
491                     $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
492
493                     # Putting it into the record
494                     if ($barcodevalue) {
495                         $record->field($tagfield)->update($tagsubfield => $barcodevalue);
496                     }
497
498                     # Checking if the barcode already exists
499                     $exist_itemnumber = get_item_from_barcode($barcodevalue);
500                 }
501
502                 # Adding the item
503         if (!$exist_itemnumber) {
504             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
505             set_item_default_location($oldbibitemnum);
506
507             # We count the item only if it was really added
508             # That way, all items are added, even if there was some already existing barcodes
509             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
510             $i++;
511         }
512
513                 # Preparing the next iteration
514                 $oldbarcode = $barcodevalue;
515             }
516             undef($itemrecord);
517         }
518     }   
519     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
520         print $input->redirect(
521            '/cgi-bin/koha/circ/circulation.pl?'
522            .'borrowernumber='.$fa_circborrowernumber
523            .'&barcode='.uri_escape($fa_barcode)
524            .'&duedatespec='.$fa_duedatespec
525            .'&stickyduedate=1'
526         );
527         exit;
528     }
529
530
531 #-------------------------------------------------------------------------------
532 } elsif ($op eq "edititem") {
533 #-------------------------------------------------------------------------------
534 # retrieve item if exist => then, it's a modif
535     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
536     $nextop = "saveitem";
537 #-------------------------------------------------------------------------------
538 } elsif ($op eq "delitem") {
539 #-------------------------------------------------------------------------------
540     # check that there is no issue on this item before deletion.
541     $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
542     if($error == 1){
543         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
544     }else{
545         push @errors,$error;
546         $nextop="additem";
547     }
548 #-------------------------------------------------------------------------------
549 } elsif ($op eq "delallitems") {
550 #-------------------------------------------------------------------------------
551     my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
552     my $errortest=0;
553     my $itemfail;
554     foreach my $biblioitem (@biblioitems) {
555         my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
556
557         foreach my $item (@$items) {
558             $error =&DelItemCheck( $dbh, $biblionumber, $item->{itemnumber} );
559             $itemfail =$item;
560         if($error == 1){
561             next
562             }
563         else {
564             push @errors,$error;
565             $errortest++
566             }
567         }
568         if($errortest > 0){
569             $nextop="additem";
570         } 
571         else {
572             my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
573             my $views = { C4::Search::enabled_staff_search_views };
574             if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
575                 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
576             } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
577                 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
578             } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
579                 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
580             } else {
581                 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
582             }
583             exit;
584         }
585         }
586 #-------------------------------------------------------------------------------
587 } elsif ($op eq "saveitem") {
588 #-------------------------------------------------------------------------------
589     # rebuild
590     my @tags      = $input->param('tag');
591     my @subfields = $input->param('subfield');
592     my @values    = $input->param('field_value');
593     # build indicator hash.
594     my @ind_tag   = $input->param('ind_tag');
595     my @indicator = $input->param('indicator');
596     # my $itemnumber = $input->param('itemnumber');
597     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
598     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
599     # MARC::Record builded => now, record in DB
600     # warn "R: ".$record->as_formatted;
601     # check that the barcode don't exist already
602     my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
603     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
604     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
605         push @errors,"barcode_not_unique";
606     } else {
607         ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
608         $itemnumber="";
609     }
610   my $item = GetItem( $itemnumber );
611     my $olditemlost =  $item->{'itemlost'};
612
613    my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
614
615    my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
616     if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
617   LostItem($itemnumber,'MARK RETURNED');
618     }
619     $nextop="additem";
620 } elsif ($op eq "delinkitem"){
621     my $analyticfield = '773';
622         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
623         $analyticfield = '773';
624     } elsif ($marcflavour eq 'UNIMARC') {
625         $analyticfield = '461';
626     }
627     foreach my $field ($record->field($analyticfield)){
628         if ($field->subfield('9') eq $hostitemnumber){
629             $record->delete_field($field);
630             last;
631         }
632     }
633         my $modbibresult = ModBiblio($record, $biblionumber,'');
634 }
635
636 #
637 #-------------------------------------------------------------------------------
638 # build screen with existing items. and "new" one
639 #-------------------------------------------------------------------------------
640
641 # now, build existiing item list
642 my $temp = GetMarcBiblio( $biblionumber );
643 #my @fields = $record->fields();
644
645
646 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
647 my @big_array;
648 #---- finds where items.itemnumber is stored
649 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
650 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
651 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
652 my @fields = $temp->fields();
653
654
655 my @hostitemnumbers;
656 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
657     my $analyticfield = '773';
658     if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC') {
659         $analyticfield = '773';
660     } elsif ($marcflavour eq 'UNIMARC') {
661         $analyticfield = '461';
662     }
663     foreach my $hostfield ($temp->field($analyticfield)){
664         my $hostbiblionumber = $hostfield->subfield('0');
665         if ($hostbiblionumber){
666             my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
667             if ($hostrecord) {
668                 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
669                 foreach my $hostitem ($hostrecord->field($itemfield)){
670                     if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
671                         push (@fields, $hostitem);
672                         push (@hostitemnumbers, $hostfield->subfield('9'));
673                     }
674                 }
675             }
676         }
677     }
678 }
679
680
681 foreach my $field (@fields) {
682     next if ( $field->tag() < 10 );
683
684     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
685     my %this_row;
686     # loop through each subfield
687     my $i = 0;
688     foreach my $subfield (@subf){
689         my $subfieldcode = $subfield->[0];
690         my $subfieldvalue= $subfield->[1];
691
692         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
693                 && ($field->tag() ne $itemtagfield 
694                 && $subfieldcode   ne $itemtagsubfield));
695         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
696                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
697                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
698                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
699                         $subfieldcode, $subfieldvalue, '', $tagslib) 
700                                                 || $subfieldvalue;
701         }
702
703         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
704             #verifying rights
705             my $userenv = C4::Context->userenv();
706             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subfieldvalue))){
707                 $this_row{'nomod'} = 1;
708             }
709         }
710         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
711
712         if ( C4::Context->preference('EasyAnalyticalRecords') ) {
713             foreach my $hostitemnumber (@hostitemnumbers){
714                 if ($this_row{itemnumber} eq $hostitemnumber){
715                         $this_row{hostitemflag} = 1;
716                         $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
717                         last;
718                 }
719             }
720
721 #           my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
722 #           if ($countanalytics > 0){
723 #                $this_row{countanalytics} = $countanalytics;
724 #           }
725         }
726
727     }
728     if (%this_row) {
729         push(@big_array, \%this_row);
730     }
731 }
732
733 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
734 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
735
736 # now, construct template !
737 # First, the existing items for display
738 my @item_value_loop;
739 my @header_value_loop;
740 for my $row ( @big_array ) {
741     my %row_data;
742     my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
743     $row_data{item_value} = [ @item_fields ];
744     $row_data{itemnumber} = $row->{itemnumber};
745     #reporting this_row values
746     $row_data{'nomod'} = $row->{'nomod'};
747     $row_data{'hostitemflag'} = $row->{'hostitemflag'};
748     $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
749 #       $row_data{'countanalytics'} = $row->{'countanalytics'};
750     push(@item_value_loop,\%row_data);
751 }
752 foreach my $subfield_code (sort keys(%witness)) {
753     my %header_value;
754     $header_value{header_value} = $witness{$subfield_code};
755     push(@header_value_loop, \%header_value);
756 }
757
758 # now, build the item form for entering a new item
759 my @loop_data =();
760 my $i=0;
761
762 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
763
764 my $onlymine = C4::Context->preference('IndependentBranches') &&
765                C4::Context->userenv                           && 
766                C4::Context->userenv->{flags}!=1               && 
767                C4::Context->userenv->{branch};
768 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
769 my $branches = GetBranchesLoop($branch,$onlymine);  # build once ahead of time, instead of multiple times later.
770
771 # We generate form, from actuel record
772 @fields = ();
773 if($itemrecord){
774     foreach my $field ($itemrecord->fields()){
775         my $tag = $field->{_tag};
776         foreach my $subfield ( $field->subfields() ){
777
778             my $subfieldtag = $subfield->[0];
779             my $value       = $subfield->[1];
780             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
781
782             next if subfield_is_koha_internal_p($subfieldtag);
783             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
784
785             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);        
786
787             push @fields, "$tag$subfieldtag";
788             push (@loop_data, $subfield_data);
789             $i++;
790                     }
791
792                 }
793             }
794     # and now we add fields that are empty
795
796 # Using last created item if it exists
797
798 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
799
800 # We generate form, and fill with values if defined
801 foreach my $tag ( keys %{$tagslib}){
802     foreach my $subtag (keys %{$tagslib->{$tag}}){
803         next if subfield_is_koha_internal_p($subtag);
804         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
805         next if any { /^$tag$subtag$/ }  @fields;
806
807         my @values = (undef);
808         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
809         for my $value (@values){
810             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i); 
811             push (@loop_data, $subfield_data);
812             $i++;
813         } 
814   }
815 }
816 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
817
818 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
819 $template->param( title => $record->title() ) if ($record ne "-1");
820 $template->param(
821     biblionumber => $biblionumber,
822     title        => $oldrecord->{title},
823     author       => $oldrecord->{author},
824     item_loop        => \@item_value_loop,
825     item_header_loop => \@header_value_loop,
826     item             => \@loop_data,
827     itemnumber       => $itemnumber,
828     barcode          => GetBarcodeFromItemnumber($itemnumber),
829     itemtagfield     => $itemtagfield,
830     itemtagsubfield  => $itemtagsubfield,
831     op      => $nextop,
832     opisadd => ($nextop eq "saveitem") ? 0 : 1,
833     popup => $input->param('popup') ? 1: 0,
834     C4::Search::enabled_staff_search_views,
835 );
836 $template->{'VARS'}->{'searchid'} = $searchid;
837
838 if ($frameworkcode eq 'FA'){
839     # fast cataloguing datas
840     $template->param(
841         'circborrowernumber' => $fa_circborrowernumber,
842         'barcode'            => $fa_barcode,
843         'branch'             => $fa_branch,
844         'stickyduedate'      => $fa_stickyduedate,
845         'duedatespec'        => $fa_duedatespec,
846     );
847 }
848
849 foreach my $error (@errors) {
850     $template->param($error => 1);
851 }
852 output_html_with_http_headers $input, $cookie, $template->output;