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