Bug 18452: Correcting 'url' to say 'URL' in catalog detail
[koha.git] / cataloguing / additem.pl
blob1ee8d825b55dd41f1f6d150eb6da0864d0b71c11
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
7 # This file is part of Koha.
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.
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.
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>.
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;
32 use C4::ClassSource;
33 use Koha::DateUtils;
34 use Koha::ItemTypes;
35 use Koha::Libraries;
36 use List::MoreUtils qw/any/;
37 use C4::Search;
38 use Storable qw(thaw freeze);
39 use URI::Escape;
40 use C4::Members;
42 use MARC::File::XML;
43 use URI::Escape;
45 our $dbh = C4::Context->dbh;
47 sub find_value {
48 my ($tagfield,$insubfield,$record) = @_;
49 my $result;
50 my $indicator;
51 foreach my $field ($record->field($tagfield)) {
52 my @subfields = $field->subfields();
53 foreach my $subfield (@subfields) {
54 if (@$subfield[0] eq $insubfield) {
55 $result .= @$subfield[1];
56 $indicator = $field->indicator(1).$field->indicator(2);
60 return($indicator,$result);
63 sub get_item_from_barcode {
64 my ($barcode)=@_;
65 my $dbh=C4::Context->dbh;
66 my $result;
67 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
68 $rq->execute($barcode);
69 ($result)=$rq->fetchrow;
70 return($result);
73 sub set_item_default_location {
74 my $itemnumber = shift;
75 my $item = GetItem( $itemnumber );
76 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
77 $item->{'permanent_location'} = $item->{'location'};
78 $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
79 ModItem( $item, undef, $itemnumber);
81 else {
82 $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
83 ModItem( $item, undef, $itemnumber);
87 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
88 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
89 sub _increment_barcode {
90 my ($record, $frameworkcode) = @_;
91 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
92 unless ($record->field($tagfield)->subfield($tagsubfield)) {
93 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
94 $sth_barcode->execute;
95 my ($newbarcode) = $sth_barcode->fetchrow;
96 $newbarcode++;
97 # OK, we have the new barcode, now create the entry in MARC record
98 my $fieldItem = $record->field($tagfield);
99 $record->delete_field($fieldItem);
100 $fieldItem->add_subfields($tagsubfield => $newbarcode);
101 $record->insert_fields_ordered($fieldItem);
103 return $record;
107 sub generate_subfield_form {
108 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
110 my $frameworkcode = &GetFrameworkCode($biblionumber);
112 my %subfield_data;
113 my $dbh = C4::Context->dbh;
115 my $index_subfield = int(rand(1000000));
116 if ($subfieldtag eq '@'){
117 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
118 } else {
119 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
122 $subfield_data{tag} = $tag;
123 $subfield_data{subfield} = $subfieldtag;
124 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
125 $subfield_data{mandatory} = $subfieldlib->{mandatory};
126 $subfield_data{repeatable} = $subfieldlib->{repeatable};
127 $subfield_data{maxlength} = $subfieldlib->{maxlength};
129 $value =~ s/"/&quot;/g;
130 if ( ! defined( $value ) || $value eq '') {
131 $value = $subfieldlib->{defaultvalue};
132 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
133 my $today_dt = dt_from_string;
134 my $year = $today_dt->strftime('%Y');
135 my $month = $today_dt->strftime('%m');
136 my $day = $today_dt->strftime('%d');
137 $value =~ s/<<YYYY>>/$year/g;
138 $value =~ s/<<MM>>/$month/g;
139 $value =~ s/<<DD>>/$day/g;
140 # And <<USER>> with surname (?)
141 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
142 $value=~s/<<USER>>/$username/g;
145 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
147 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
148 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
149 my $CNtag = substr($pref_itemcallnumber, 0, 3);
150 my $CNsubfield = substr($pref_itemcallnumber, 3, 1);
151 my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
152 my $temp2 = $temp->field($CNtag);
153 if ($temp2) {
154 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
155 #remove any trailing space incase one subfield is used
156 $value =~ s/^\s+|\s+$//g;
160 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
161 my $input = new CGI;
162 $value = $input->param('barcode');
165 # Getting list of subfields to keep when restricted editing is enabled
166 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
167 my $allowAllSubfields = (
168 not defined $subfieldsToAllowForRestrictedEditing
169 or $subfieldsToAllowForRestrictedEditing == q||
170 ) ? 1 : 0;
171 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
173 if ( $subfieldlib->{authorised_value} ) {
174 my @authorised_values;
175 my %authorised_lib;
176 # builds list, depending on authorised value...
177 if ( $subfieldlib->{authorised_value} eq "branches" ) {
178 foreach my $thisbranch (@$branches) {
179 push @authorised_values, $thisbranch->{branchcode};
180 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
181 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
184 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
185 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
186 my $itemtypes = Koha::ItemTypes->search_with_localization;
187 while ( my $itemtype = $itemtypes->next ) {
188 push @authorised_values, $itemtype->itemtype;
189 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
192 unless ( $value ) {
193 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
194 $itype_sth->execute( $biblionumber );
195 ( $value ) = $itype_sth->fetchrow_array;
198 #---- class_sources
200 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
201 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
203 my $class_sources = GetClassSources();
204 my $default_source = C4::Context->preference("DefaultClassificationSource");
206 foreach my $class_source (sort keys %$class_sources) {
207 next unless $class_sources->{$class_source}->{'used'} or
208 ($value and $class_source eq $value) or
209 ($class_source eq $default_source);
210 push @authorised_values, $class_source;
211 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
213 $value = $default_source unless ($value);
215 #---- "true" authorised value
217 else {
218 push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
219 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
220 for my $r ( @$av ) {
221 push @authorised_values, $r->{authorised_value};
222 $authorised_lib{$r->{authorised_value}} = $r->{lib};
226 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
227 $subfield_data{marc_value} = {
228 type => 'hidden',
229 id => $subfield_data{id},
230 maxlength => $subfield_data{max_length},
231 value => $value,
234 else {
235 $subfield_data{marc_value} = {
236 type => 'select',
237 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
238 values => \@authorised_values,
239 labels => \%authorised_lib,
240 default => $value,
242 # If we're on restricted editing, and our field is not in the list of subfields to allow,
243 # then it is read-only
244 $subfield_data{marc_value}->{readonlyselect} = (
245 not $allowAllSubfields
246 and $restrictededition
247 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
248 ) ? 1: 0;
251 # it's a thesaurus / authority field
252 elsif ( $subfieldlib->{authtypecode} ) {
253 $subfield_data{marc_value} = {
254 type => 'text_auth',
255 id => $subfield_data{id},
256 maxlength => $subfield_data{max_length},
257 value => $value,
258 authtypecode => $subfieldlib->{authtypecode},
261 # it's a plugin field
262 elsif ( $subfieldlib->{value_builder} ) { # plugin
263 require Koha::FrameworkPlugin;
264 my $plugin = Koha::FrameworkPlugin->new({
265 name => $subfieldlib->{'value_builder'},
266 item_style => 1,
268 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
269 id => $subfield_data{id}, tabloop => $loop_data };
270 $plugin->build( $pars );
271 if( !$plugin->errstr ) {
272 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
273 $subfield_data{marc_value} = {
274 type => 'text_plugin',
275 id => $subfield_data{id},
276 maxlength => $subfield_data{max_length},
277 value => $value,
278 class => $class,
279 nopopup => $plugin->noclick,
280 javascript => $plugin->javascript,
282 } else {
283 warn $plugin->errstr;
284 $subfield_data{marc_value} = {
285 type => 'text',
286 id => $subfield_data{id},
287 maxlength => $subfield_data{max_length},
288 value => $value,
289 }; # supply default input form
292 elsif ( $tag eq '' ) { # it's an hidden field
293 $subfield_data{marc_value} = {
294 type => 'hidden',
295 id => $subfield_data{id},
296 maxlength => $subfield_data{max_length},
297 value => $value,
300 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
301 $subfield_data{marc_value} = {
302 type => 'text',
303 id => $subfield_data{id},
304 maxlength => $subfield_data{max_length},
305 value => $value,
308 elsif (
309 length($value) > 100
310 or (
311 C4::Context->preference("marcflavour") eq "UNIMARC"
312 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
314 or (
315 C4::Context->preference("marcflavour") eq "MARC21"
316 and 500 <= $tag && $tag < 600
319 # oversize field (textarea)
320 $subfield_data{marc_value} = {
321 type => 'textarea',
322 id => $subfield_data{id},
323 value => $value,
325 } else {
326 # it's a standard field
327 $subfield_data{marc_value} = {
328 type => 'text',
329 id => $subfield_data{id},
330 maxlength => $subfield_data{max_length},
331 value => $value,
335 return \%subfield_data;
338 # Removes some subfields when prefilling items
339 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
340 sub removeFieldsForPrefill {
342 my $item = shift;
344 # Getting item tag
345 my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
347 # Getting list of subfields to keep
348 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
350 # Removing subfields that are not in the syspref
351 if ($tag && $subfieldsToUseWhenPrefill) {
352 my $field = $item->field($tag);
353 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
354 foreach my $subfield ($field->subfields()) {
355 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
356 $field->delete_subfield(code => $subfield->[0]);
362 return $item;
366 my $input = new CGI;
367 my $error = $input->param('error');
368 my $biblionumber = $input->param('biblionumber');
369 my $itemnumber = $input->param('itemnumber');
370 my $op = $input->param('op');
371 my $hostitemnumber = $input->param('hostitemnumber');
372 my $marcflavour = C4::Context->preference("marcflavour");
373 my $searchid = $input->param('searchid');
374 # fast cataloguing datas
375 my $fa_circborrowernumber = $input->param('circborrowernumber');
376 my $fa_barcode = $input->param('barcode');
377 my $fa_branch = $input->param('branch');
378 my $fa_stickyduedate = $input->param('stickyduedate');
379 my $fa_duedatespec = $input->param('duedatespec');
381 my $frameworkcode = &GetFrameworkCode($biblionumber);
383 # Defining which userflag is needing according to the framework currently used
384 my $userflags;
385 if (defined $input->param('frameworkcode')) {
386 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
389 if (not defined $userflags) {
390 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
393 my ($template, $loggedinuser, $cookie)
394 = get_template_and_user({template_name => "cataloguing/additem.tt",
395 query => $input,
396 type => "intranet",
397 authnotrequired => 0,
398 flagsrequired => {editcatalogue => $userflags},
399 debug => 1,
403 # Does the user have a restricted item editing permission?
404 my $uid = $loggedinuser ? GetMember( borrowernumber => $loggedinuser )->{userid} : undef;
405 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
406 # In case user is a superlibrarian, editing is not restricted
407 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
408 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
409 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
411 my $tagslib = &GetMarcStructure(1,$frameworkcode);
412 my $record = GetMarcBiblio($biblionumber);
413 my $oldrecord = TransformMarcToKoha($record);
414 my $itemrecord;
415 my $nextop="additem";
416 my @errors; # store errors found while checking data BEFORE saving item.
418 # Getting last created item cookie
419 my $prefillitem = C4::Context->preference('PrefillItem');
420 my $justaddeditem;
421 my $cookieitemrecord;
422 if ($prefillitem) {
423 my $lastitemcookie = $input->cookie('LastCreatedItem');
424 if ($lastitemcookie) {
425 $lastitemcookie = uri_unescape($lastitemcookie);
426 eval {
427 if ( thaw($lastitemcookie) ) {
428 $cookieitemrecord = thaw($lastitemcookie);
429 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
432 if ($@) {
433 $lastitemcookie = 'undef' unless $lastitemcookie;
434 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
439 #-------------------------------------------------------------------------------
440 if ($op eq "additem") {
442 #-------------------------------------------------------------------------------
443 # rebuild
444 my @tags = $input->multi_param('tag');
445 my @subfields = $input->multi_param('subfield');
446 my @values = $input->multi_param('field_value');
447 # build indicator hash.
448 my @ind_tag = $input->multi_param('ind_tag');
449 my @indicator = $input->multi_param('indicator');
450 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
451 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
453 # type of add
454 my $add_submit = $input->param('add_submit');
455 my $add_duplicate_submit = $input->param('add_duplicate_submit');
456 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
457 my $number_of_copies = $input->param('number_of_copies');
459 # This is a bit tricky : if there is a cookie for the last created item and
460 # we just added an item, the cookie value is not correct yet (it will be updated
461 # next page). To prevent the form from being filled with outdated values, we
462 # force the use of "add and duplicate" feature, so the form will be filled with
463 # correct values.
464 $add_duplicate_submit = 1 if ($prefillitem);
465 $justaddeditem = 1;
467 # if autoBarcode is set to 'incremental', calculate barcode...
468 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
469 $record = _increment_barcode($record, $frameworkcode);
472 my $addedolditem = TransformMarcToKoha( $record );
474 # If we have to add or add & duplicate, we add the item
475 if ( $add_submit || $add_duplicate_submit ) {
477 # check for item barcode # being unique
478 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
479 push @errors, "barcode_not_unique" if ($exist_itemnumber);
481 # if barcode exists, don't create, but report The problem.
482 unless ($exist_itemnumber) {
483 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
484 set_item_default_location($oldbibitemnum);
486 # Pushing the last created item cookie back
487 if ($prefillitem && defined $record) {
488 my $itemcookie = $input->cookie(
489 -name => 'LastCreatedItem',
490 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
491 -value => uri_escape_utf8( freeze( $record ) ),
492 -HttpOnly => 1,
493 -expires => ''
496 $cookie = [ $cookie, $itemcookie ];
500 $nextop = "additem";
501 if ($exist_itemnumber) {
502 $itemrecord = $record;
506 # If we have to add & duplicate
507 if ($add_duplicate_submit) {
508 $itemrecord = $record;
509 if (C4::Context->preference('autoBarcode') eq 'incremental') {
510 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
512 else {
513 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
514 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
515 my $fieldItem = $itemrecord->field($tagfield);
516 $itemrecord->delete_field($fieldItem);
517 $fieldItem->delete_subfields($tagsubfield);
518 $itemrecord->insert_fields_ordered($fieldItem);
520 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
523 # If we have to add multiple copies
524 if ($add_multiple_copies_submit) {
526 use C4::Barcodes;
527 my $barcodeobj = C4::Barcodes->new;
528 my $oldbarcode = $addedolditem->{'barcode'};
529 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
531 # If there is a barcode and we can't find their new values, we can't add multiple copies
532 my $testbarcode;
533 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
534 if ($oldbarcode && !$testbarcode) {
536 push @errors, "no_next_barcode";
537 $itemrecord = $record;
539 } else {
540 # We add each item
542 # For the first iteration
543 my $barcodevalue = $oldbarcode;
544 my $exist_itemnumber;
547 for (my $i = 0; $i < $number_of_copies;) {
549 # If there is a barcode
550 if ($barcodevalue) {
552 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
553 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
555 # Putting it into the record
556 if ($barcodevalue) {
557 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
560 # Checking if the barcode already exists
561 $exist_itemnumber = get_item_from_barcode($barcodevalue);
564 # Adding the item
565 if (!$exist_itemnumber) {
566 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
567 set_item_default_location($oldbibitemnum);
569 # We count the item only if it was really added
570 # That way, all items are added, even if there was some already existing barcodes
571 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
572 $i++;
575 # Preparing the next iteration
576 $oldbarcode = $barcodevalue;
578 undef($itemrecord);
581 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
582 print $input->redirect(
583 '/cgi-bin/koha/circ/circulation.pl?'
584 .'borrowernumber='.$fa_circborrowernumber
585 .'&barcode='.uri_escape_utf8($fa_barcode)
586 .'&duedatespec='.$fa_duedatespec
587 .'&stickyduedate=1'
589 exit;
593 #-------------------------------------------------------------------------------
594 } elsif ($op eq "edititem") {
595 #-------------------------------------------------------------------------------
596 # retrieve item if exist => then, it's a modif
597 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
598 $nextop = "saveitem";
599 #-------------------------------------------------------------------------------
600 } elsif ($op eq "dupeitem") {
601 #-------------------------------------------------------------------------------
602 # retrieve item if exist => then, it's a modif
603 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
604 if (C4::Context->preference('autoBarcode') eq 'incremental') {
605 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
607 else {
608 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
609 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
610 my $fieldItem = $itemrecord->field($tagfield);
611 $itemrecord->delete_field($fieldItem);
612 $fieldItem->delete_subfields($tagsubfield);
613 $itemrecord->insert_fields_ordered($fieldItem);
616 #check for hidden subfield and remove them for the duplicated item
617 foreach my $field ($itemrecord->fields()){
618 my $tag = $field->{_tag};
619 foreach my $subfield ($field->subfields()){
620 my $subfieldtag = $subfield->[0];
621 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
622 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
623 my $fieldItem = $itemrecord->field($tag);
624 $itemrecord->delete_field($fieldItem);
625 $fieldItem->delete_subfields($subfieldtag);
626 $itemrecord->insert_fields_ordered($fieldItem);
631 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
632 $nextop = "additem";
633 #-------------------------------------------------------------------------------
634 } elsif ($op eq "delitem") {
635 #-------------------------------------------------------------------------------
636 # check that there is no issue on this item before deletion.
637 $error = &DelItemCheck( $biblionumber,$itemnumber);
638 if($error == 1){
639 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
640 }else{
641 push @errors,$error;
642 $nextop="additem";
644 #-------------------------------------------------------------------------------
645 } elsif ($op eq "delallitems") {
646 #-------------------------------------------------------------------------------
647 my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
648 my $errortest=0;
649 my $itemfail;
650 foreach my $biblioitem (@biblioitems) {
651 my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
653 foreach my $item (@$items) {
654 $error =&DelItemCheck( $biblionumber, $item->{itemnumber} );
655 $itemfail =$item;
656 if($error == 1){
657 next
659 else {
660 push @errors,$error;
661 $errortest++
664 if($errortest > 0){
665 $nextop="additem";
667 else {
668 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
669 my $views = { C4::Search::enabled_staff_search_views };
670 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
671 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
672 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
673 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
674 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
675 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
676 } else {
677 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
679 exit;
682 #-------------------------------------------------------------------------------
683 } elsif ($op eq "saveitem") {
684 #-------------------------------------------------------------------------------
685 # rebuild
686 my @tags = $input->multi_param('tag');
687 my @subfields = $input->multi_param('subfield');
688 my @values = $input->multi_param('field_value');
689 # build indicator hash.
690 my @ind_tag = $input->multi_param('ind_tag');
691 my @indicator = $input->multi_param('indicator');
692 # my $itemnumber = $input->param('itemnumber');
693 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
694 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
695 # MARC::Record builded => now, record in DB
696 # warn "R: ".$record->as_formatted;
697 # check that the barcode don't exist already
698 my $addedolditem = TransformMarcToKoha($itemtosave);
699 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
700 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
701 push @errors,"barcode_not_unique";
702 } else {
703 ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
704 $itemnumber="";
706 my $item = GetItem( $itemnumber );
707 my $olditemlost = $item->{'itemlost'};
709 my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
711 my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
712 if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
713 LostItem($itemnumber,'MARK RETURNED');
715 $nextop="additem";
716 } elsif ($op eq "delinkitem"){
717 my $analyticfield = '773';
718 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
719 $analyticfield = '773';
720 } elsif ($marcflavour eq 'UNIMARC') {
721 $analyticfield = '461';
723 foreach my $field ($record->field($analyticfield)){
724 if ($field->subfield('9') eq $hostitemnumber){
725 $record->delete_field($field);
726 last;
729 my $modbibresult = ModBiblio($record, $biblionumber,'');
733 #-------------------------------------------------------------------------------
734 # build screen with existing items. and "new" one
735 #-------------------------------------------------------------------------------
737 # now, build existiing item list
738 my $temp = GetMarcBiblio( $biblionumber );
739 #my @fields = $record->fields();
742 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
743 my @big_array;
744 #---- finds where items.itemnumber is stored
745 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
746 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
747 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
748 my @fields = $temp->fields();
751 my @hostitemnumbers;
752 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
753 my $analyticfield = '773';
754 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
755 $analyticfield = '773';
756 } elsif ($marcflavour eq 'UNIMARC') {
757 $analyticfield = '461';
759 foreach my $hostfield ($temp->field($analyticfield)){
760 my $hostbiblionumber = $hostfield->subfield('0');
761 if ($hostbiblionumber){
762 my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
763 if ($hostrecord) {
764 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
765 foreach my $hostitem ($hostrecord->field($itemfield)){
766 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
767 push (@fields, $hostitem);
768 push (@hostitemnumbers, $hostfield->subfield('9'));
777 foreach my $field (@fields) {
778 next if ( $field->tag() < 10 );
780 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
781 my %this_row;
782 # loop through each subfield
783 my $i = 0;
784 foreach my $subfield (@subf){
785 my $subfieldcode = $subfield->[0];
786 my $subfieldvalue= $subfield->[1];
788 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
789 && ($field->tag() ne $itemtagfield
790 && $subfieldcode ne $itemtagsubfield));
791 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
792 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
793 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
794 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
795 $subfieldcode, $subfieldvalue, '', $tagslib)
796 || $subfieldvalue;
799 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
800 #verifying rights
801 my $userenv = C4::Context->userenv();
802 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
803 $this_row{'nomod'} = 1;
806 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
808 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
809 foreach my $hostitemnumber (@hostitemnumbers){
810 if ($this_row{itemnumber} eq $hostitemnumber){
811 $this_row{hostitemflag} = 1;
812 $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
813 last;
817 # my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
818 # if ($countanalytics > 0){
819 # $this_row{countanalytics} = $countanalytics;
824 if (%this_row) {
825 push(@big_array, \%this_row);
829 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
830 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
832 # now, construct template !
833 # First, the existing items for display
834 my @item_value_loop;
835 my @header_value_loop;
836 for my $row ( @big_array ) {
837 my %row_data;
838 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
839 $row_data{item_value} = [ @item_fields ];
840 $row_data{itemnumber} = $row->{itemnumber};
841 #reporting this_row values
842 $row_data{'nomod'} = $row->{'nomod'};
843 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
844 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
845 # $row_data{'countanalytics'} = $row->{'countanalytics'};
846 push(@item_value_loop,\%row_data);
848 foreach my $subfield_code (sort keys(%witness)) {
849 my %header_value;
850 $header_value{header_value} = $witness{$subfield_code};
852 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
853 my $kohafield = $subfieldlib->{kohafield};
854 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
855 $header_value{column_name} = $1;
858 push(@header_value_loop, \%header_value);
861 # now, build the item form for entering a new item
862 my @loop_data =();
863 my $i=0;
865 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
867 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
868 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
869 for my $library ( @$libraries ) {
870 $library->{selected} = 1 if $library->{branchcode} eq $branch
873 # We generate form, from actuel record
874 @fields = ();
875 if($itemrecord){
876 foreach my $field ($itemrecord->fields()){
877 my $tag = $field->{_tag};
878 foreach my $subfield ( $field->subfields() ){
880 my $subfieldtag = $subfield->[0];
881 my $value = $subfield->[1];
882 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
884 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
886 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
887 push @fields, "$tag$subfieldtag";
888 push (@loop_data, $subfield_data);
889 $i++;
894 # and now we add fields that are empty
896 # Using last created item if it exists
898 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
900 # We generate form, and fill with values if defined
901 foreach my $tag ( keys %{$tagslib}){
902 foreach my $subtag (keys %{$tagslib->{$tag}}){
903 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
904 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
905 next if any { /^$tag$subtag$/ } @fields;
907 my @values = (undef);
908 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
909 for my $value (@values){
910 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
911 push (@loop_data, $subfield_data);
912 $i++;
916 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
918 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
919 $template->param(
920 biblionumber => $biblionumber,
921 title => $oldrecord->{title},
922 author => $oldrecord->{author},
923 item_loop => \@item_value_loop,
924 item_header_loop => \@header_value_loop,
925 item => \@loop_data,
926 itemnumber => $itemnumber,
927 barcode => GetBarcodeFromItemnumber($itemnumber),
928 itemtagfield => $itemtagfield,
929 itemtagsubfield => $itemtagsubfield,
930 op => $nextop,
931 opisadd => ($nextop eq "saveitem") ? 0 : 1,
932 popup => scalar $input->param('popup') ? 1: 0,
933 C4::Search::enabled_staff_search_views,
935 $template->{'VARS'}->{'searchid'} = $searchid;
937 if ($frameworkcode eq 'FA'){
938 # fast cataloguing datas
939 $template->param(
940 'circborrowernumber' => $fa_circborrowernumber,
941 'barcode' => $fa_barcode,
942 'branch' => $fa_branch,
943 'stickyduedate' => $fa_stickyduedate,
944 'duedatespec' => $fa_duedatespec,
948 foreach my $error (@errors) {
949 $template->param($error => 1);
951 output_html_with_http_headers $input, $cookie, $template->output;