Bug 13987: Fix server name in z39.50 authority search results
[koha.git] / cataloguing / additem.pl
blob24c06917efc153410a1ff06879cfa00e825f5bd1
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; # 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;
41 use MARC::File::XML;
42 use URI::Escape;
44 our $dbh = C4::Context->dbh;
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);
59 return($indicator,$result);
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);
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);
80 else {
81 $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
82 ModItem( $item, undef, $itemnumber);
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);
102 return $record;
106 sub generate_subfield_form {
107 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $today_iso, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
109 my $frameworkcode = &GetFrameworkCode($biblionumber);
111 my %subfield_data;
112 my $dbh = C4::Context->dbh;
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;
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};
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;
138 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
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;
153 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
154 my $input = new CGI;
155 $value = $input->param('barcode');
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" );
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);
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
177 my $attributes = qq($attributes_no_value value="$value" );
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;
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;
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;
205 #---- class_sources
207 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
208 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
210 my $class_sources = GetClassSources();
211 my $default_source = C4::Context->preference("DefaultClassificationSource");
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'};
220 $value = $default_source unless ($value);
222 #---- "true" authorised value
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};
233 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
234 $subfield_data{marc_value} = qq(<input type="hidden" $attributes /> $authorised_lib{$value});
236 else {
237 my @scrparam = (
238 -name => "field_value",
239 -values => \@authorised_values,
240 -default => $value,
241 -labels => \%authorised_lib,
242 -override => 1,
243 -size => 1,
244 -multiple => 0,
245 -id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
246 -class => "input_marceditor",
249 # If we're on restricted editing, and our field is not in the list of subfields to allow,
250 # then it is read-only
251 push @scrparam, (-readonly => "readonly"), (-disabled => "disabled")
252 if (
253 not $allowAllSubfields
254 and $restrictededition
255 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
257 $subfield_data{marc_value} =CGI::scrolling_list(@scrparam);
261 # it's a thesaurus / authority field
262 elsif ( $subfieldlib->{authtypecode} ) {
263 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
264 <a href=\"#\" class=\"buttonDot\"
265 onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$subfieldlib->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
268 # it's a plugin field
269 elsif ( $subfieldlib->{value_builder} ) { # plugin
270 require Koha::FrameworkPlugin;
271 my $plugin = Koha::FrameworkPlugin->new({
272 name => $subfieldlib->{'value_builder'},
273 item_style => 1,
275 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
276 id => $subfield_data{id}, tabloop => $loop_data };
277 $plugin->build( $pars );
278 if( !$plugin->errstr ) {
279 #TODO Report 12176 will make this even better !
280 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
281 my $title= $plugin->noclick? 'No popup': 'Tag editor';
282 $subfield_data{marc_value} = qq[<input type="text" $attributes /><a href="#" id="buttonDot_$subfield_data{id}" class="$class" title="$title">...</a>\n].$plugin->javascript;
283 } else {
284 warn $plugin->errstr;
285 $subfield_data{marc_value} = "<input type=\"text\" $attributes />"; # supply default input form
288 elsif ( $tag eq '' ) { # it's an hidden field
289 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
291 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
292 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
294 elsif ( length($value) > 100
295 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
296 300 <= $tag && $tag < 400 && $subfieldtag eq 'a' )
297 or (C4::Context->preference("marcflavour") eq "MARC21" and
298 500 <= $tag && $tag < 600 )
300 # oversize field (textarea)
301 $subfield_data{marc_value} = "<textarea $attributes_no_value_textarea>$value</textarea>\n";
302 } else {
303 # it's a standard field
304 $subfield_data{marc_value} = "<input type=\"text\" $attributes />";
307 return \%subfield_data;
310 # Removes some subfields when prefilling items
311 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
312 sub removeFieldsForPrefill {
314 my $item = shift;
316 # Getting item tag
317 my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
319 # Getting list of subfields to keep
320 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
322 # Removing subfields that are not in the syspref
323 if ($tag && $subfieldsToUseWhenPrefill) {
324 my $field = $item->field($tag);
325 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
326 foreach my $subfield ($field->subfields()) {
327 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
328 $field->delete_subfield(code => $subfield->[0]);
334 return $item;
338 my $input = new CGI;
339 my $error = $input->param('error');
340 my $biblionumber = $input->param('biblionumber');
341 my $itemnumber = $input->param('itemnumber');
342 my $op = $input->param('op');
343 my $hostitemnumber = $input->param('hostitemnumber');
344 my $marcflavour = C4::Context->preference("marcflavour");
345 my $searchid = $input->param('searchid');
346 # fast cataloguing datas
347 my $fa_circborrowernumber = $input->param('circborrowernumber');
348 my $fa_barcode = $input->param('barcode');
349 my $fa_branch = $input->param('branch');
350 my $fa_stickyduedate = $input->param('stickyduedate');
351 my $fa_duedatespec = $input->param('duedatespec');
353 my $frameworkcode = &GetFrameworkCode($biblionumber);
355 # Defining which userflag is needing according to the framework currently used
356 my $userflags;
357 if (defined $input->param('frameworkcode')) {
358 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
361 if (not defined $userflags) {
362 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
365 my ($template, $loggedinuser, $cookie)
366 = get_template_and_user({template_name => "cataloguing/additem.tt",
367 query => $input,
368 type => "intranet",
369 authnotrequired => 0,
370 flagsrequired => {editcatalogue => $userflags},
371 debug => 1,
375 # Does the user have a restricted item editing permission?
376 my $uid = $loggedinuser ? GetMember( borrowernumber => $loggedinuser )->{userid} : undef;
377 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
378 # In case user is a superlibrarian, editing is not restricted
379 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
380 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
381 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
383 my $today_iso = C4::Dates->today('iso');
384 my $tagslib = &GetMarcStructure(1,$frameworkcode);
385 my $record = GetMarcBiblio($biblionumber);
386 my $oldrecord = TransformMarcToKoha($dbh,$record);
387 my $itemrecord;
388 my $nextop="additem";
389 my @errors; # store errors found while checking data BEFORE saving item.
391 # Getting last created item cookie
392 my $prefillitem = C4::Context->preference('PrefillItem');
393 my $justaddeditem;
394 my $cookieitemrecord;
395 if ($prefillitem) {
396 my $lastitemcookie = $input->cookie('LastCreatedItem');
397 if ($lastitemcookie) {
398 $lastitemcookie = uri_unescape($lastitemcookie);
399 if ( thaw($lastitemcookie) ) {
400 $cookieitemrecord = thaw($lastitemcookie) ;
401 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
406 #-------------------------------------------------------------------------------
407 if ($op eq "additem") {
409 #-------------------------------------------------------------------------------
410 # rebuild
411 my @tags = $input->param('tag');
412 my @subfields = $input->param('subfield');
413 my @values = $input->param('field_value');
414 # build indicator hash.
415 my @ind_tag = $input->param('ind_tag');
416 my @indicator = $input->param('indicator');
417 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
418 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
420 # type of add
421 my $add_submit = $input->param('add_submit');
422 my $add_duplicate_submit = $input->param('add_duplicate_submit');
423 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
424 my $number_of_copies = $input->param('number_of_copies');
426 # This is a bit tricky : if there is a cookie for the last created item and
427 # we just added an item, the cookie value is not correct yet (it will be updated
428 # next page). To prevent the form from being filled with outdated values, we
429 # force the use of "add and duplicate" feature, so the form will be filled with
430 # correct values.
431 $add_duplicate_submit = 1 if ($prefillitem);
432 $justaddeditem = 1;
434 # if autoBarcode is set to 'incremental', calculate barcode...
435 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
436 $record = _increment_barcode($record, $frameworkcode);
439 my $addedolditem = TransformMarcToKoha( $dbh, $record );
441 # If we have to add or add & duplicate, we add the item
442 if ( $add_submit || $add_duplicate_submit ) {
444 # check for item barcode # being unique
445 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
446 push @errors, "barcode_not_unique" if ($exist_itemnumber);
448 # if barcode exists, don't create, but report The problem.
449 unless ($exist_itemnumber) {
450 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
451 set_item_default_location($oldbibitemnum);
453 # Pushing the last created item cookie back
454 if ($prefillitem && defined $record) {
455 my $itemcookie = $input->cookie(
456 -name => 'LastCreatedItem',
457 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
458 -value => uri_escape_utf8( freeze( $record ) ),
459 -HttpOnly => 1,
460 -expires => ''
463 $cookie = [ $cookie, $itemcookie ];
467 $nextop = "additem";
468 if ($exist_itemnumber) {
469 $itemrecord = $record;
473 # If we have to add & duplicate
474 if ($add_duplicate_submit) {
475 $itemrecord = $record;
476 if (C4::Context->preference('autoBarcode') eq 'incremental') {
477 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
479 else {
480 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
481 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
482 my $fieldItem = $itemrecord->field($tagfield);
483 $itemrecord->delete_field($fieldItem);
484 $fieldItem->delete_subfields($tagsubfield);
485 $itemrecord->insert_fields_ordered($fieldItem);
487 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
490 # If we have to add multiple copies
491 if ($add_multiple_copies_submit) {
493 use C4::Barcodes;
494 my $barcodeobj = C4::Barcodes->new;
495 my $oldbarcode = $addedolditem->{'barcode'};
496 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
498 # If there is a barcode and we can't find him new values, we can't add multiple copies
499 my $testbarcode;
500 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
501 if ($oldbarcode && !$testbarcode) {
503 push @errors, "no_next_barcode";
504 $itemrecord = $record;
506 } else {
507 # We add each item
509 # For the first iteration
510 my $barcodevalue = $oldbarcode;
511 my $exist_itemnumber;
514 for (my $i = 0; $i < $number_of_copies;) {
516 # If there is a barcode
517 if ($barcodevalue) {
519 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
520 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
522 # Putting it into the record
523 if ($barcodevalue) {
524 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
527 # Checking if the barcode already exists
528 $exist_itemnumber = get_item_from_barcode($barcodevalue);
531 # Adding the item
532 if (!$exist_itemnumber) {
533 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
534 set_item_default_location($oldbibitemnum);
536 # We count the item only if it was really added
537 # That way, all items are added, even if there was some already existing barcodes
538 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
539 $i++;
542 # Preparing the next iteration
543 $oldbarcode = $barcodevalue;
545 undef($itemrecord);
548 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
549 print $input->redirect(
550 '/cgi-bin/koha/circ/circulation.pl?'
551 .'borrowernumber='.$fa_circborrowernumber
552 .'&barcode='.uri_escape_utf8($fa_barcode)
553 .'&duedatespec='.$fa_duedatespec
554 .'&stickyduedate=1'
556 exit;
560 #-------------------------------------------------------------------------------
561 } elsif ($op eq "edititem") {
562 #-------------------------------------------------------------------------------
563 # retrieve item if exist => then, it's a modif
564 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
565 $nextop = "saveitem";
566 #-------------------------------------------------------------------------------
567 } elsif ($op eq "delitem") {
568 #-------------------------------------------------------------------------------
569 # check that there is no issue on this item before deletion.
570 $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
571 if($error == 1){
572 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
573 }else{
574 push @errors,$error;
575 $nextop="additem";
577 #-------------------------------------------------------------------------------
578 } elsif ($op eq "delallitems") {
579 #-------------------------------------------------------------------------------
580 my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
581 my $errortest=0;
582 my $itemfail;
583 foreach my $biblioitem (@biblioitems) {
584 my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
586 foreach my $item (@$items) {
587 $error =&DelItemCheck( $dbh, $biblionumber, $item->{itemnumber} );
588 $itemfail =$item;
589 if($error == 1){
590 next
592 else {
593 push @errors,$error;
594 $errortest++
597 if($errortest > 0){
598 $nextop="additem";
600 else {
601 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
602 my $views = { C4::Search::enabled_staff_search_views };
603 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
604 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
605 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
606 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
607 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
608 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
609 } else {
610 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
612 exit;
615 #-------------------------------------------------------------------------------
616 } elsif ($op eq "saveitem") {
617 #-------------------------------------------------------------------------------
618 # rebuild
619 my @tags = $input->param('tag');
620 my @subfields = $input->param('subfield');
621 my @values = $input->param('field_value');
622 # build indicator hash.
623 my @ind_tag = $input->param('ind_tag');
624 my @indicator = $input->param('indicator');
625 # my $itemnumber = $input->param('itemnumber');
626 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
627 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
628 # MARC::Record builded => now, record in DB
629 # warn "R: ".$record->as_formatted;
630 # check that the barcode don't exist already
631 my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
632 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
633 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
634 push @errors,"barcode_not_unique";
635 } else {
636 ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
637 $itemnumber="";
639 my $item = GetItem( $itemnumber );
640 my $olditemlost = $item->{'itemlost'};
642 my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
644 my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
645 if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
646 LostItem($itemnumber,'MARK RETURNED');
648 $nextop="additem";
649 } elsif ($op eq "delinkitem"){
650 my $analyticfield = '773';
651 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
652 $analyticfield = '773';
653 } elsif ($marcflavour eq 'UNIMARC') {
654 $analyticfield = '461';
656 foreach my $field ($record->field($analyticfield)){
657 if ($field->subfield('9') eq $hostitemnumber){
658 $record->delete_field($field);
659 last;
662 my $modbibresult = ModBiblio($record, $biblionumber,'');
666 #-------------------------------------------------------------------------------
667 # build screen with existing items. and "new" one
668 #-------------------------------------------------------------------------------
670 # now, build existiing item list
671 my $temp = GetMarcBiblio( $biblionumber );
672 #my @fields = $record->fields();
675 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
676 my @big_array;
677 #---- finds where items.itemnumber is stored
678 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
679 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
680 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
681 my @fields = $temp->fields();
684 my @hostitemnumbers;
685 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
686 my $analyticfield = '773';
687 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
688 $analyticfield = '773';
689 } elsif ($marcflavour eq 'UNIMARC') {
690 $analyticfield = '461';
692 foreach my $hostfield ($temp->field($analyticfield)){
693 my $hostbiblionumber = $hostfield->subfield('0');
694 if ($hostbiblionumber){
695 my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
696 if ($hostrecord) {
697 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
698 foreach my $hostitem ($hostrecord->field($itemfield)){
699 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
700 push (@fields, $hostitem);
701 push (@hostitemnumbers, $hostfield->subfield('9'));
710 foreach my $field (@fields) {
711 next if ( $field->tag() < 10 );
713 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
714 my %this_row;
715 # loop through each subfield
716 my $i = 0;
717 foreach my $subfield (@subf){
718 my $subfieldcode = $subfield->[0];
719 my $subfieldvalue= $subfield->[1];
721 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
722 && ($field->tag() ne $itemtagfield
723 && $subfieldcode ne $itemtagsubfield));
724 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
725 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
726 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
727 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
728 $subfieldcode, $subfieldvalue, '', $tagslib)
729 || $subfieldvalue;
732 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
733 #verifying rights
734 my $userenv = C4::Context->userenv();
735 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
736 $this_row{'nomod'} = 1;
739 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
741 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
742 foreach my $hostitemnumber (@hostitemnumbers){
743 if ($this_row{itemnumber} eq $hostitemnumber){
744 $this_row{hostitemflag} = 1;
745 $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
746 last;
750 # my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
751 # if ($countanalytics > 0){
752 # $this_row{countanalytics} = $countanalytics;
757 if (%this_row) {
758 push(@big_array, \%this_row);
762 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
763 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
765 # now, construct template !
766 # First, the existing items for display
767 my @item_value_loop;
768 my @header_value_loop;
769 for my $row ( @big_array ) {
770 my %row_data;
771 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
772 $row_data{item_value} = [ @item_fields ];
773 $row_data{itemnumber} = $row->{itemnumber};
774 #reporting this_row values
775 $row_data{'nomod'} = $row->{'nomod'};
776 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
777 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
778 # $row_data{'countanalytics'} = $row->{'countanalytics'};
779 push(@item_value_loop,\%row_data);
781 foreach my $subfield_code (sort keys(%witness)) {
782 my %header_value;
783 $header_value{header_value} = $witness{$subfield_code};
784 push(@header_value_loop, \%header_value);
787 # now, build the item form for entering a new item
788 my @loop_data =();
789 my $i=0;
791 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
793 my $onlymine =
794 C4::Context->preference('IndependentBranches')
795 && C4::Context->userenv
796 && !C4::Context->IsSuperLibrarian()
797 && C4::Context->userenv->{branch};
798 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
799 my $branches = GetBranchesLoop($branch,$onlymine); # build once ahead of time, instead of multiple times later.
801 # We generate form, from actuel record
802 @fields = ();
803 if($itemrecord){
804 foreach my $field ($itemrecord->fields()){
805 my $tag = $field->{_tag};
806 foreach my $subfield ( $field->subfields() ){
808 my $subfieldtag = $subfield->[0];
809 my $value = $subfield->[1];
810 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
812 next if subfield_is_koha_internal_p($subfieldtag);
813 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
815 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
816 push @fields, "$tag$subfieldtag";
817 push (@loop_data, $subfield_data);
818 $i++;
823 # and now we add fields that are empty
825 # Using last created item if it exists
827 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
829 # We generate form, and fill with values if defined
830 foreach my $tag ( keys %{$tagslib}){
831 foreach my $subtag (keys %{$tagslib->{$tag}}){
832 next if subfield_is_koha_internal_p($subtag);
833 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
834 next if any { /^$tag$subtag$/ } @fields;
836 my @values = (undef);
837 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
838 for my $value (@values){
839 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
840 push (@loop_data, $subfield_data);
841 $i++;
845 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
847 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
848 $template->param(
849 biblionumber => $biblionumber,
850 title => $oldrecord->{title},
851 author => $oldrecord->{author},
852 item_loop => \@item_value_loop,
853 item_header_loop => \@header_value_loop,
854 item => \@loop_data,
855 itemnumber => $itemnumber,
856 barcode => GetBarcodeFromItemnumber($itemnumber),
857 itemtagfield => $itemtagfield,
858 itemtagsubfield => $itemtagsubfield,
859 op => $nextop,
860 opisadd => ($nextop eq "saveitem") ? 0 : 1,
861 popup => $input->param('popup') ? 1: 0,
862 C4::Search::enabled_staff_search_views,
864 $template->{'VARS'}->{'searchid'} = $searchid;
866 if ($frameworkcode eq 'FA'){
867 # fast cataloguing datas
868 $template->param(
869 'circborrowernumber' => $fa_circborrowernumber,
870 'barcode' => $fa_barcode,
871 'branch' => $fa_branch,
872 'stickyduedate' => $fa_stickyduedate,
873 'duedatespec' => $fa_duedatespec,
877 foreach my $error (@errors) {
878 $template->param($error => 1);
880 output_html_with_http_headers $input, $cookie, $template->output;