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