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